@indigoai-us/hq-cli 5.345.251 → 5.345.253

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 (188) hide show
  1. package/CHANGELOG.md +153 -0
  2. package/assets/scaffold/core/scripts/hq-session.sh +9 -0
  3. package/contracts/host-canary-release.json +9 -3
  4. package/dist/command-catalog.generated.d.ts +269 -1
  5. package/dist/command-catalog.generated.js +330 -1
  6. package/dist/command-registration-plan.d.ts +6 -0
  7. package/dist/command-registration-plan.js +1 -0
  8. package/dist/commands/bot.js +7 -2
  9. package/dist/commands/ci-intake.d.ts +15 -0
  10. package/dist/commands/ci-intake.js +252 -0
  11. package/dist/commands/ci-metrics.d.ts +8 -0
  12. package/dist/commands/ci-metrics.js +55 -0
  13. package/dist/commands/ci.d.ts +13 -0
  14. package/dist/commands/ci.js +10 -0
  15. package/dist/commands/core-bucket-c-work-mesh-offer-native.js +1 -1
  16. package/dist/commands/core-hq-session-binding.d.ts +140 -0
  17. package/dist/commands/core-hq-session-binding.js +363 -0
  18. package/dist/commands/core-hq-session-native.d.ts +23 -0
  19. package/dist/commands/core-hq-session-native.js +59 -9
  20. package/dist/commands/core-stop-autosave.js +1 -1
  21. package/dist/commands/core.js +10 -0
  22. package/dist/commands/doctor.d.ts +5 -1
  23. package/dist/commands/doctor.js +42 -5
  24. package/dist/commands/files.d.ts +62 -0
  25. package/dist/commands/files.js +250 -9
  26. package/dist/commands/install-global.js +4 -2
  27. package/dist/commands/logout.js +4 -0
  28. package/dist/commands/ontology-graph.d.ts +2 -0
  29. package/dist/commands/ontology-graph.js +33 -0
  30. package/dist/commands/report.js +35 -2
  31. package/dist/commands/storage-gate.js +1 -1
  32. package/dist/commands/vault-retention-flag.js +2 -1
  33. package/dist/commands/whoami.js +1 -1
  34. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +238 -221
  35. package/dist/hq-cloud-sync-runner/package.json +1 -1
  36. package/dist/index.js +3 -1
  37. package/dist/lib/agent-kit/inbox-poll-backoff-flag.js +1 -1
  38. package/dist/lib/agent-kit/mcp/tools.js +48 -0
  39. package/dist/lib/bot/fleet-bots-update-pass.js +1 -1
  40. package/dist/lib/bot/fleet-cron.d.ts +50 -0
  41. package/dist/lib/bot/fleet-cron.js +173 -32
  42. package/dist/lib/bot/fleet-local.d.ts +18 -0
  43. package/dist/lib/bot/fleet-local.js +51 -5
  44. package/dist/lib/bot/inbox-poll-backoff-flag.js +1 -1
  45. package/dist/lib/bot/signals-engine-flag.d.ts +1 -1
  46. package/dist/lib/bot/signals-engine-flag.js +1 -1
  47. package/dist/lib/cli-invite-nudge.js +1 -1
  48. package/dist/lib/client-version.d.ts +2 -0
  49. package/dist/lib/client-version.js +24 -0
  50. package/dist/lib/company-flag-gate.d.ts +30 -0
  51. package/dist/lib/company-flag-gate.js +104 -0
  52. package/dist/lib/core-utils/hook-timeout-debug-context-flag.js +1 -1
  53. package/dist/lib/daemon/flag.js +2 -1
  54. package/dist/lib/daemon/legacy-journal-gate.js +3 -1
  55. package/dist/lib/daemon/run.js +4 -3
  56. package/dist/lib/daemon/shared-flag-reads.js +1 -1
  57. package/dist/lib/delivery/migrations.d.ts +32 -1
  58. package/dist/lib/delivery/migrations.js +69 -8
  59. package/dist/lib/doctor/checks/host-core.js +22 -4
  60. package/dist/lib/doctor/checks/jq.d.ts +27 -6
  61. package/dist/lib/doctor/checks/jq.js +46 -8
  62. package/dist/lib/doctor/client-health-reason-codes-flag.js +1 -1
  63. package/dist/lib/doctor/fix/refresh-sync-handoff.d.ts +1 -1
  64. package/dist/lib/doctor/fix/refresh-sync-handoff.js +1 -1
  65. package/dist/lib/flag-client-gate-headers.d.ts +38 -0
  66. package/dist/lib/flag-client-gate-headers.js +62 -0
  67. package/dist/lib/flag-client-headers.d.ts +15 -0
  68. package/dist/lib/flag-client-headers.js +25 -0
  69. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  70. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  71. package/dist/lib/flag-registry-worker.js +35 -0
  72. package/dist/lib/flag-registry.d.ts +1 -20
  73. package/dist/lib/flag-registry.js +5 -81
  74. package/dist/lib/hook-engine/adapter-core-pin.d.ts +30 -0
  75. package/dist/lib/hook-engine/adapter-core-pin.js +30 -0
  76. package/dist/lib/hook-engine/coverage.d.ts +65 -1
  77. package/dist/lib/hook-engine/coverage.js +173 -8
  78. package/dist/lib/hook-engine/reconcile.js +3 -2
  79. package/dist/lib/hot-channels/prompts/signals-pass.md +20 -0
  80. package/dist/lib/hot-channels/signal-changes.d.ts +228 -0
  81. package/dist/lib/hot-channels/signal-changes.js +683 -0
  82. package/dist/lib/hot-channels/signals-pass.d.ts +24 -0
  83. package/dist/lib/hot-channels/signals-pass.js +232 -12
  84. package/dist/lib/lanes/outpost-worktree-pruner-flag.d.ts +1 -1
  85. package/dist/lib/lanes/outpost-worktree-pruner-flag.js +1 -1
  86. package/dist/lib/lanes/registry-flag.js +2 -1
  87. package/dist/lib/lanes/spawn.js +11 -1
  88. package/dist/lib/mesh/live/binding-intent.d.ts +61 -0
  89. package/dist/lib/mesh/live/binding-intent.js +201 -0
  90. package/dist/lib/mesh/live/binding-receipt.d.ts +157 -0
  91. package/dist/lib/mesh/live/binding-receipt.js +365 -0
  92. package/dist/lib/mesh/live/company-flag-refresh.js +1 -1
  93. package/dist/lib/mesh/live/daemon/doctor-telemetry.d.ts +39 -0
  94. package/dist/lib/mesh/live/daemon/doctor-telemetry.js +58 -0
  95. package/dist/lib/mesh/live/daemon/install.js +2 -1
  96. package/dist/lib/mesh/live/daemon/presence.js +9 -0
  97. package/dist/lib/mesh/live/daemon/run.d.ts +3 -0
  98. package/dist/lib/mesh/live/daemon/run.js +33 -1
  99. package/dist/lib/ontology-graph/lineage/index.d.ts +401 -0
  100. package/dist/lib/ontology-graph/lineage/index.js +1027 -0
  101. package/dist/lib/ontology-graph/model/index.d.ts +54 -0
  102. package/dist/lib/ontology-graph/model/index.js +112 -0
  103. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +75 -0
  104. package/dist/lib/ontology-graph/model/pass-tasks.js +166 -0
  105. package/dist/lib/ontology-graph/model/pass.d.ts +6 -0
  106. package/dist/lib/ontology-graph/model/pass.js +9 -2
  107. package/dist/lib/ontology-graph/model/pending-items.d.ts +8 -0
  108. package/dist/lib/ontology-graph/model/pending-items.js +24 -1
  109. package/dist/lib/ontology-graph/model/step.d.ts +1 -1
  110. package/dist/lib/ontology-graph/model/tasks.d.ts +11 -3
  111. package/dist/lib/ontology-graph/model/tasks.js +20 -7
  112. package/dist/lib/ontology-graph/read/brief.js +41 -6
  113. package/dist/lib/ontology-graph/read/index.d.ts +4 -0
  114. package/dist/lib/ontology-graph/read/index.js +173 -29
  115. package/dist/lib/ontology-graph/read/lineage.d.ts +101 -0
  116. package/dist/lib/ontology-graph/read/lineage.js +262 -0
  117. package/dist/lib/ontology-graph/replay/buffered-store.js +17 -0
  118. package/dist/lib/ontology-graph/replay/engine.d.ts +32 -1
  119. package/dist/lib/ontology-graph/replay/engine.js +213 -8
  120. package/dist/lib/ontology-graph/replay/extractors.d.ts +26 -0
  121. package/dist/lib/ontology-graph/replay/extractors.js +25 -1
  122. package/dist/lib/ontology-graph/replay/index.d.ts +2 -0
  123. package/dist/lib/ontology-graph/replay/index.js +9 -3
  124. package/dist/lib/ontology-graph/replay/signal-changes.d.ts +118 -0
  125. package/dist/lib/ontology-graph/replay/signal-changes.js +687 -0
  126. package/dist/lib/ontology-graph/schema/decision-status.d.ts +18 -0
  127. package/dist/lib/ontology-graph/schema/decision-status.js +20 -0
  128. package/dist/lib/ontology-graph/schema/index.d.ts +1 -0
  129. package/dist/lib/ontology-graph/schema/index.js +1 -0
  130. package/dist/lib/ontology-graph/setup/index.js +13 -3
  131. package/dist/lib/search-index/index.d.ts +33 -1
  132. package/dist/lib/search-index/index.js +180 -25
  133. package/dist/lib/search-index/qmd-exit-diagnostics.d.ts +7 -0
  134. package/dist/lib/search-index/qmd-exit-diagnostics.js +25 -1
  135. package/dist/lib/signals/adapters-catalog.js +1 -1
  136. package/dist/lib/smart-ci/cost.d.ts +72 -0
  137. package/dist/lib/smart-ci/cost.js +120 -0
  138. package/dist/lib/smart-ci/github.d.ts +112 -0
  139. package/dist/lib/smart-ci/github.js +267 -0
  140. package/dist/lib/smart-ci/intake.d.ts +288 -0
  141. package/dist/lib/smart-ci/intake.js +1078 -0
  142. package/dist/lib/smart-ci/ledger.d.ts +218 -0
  143. package/dist/lib/smart-ci/ledger.js +527 -0
  144. package/dist/lib/smart-ci/metrics.d.ts +137 -0
  145. package/dist/lib/smart-ci/metrics.js +249 -0
  146. package/dist/lib/smart-ci/records.d.ts +265 -0
  147. package/dist/lib/smart-ci/records.js +281 -0
  148. package/dist/lib/smart-ci/reducer.d.ts +67 -0
  149. package/dist/lib/smart-ci/reducer.js +261 -0
  150. package/dist/lib/sync-core/engine-holds.d.ts +15 -0
  151. package/dist/lib/sync-core/engine-holds.js +104 -11
  152. package/dist/lib/sync-core/engine-home.d.ts +3 -0
  153. package/dist/lib/sync-core/engine-home.js +41 -1
  154. package/dist/lib/sync-core/flag.js +2 -1
  155. package/dist/lib/sync-core/hand-back.d.ts +1 -0
  156. package/dist/lib/sync-core/hand-back.js +7 -2
  157. package/dist/lib/sync-core/legacy-journal-export-child.js +5 -3
  158. package/dist/lib/sync-core/legacy-journal-export.d.ts +23 -4
  159. package/dist/lib/sync-core/legacy-journal-export.js +120 -55
  160. package/dist/lib/sync-core/reconcile.d.ts +2 -1
  161. package/dist/lib/sync-core/reconcile.js +40 -7
  162. package/dist/lib/sync-invalid-entity-warning.js +2 -1
  163. package/dist/lib/windows/install-followup.d.ts +41 -0
  164. package/dist/lib/windows/install-followup.js +87 -0
  165. package/dist/lib/windows/jq.d.ts +59 -0
  166. package/dist/lib/windows/jq.js +154 -3
  167. package/dist/lib/windows/user-path.d.ts +5 -0
  168. package/dist/lib/windows/user-path.js +1 -1
  169. package/dist/lib/work-context/auto-bind.d.ts +12 -0
  170. package/dist/lib/work-context/auto-bind.js +49 -3
  171. package/dist/lib/work-context/organize.d.ts +4 -2
  172. package/dist/lib/work-context/organize.js +18 -8
  173. package/dist/lib/work-context/reconcile.js +16 -1
  174. package/dist/main.js +12 -1
  175. package/dist/utils/client-health-contract.d.ts +30 -0
  176. package/dist/utils/client-health-contract.js +111 -0
  177. package/dist/utils/client-health.d.ts +5 -2
  178. package/dist/utils/client-health.js +74 -5
  179. package/dist/utils/exclusive-lock.d.ts +5 -1
  180. package/dist/utils/exclusive-lock.js +9 -2
  181. package/dist/utils/host-registration.d.ts +7 -0
  182. package/dist/utils/host-registration.js +10 -1
  183. package/dist/utils/pid.d.ts +31 -0
  184. package/dist/utils/pid.js +65 -0
  185. package/dist/utils/resident-package-preload.js +12 -4
  186. package/dist/utils/sentry-fingerprint.js +3 -0
  187. package/package.json +10 -8
  188. package/scripts/install-hook-engine.mjs +5 -3
@@ -1 +1 @@
1
- {"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.122","bundleSha256":"b8fdfeffdf3169c9c27d4eaf2dd3ce730b2f1e20f5ada5aacaa0217ddeecc72e","formatVersion":1}
1
+ {"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.124","bundleSha256":"98bb542b595ecef200dd72eb1d25a8b741d7df41a0d7afd06241e553d6eefe12","formatVersion":1}
package/dist/index.js CHANGED
@@ -341,13 +341,15 @@ export function stableHealWouldRun(argv, env, platform, home = homedir()) {
341
341
  function dispatchInstallFollowupThenCommand(versionRequest, helpRequest, parsedFastCore, monitorRequest, secretsRequest, mcpRequest) {
342
342
  if (!versionRequest && !monitorRequest && !parsedFastCore && !secretsRequest && !mcpRequest
343
343
  && installFollowupWouldDoWork(process.argv, process.env, process.platform)) {
344
- void import("./lib/windows/install-followup.js").then(({ runWindowsInstallFollowup }) => {
344
+ void import("./lib/windows/install-followup.js").then(async ({ runWindowsInstallFollowup, runWindowsJqFollowup }) => {
345
345
  try {
346
346
  runWindowsInstallFollowup({ argv: process.argv });
347
347
  }
348
348
  catch {
349
349
  // Install repair must not turn into a failed command.
350
350
  }
351
+ // Windows only, and it never rejects: the jq HQ hooks need (hq-cli #3716).
352
+ await runWindowsJqFollowup({ argv: process.argv });
351
353
  }).catch(() => undefined).then(() => {
352
354
  dispatchCliCommand(versionRequest, helpRequest, parsedFastCore, monitorRequest, secretsRequest, mcpRequest);
353
355
  });
@@ -1,4 +1,4 @@
1
- import { createFlagClient, } from "@indigoai-us/hq-flags-client";
1
+ import { createHqFlagClient as createFlagClient } from "../flag-client-headers.js";
2
2
  import { resolveFlagGate } from "../flag-registry.js";
3
3
  import { resolveFlagRegistryEndpoint } from "../flag-registry-endpoint.js";
4
4
  export const AGENT_KIT_INBOX_BACKOFF_FLAG = "agents.inbox-poll-backoff-agent-kit";
@@ -15,6 +15,7 @@
15
15
  * never a secret value. `hq_secrets_list` names secrets; values are never a
16
16
  * tool result.
17
17
  */
18
+ import { createHash, randomUUID } from "node:crypto";
18
19
  import { CLI_VERSION } from "../../../cli-version.js";
19
20
  import { peekIdToken } from "../../../utils/id-token.js";
20
21
  import { PERSON_AGENT_AUDIENCE_MESSAGE, callerMayUseAudience, defaultAudienceFor, isAgentUid, isRecipientUid } from "../../../lib/notify-recipient.js";
@@ -84,6 +85,11 @@ function fromRun(r, label) {
84
85
  export function buildAgentMcpTools(clients) {
85
86
  const { creds } = clients;
86
87
  const company = creds.companySlug;
88
+ // Idempotency keys of agent DMs the loop check held, by recipient and
89
+ // message, so the continueExchange resend reuses the held message's key
90
+ // (one dispatch identity) instead of minting a new one. Bounded; oldest first out.
91
+ const heldDmKeys = new Map();
92
+ const heldDmKey = (to, message) => createHash("sha256").update(JSON.stringify([to, message])).digest("hex");
87
93
  /** Bounded, once-retried ack of one inbox id, under one batch deadline (feedback 3e376c49). */
88
94
  const inboxAckDeps = () => ({
89
95
  timeoutMs: resolveAgentInboxTimeoutMs(process.env),
@@ -239,6 +245,14 @@ export function buildAgentMcpTools(clients) {
239
245
  to: { type: "string", description: "Email, prs_… or agt_… uid, or a chn_… channel id" },
240
246
  message: { type: "string" },
241
247
  audience: { type: "string", enum: ["human", "agent", "both"], description: "Who this message is for (default: human for a person, agent for an agent, channel or group)" },
248
+ continueExchange: {
249
+ type: "boolean",
250
+ description: "Agent recipients (agt_…) only. Use it only after a send to this agent came back paused by the agent-to-agent loop check, " +
251
+ "and only if your last messages asked for or delivered specific work that is not finished yet. " +
252
+ "If the recent messages are thanks, acknowledgments, greetings or status echoes, stop: do not resend and do not reply. " +
253
+ "If you are unsure, ask your owner instead. To continue, resend the same message once with continueExchange: true; " +
254
+ "set it on that one resend only, never on a first send.",
255
+ },
242
256
  },
243
257
  required: ["to", "message"],
244
258
  additionalProperties: false,
@@ -250,6 +264,13 @@ export function buildAgentMcpTools(clients) {
250
264
  if (audience !== undefined && !["human", "agent", "both"].includes(audience)) {
251
265
  throw new McpToolInputError('"audience" must be human, agent, or both');
252
266
  }
267
+ const continueExchange = args.continueExchange;
268
+ if (continueExchange !== undefined && typeof continueExchange !== "boolean") {
269
+ throw new McpToolInputError('"continueExchange" must be true or false');
270
+ }
271
+ if (continueExchange === true && !isAgentUid(to)) {
272
+ throw new McpToolInputError('"continueExchange" applies only to an agent recipient (agt_…)');
273
+ }
253
274
  // The token decides who is sending. Normally the agent's machine
254
275
  // identity; if it ever resolves to a person login, people only send
255
276
  // human messages, so refuse agent/both before any send.
@@ -278,6 +299,13 @@ export function buildAgentMcpTools(clients) {
278
299
  throw new McpToolInputError('"to" must be an email, prs_… or agt_… uid, or a chn_… channel id');
279
300
  })();
280
301
  body.audience = audience ?? defaultAudienceFor(isAgentUid(to) ? "agent" : "person", machineCaller);
302
+ // One idempotency key per agent DM; a continue reuses the held send's key.
303
+ const heldKey = isAgentUid(to) ? heldDmKey(to, message) : undefined;
304
+ if (heldKey)
305
+ body.idempotencyKey = (continueExchange === true && heldDmKeys.get(heldKey)) || randomUUID();
306
+ // The sender's answer to the server's loop check (hq-pro-core 1.182.0+).
307
+ if (continueExchange === true)
308
+ body.continueExchange = true;
281
309
  const res = await clients.apiJson(token, "/v1/notify/dm", { method: "POST", body });
282
310
  if (res.status < 200 || res.status >= 300) {
283
311
  return errorResult(`DM send failed (${res.status}): ${describeError(res.body)}`);
@@ -286,8 +314,28 @@ export function buildAgentMcpTools(clients) {
286
314
  // is stored (200) but never reaches the recipient. Say so plainly
287
315
  // instead of "sent", so the agent does not assume it was delivered.
288
316
  const held = heldDeliveryNotice(res.body);
317
+ if (heldKey) {
318
+ heldDmKeys.delete(heldKey);
319
+ if (held) {
320
+ heldDmKeys.set(heldKey, String(body.idempotencyKey));
321
+ while (heldDmKeys.size > 100)
322
+ heldDmKeys.delete(heldDmKeys.keys().next().value);
323
+ }
324
+ }
325
+ if (held && continueExchange === true) {
326
+ // The agent already answered the check with continueExchange. Do not
327
+ // pass on the server's "To continue, resend…" hint: that would invite
328
+ // another resend. Only the reason code goes with the stop.
329
+ const b = res.body;
330
+ const reason = typeof b.heldReason === "string" && b.heldReason ? ` (${b.heldReason})` : "";
331
+ return textResult(`STOP: held, NOT delivered to ${to}; you already set continueExchange, so stop. ` +
332
+ `Do not resend it and do not reply to ${to}; tell your owner if the work is still needed.${reason}`);
333
+ }
289
334
  if (held)
290
335
  return textResult(`WARNING: saved but NOT delivered to ${to}. ${held}`);
336
+ if (res.body && typeof res.body === "object" && res.body.exchangeContinued === true) {
337
+ return textResult(`sent to ${to} (continued the exchange: a new batch of agent-to-agent DMs started)`);
338
+ }
291
339
  return textResult(`sent to ${to}`);
292
340
  },
293
341
  },
@@ -32,7 +32,7 @@ export async function runInstalledFleetBotsUpdate(log) {
32
32
  },
33
33
  heldForPromotion: (b) => hasPromotionHold(b.dir),
34
34
  needsAdoption: (b, release) => local.fleetLocalProfileNeedsAdoption(b.config.agentUid, { release }),
35
- busy: (b) => local.fleetLocalBusyReason(b.config.agentUid),
35
+ busy: (b) => local.fleetLocalBusyReason(b.config.agentUid, { warn: (message) => log(`${b.name}: ${message}`) }),
36
36
  update: (b) => bot.updateFleetRuntimeBot(b.name, { busy: () => local.fleetLocalBusyReason(b.config.agentUid) }),
37
37
  log,
38
38
  });
@@ -1,5 +1,6 @@
1
1
  import { type BotConfig } from "./config.js";
2
2
  import { type FleetLocalControlDeps } from "./fleet-local.js";
3
+ import { type LocalJob } from "./local-jobs.js";
3
4
  export interface FleetCronSchedule {
4
5
  kind?: string;
5
6
  expr?: string;
@@ -61,10 +62,44 @@ export declare function runFleetCronRequest(agentUid: string, request: Record<st
61
62
  export declare function fleetCronOps(agentUid: string, deps?: FleetCronDeps): FleetCronOps;
62
63
  export declare function fleetOwnerOrigin(ownerUid: string, jobs?: readonly FleetCronJob[]): FleetCronOrigin;
63
64
  export declare function fleetScheduleFromLegacy(expr: string): string;
65
+ /** A legacy job's schedule in a form the HQ Fleet Runtime runs, or why there is none. */
66
+ export type LegacyJobSchedule = {
67
+ ok: true;
68
+ schedule: string;
69
+ note?: string;
70
+ } | {
71
+ ok: false;
72
+ reason: string;
73
+ };
74
+ /**
75
+ * Convert a job from a bot's old `jobs.json` to a schedule the HQ Fleet
76
+ * Runtime runs. The job's `timezone` is not carried over (the migration never
77
+ * carried it); the schedule's fields are evaluated in the runtime's zone.
78
+ *
79
+ * The old scheduler (`local-jobs.ts`) read a six-field `cron(...)` through
80
+ * `toStandardCron`, which drops the year field: a job saved as
81
+ * `cron(0 9 ? * MON-FRI 2026)` ran every weekday, every year.
82
+ * `fleetScheduleFromLegacy` refuses a year, because `hq bot jobs --add` must
83
+ * not accept a year the runtime cannot honor. For a job the old scheduler
84
+ * already ran, the faithful move is the same five fields it ran on.
85
+ *
86
+ * Only a job without a timed schedule (an event job) has no Fleet form.
87
+ */
88
+ export declare function fleetScheduleFromLocalJob(job: Pick<LocalJob, "cron" | "trigger">): LegacyJobSchedule;
64
89
  export interface FleetJobsMigrationResult {
65
90
  imported: number;
66
91
  alreadyPresent: number;
67
92
  skipped: string[];
93
+ /** Why each skipped job could not move, in the order of `skipped`. */
94
+ skippedReasons: Array<{
95
+ jobId: string;
96
+ reason: string;
97
+ }>;
98
+ /** Jobs that moved with a schedule written differently from the old one. */
99
+ notes: Array<{
100
+ jobId: string;
101
+ note: string;
102
+ }>;
68
103
  /** Where the old list went. Null when some jobs could not move: jobs.json then stays. */
69
104
  renamedTo: string | null;
70
105
  }
@@ -73,6 +108,19 @@ export declare const FLEET_HOT_SIGNAL_SYNC_NAME = "hot-signal-sync";
73
108
  export declare const FLEET_HOT_SIGNAL_SYNC_SCHEDULE = "30 6 * * *";
74
109
  export declare function fleetHotSignalSyncScript(company: string): string;
75
110
  export declare function companyOfHotSignalSyncJob(job: FleetCronJob): string | null;
111
+ /**
112
+ * Waits between tries when a run fails because HQ could not reach the network.
113
+ * The job often fires the moment a laptop wakes, before Wi-Fi and DNS are back
114
+ * (Fleet catches up a missed daily run for up to 2 hours), so a short retry
115
+ * finds the connection. About 3.5 minutes in all, well inside Fleet's 1-hour
116
+ * script timeout.
117
+ */
118
+ export declare const HOT_SIGNAL_SYNC_NETWORK_RETRY_DELAYS_SEC: readonly number[];
119
+ /**
120
+ * A network failure reaches the owner only once it repeats this many runs in a
121
+ * row. A single morning on a sleeping laptop is not worth a message.
122
+ */
123
+ export declare const HOT_SIGNAL_SYNC_TRANSIENT_ALERT_AFTER = 2;
76
124
  /**
77
125
  * pnpm global installs land the CLI under `.../pnpm/global/vN/<hash>/...`.
78
126
  * That hash folder is removed on the next CLI update. The stable launcher is
@@ -93,6 +141,8 @@ export declare function renderFleetHotSignalSyncScript(input: {
93
141
  signalsEngine?: boolean;
94
142
  /** Override the baked pnpm `bin/hq` fallback. Tests pass this. */
95
143
  hqLauncher?: string;
144
+ /** Seconds between network retries. Default HOT_SIGNAL_SYNC_NETWORK_RETRY_DELAYS_SEC; tests pass zeros. */
145
+ networkRetryDelaysSec?: readonly number[];
96
146
  }): string;
97
147
  export interface EnsureFleetHotSignalSyncInput {
98
148
  dir: string;
@@ -3,7 +3,7 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { effectiveBotCompanies, effectiveBotKind } from "./config.js";
5
5
  import { fleetLocalRuntimePython, stderrTail } from "./fleet-local.js";
6
- import { readLocalJobs, withJobsLock, writeLocalJobs } from "./local-jobs.js";
6
+ import { parseCron, readLocalJobs, toStandardCron, withJobsLock, writeLocalJobs } from "./local-jobs.js";
7
7
  import { signInCommand } from "./runtime-sign-in.js";
8
8
  import { BOT_SIGNALS_ENGINE_JOB_FLAG, signalsEngineJobCompanies } from "./signals-engine-flag.js";
9
9
  import { SIGNALS_FAILURE_PREFIX } from "../hot-channels/alert.js";
@@ -151,6 +151,49 @@ export function fleetScheduleFromLegacy(expr) {
151
151
  const dow = dayOfWeek === "?" ? "*" : dayOfWeek.split(",").map((term) => unshiftDayOfWeekTerm(term.trim())).join(",");
152
152
  return `${minute} ${hour} ${dom} ${month} ${dow}`;
153
153
  }
154
+ /**
155
+ * Convert a job from a bot's old `jobs.json` to a schedule the HQ Fleet
156
+ * Runtime runs. The job's `timezone` is not carried over (the migration never
157
+ * carried it); the schedule's fields are evaluated in the runtime's zone.
158
+ *
159
+ * The old scheduler (`local-jobs.ts`) read a six-field `cron(...)` through
160
+ * `toStandardCron`, which drops the year field: a job saved as
161
+ * `cron(0 9 ? * MON-FRI 2026)` ran every weekday, every year.
162
+ * `fleetScheduleFromLegacy` refuses a year, because `hq bot jobs --add` must
163
+ * not accept a year the runtime cannot honor. For a job the old scheduler
164
+ * already ran, the faithful move is the same five fields it ran on.
165
+ *
166
+ * Only a job without a timed schedule (an event job) has no Fleet form.
167
+ */
168
+ export function fleetScheduleFromLocalJob(job) {
169
+ if (job.trigger) {
170
+ return { ok: false, reason: `it runs on the "${job.trigger.event}" event, and the HQ Fleet Runtime runs only timed schedules` };
171
+ }
172
+ if (job.cron !== undefined && typeof job.cron !== "string") {
173
+ return { ok: false, reason: `its schedule is not text (${JSON.stringify(job.cron)})` };
174
+ }
175
+ const expr = job.cron?.trim() ?? "";
176
+ if (!expr)
177
+ return { ok: false, reason: "it has no schedule" };
178
+ if (!/^(cron|rate)\(/i.test(expr))
179
+ return { ok: true, schedule: expr };
180
+ try {
181
+ return { ok: true, schedule: fleetScheduleFromLegacy(expr) };
182
+ }
183
+ catch (error) {
184
+ const refused = error instanceof Error ? error.message : String(error);
185
+ const year = /^cron\(\s*(?:\S+\s+){5}(\S+)\s*\)$/i.exec(expr)?.[1];
186
+ const standard = year !== undefined ? toStandardCron(expr) : null;
187
+ if (standard && parseCron(expr)) {
188
+ return {
189
+ ok: true,
190
+ schedule: standard,
191
+ note: `its year field (${year}) was never applied by the old scheduler, so it moves as "${standard}", the schedule the old scheduler ran`,
192
+ };
193
+ }
194
+ return { ok: false, reason: refused.replace(/\.$/, "") };
195
+ }
196
+ }
154
197
  function migratedJobsPath(dir, now) {
155
198
  const first = path.join(dir, "jobs.migrated.json");
156
199
  if (!fs.existsSync(first))
@@ -170,20 +213,19 @@ export function migrateLegacyJobsToFleet(dir, config, ops, now = new Date()) {
170
213
  let imported = 0;
171
214
  let alreadyPresent = 0;
172
215
  const skipped = [];
216
+ const skippedReasons = [];
217
+ const notes = [];
173
218
  const moved = new Set();
174
219
  for (const job of legacy) {
175
- if (job.trigger || !job.cron) {
176
- skipped.push(job.jobId);
177
- continue;
178
- }
179
- let schedule;
180
- try {
181
- schedule = /^(cron|rate)\(/i.test(job.cron.trim()) ? fleetScheduleFromLegacy(job.cron) : job.cron.trim();
182
- }
183
- catch {
220
+ const converted = fleetScheduleFromLocalJob(job);
221
+ if (!converted.ok) {
184
222
  skipped.push(job.jobId);
223
+ skippedReasons.push({ jobId: job.jobId, reason: converted.reason });
185
224
  continue;
186
225
  }
226
+ const schedule = converted.schedule;
227
+ if (converted.note)
228
+ notes.push({ jobId: job.jobId, note: converted.note });
187
229
  const present = existing.some((candidate) => candidate.prompt === job.prompt && candidate.schedule?.expr === schedule);
188
230
  if (present) {
189
231
  alreadyPresent += 1;
@@ -201,11 +243,11 @@ export function migrateLegacyJobsToFleet(dir, config, ops, now = new Date()) {
201
243
  const all = readLocalJobs(dir);
202
244
  writeLocalJobs(dir, all.filter((job) => !moved.has(job.jobId)));
203
245
  }
204
- return { imported, alreadyPresent, skipped, renamedTo: null };
246
+ return { imported, alreadyPresent, skipped, skippedReasons, notes, renamedTo: null };
205
247
  }
206
248
  const renamedTo = migratedJobsPath(dir, now);
207
249
  fs.renameSync(file, renamedTo);
208
- return { imported, alreadyPresent, skipped, renamedTo };
250
+ return { imported, alreadyPresent, skipped, skippedReasons, notes, renamedTo };
209
251
  });
210
252
  }
211
253
  export const FLEET_HOT_SIGNAL_SYNC_NAME = "hot-signal-sync";
@@ -422,6 +464,71 @@ def signals_failures(err):
422
464
  errors.append(error)
423
465
  return found, errors
424
466
  `;
467
+ /**
468
+ * Waits between tries when a run fails because HQ could not reach the network.
469
+ * The job often fires the moment a laptop wakes, before Wi-Fi and DNS are back
470
+ * (Fleet catches up a missed daily run for up to 2 hours), so a short retry
471
+ * finds the connection. About 3.5 minutes in all, well inside Fleet's 1-hour
472
+ * script timeout.
473
+ */
474
+ export const HOT_SIGNAL_SYNC_NETWORK_RETRY_DELAYS_SEC = [30, 60, 120];
475
+ /**
476
+ * A network failure reaches the owner only once it repeats this many runs in a
477
+ * row. A single morning on a sleeping laptop is not worth a message.
478
+ */
479
+ export const HOT_SIGNAL_SYNC_TRANSIENT_ALERT_AFTER = 2;
480
+ /**
481
+ * Python helper for the flag-off script: one alert per failure streak.
482
+ *
483
+ * The state file next to the log counts failed runs in a row and the reasons
484
+ * already sent to the owner in this streak. A failure the owner already heard
485
+ * about stays in the log only, and the script exits 0 so Fleet sends nothing
486
+ * (Fleet turns any non-zero exit of a no-agent job into a DM). A new reason
487
+ * alerts again. A clean run deletes the file, which ends the streak. A
488
+ * network-only failure alerts from HOT_SIGNAL_SYNC_TRANSIENT_ALERT_AFTER runs
489
+ * in a row. When the file cannot be read or written the script alerts, as it
490
+ * did before the state file existed.
491
+ */
492
+ const HOT_SIGNAL_SYNC_STREAK = String.raw `def read_streak():
493
+ try:
494
+ with open(STATE, encoding='utf-8') as f:
495
+ data = json.load(f)
496
+ if isinstance(data, dict):
497
+ return data
498
+ except Exception:
499
+ pass
500
+ return {}
501
+
502
+ def note_failure(reason, transient):
503
+ # Returns (alert, failures in a row including this run).
504
+ try:
505
+ state = read_streak()
506
+ failures = int(state.get('failures') or 0) + 1
507
+ alerted = [r for r in (state.get('alerted') or []) if isinstance(r, str)]
508
+ alert = reason not in alerted and (not transient or failures >= TRANSIENT_ALERT_AFTER)
509
+ if alert:
510
+ alerted.append(reason)
511
+ tmp = STATE + '.tmp'
512
+ with open(tmp, 'w', encoding='utf-8') as f:
513
+ json.dump({'failures': failures, 'alerted': alerted, 'last': reason, 'at': time.strftime('%Y-%m-%dT%H:%M:%S%z', STARTED)}, f)
514
+ os.replace(tmp, STATE)
515
+ return alert, failures
516
+ except Exception:
517
+ return True, 1
518
+
519
+ def clear_streak():
520
+ try:
521
+ os.remove(STATE)
522
+ except OSError:
523
+ pass
524
+
525
+ def in_a_row(failures):
526
+ return ' (%d runs in a row)' % failures if failures > 1 else ''
527
+
528
+ def log_quiet(failures):
529
+ with open(LOG, 'a', encoding='utf-8') as log:
530
+ log.write('Not sent to the owner: they already heard about this failure in this streak, or it is a network failure seen fewer than %d runs in a row (%d so far).\n' % (TRANSIENT_ALERT_AFTER, failures))
531
+ `;
425
532
  /** How a run ended, for the log line after it: `exit 1` or `signal 9`. */
426
533
  const HOT_SIGNAL_SYNC_RUN_END = String.raw `def run_end(code):
427
534
  return 'signal %d' % -code if code < 0 else 'exit %d' % code
@@ -505,6 +612,12 @@ export function renderFleetHotSignalSyncScript(input) {
505
612
  // lines (US-018 AC1). A clean run that landed sources and found no signals
506
613
  // also raises the alert, but with no error; it stays in the log. The exit
507
614
  // code stays 0: the sync itself finished.
615
+ //
616
+ // Each failure streak alerts once (HOT_SIGNAL_SYNC_STREAK): a reason the
617
+ // owner already heard about in this streak stays in the log and the script
618
+ // exits 0, because Fleet DMs every non-zero exit. A network failure is
619
+ // retried within the run (NETWORK_RETRY_DELAYS) and alerts only from its
620
+ // second run in a row.
508
621
  const launcher = input.hqLauncher ?? fleetPnpmHqLauncher(input.hqBinary);
509
622
  // HQ is often the pnpm hash folder's dist/index.js. That path dies on the
510
623
  // next CLI update (feedback_614121bf). Prefer it while it exists so tests
@@ -512,31 +625,51 @@ export function renderFleetHotSignalSyncScript(input) {
512
625
  // launcher without node (it is a shell/cmd shim, not JS).
513
626
  const run = plainSync
514
627
  ? [
515
- " command = hq_argv() + ARGS",
516
- " result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
517
- " note = ''",
628
+ " def sync_once():",
629
+ " command = hq_argv() + ARGS",
630
+ " result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
631
+ " note = ''",
518
632
  // Commander rejects the option before the sync starts, so the retry is
519
633
  // the only run that does any work.
520
- " if result.returncode != 0 and \"unknown option '--trigger'\" in result.stderr:",
521
- " note = 'This hq has no --trigger option; ran the sync without it.\\n'",
522
- " command = hq_argv() + LEGACY_ARGS",
523
- " result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
524
- " with open(LOG, 'a', encoding='utf-8') as log:",
525
- header,
526
- " log.write(note)",
527
- " log.write(result.stderr)",
528
- " log.write(result.stdout)",
529
- " if result.returncode != 0 and not output_lines(result.stderr) and not output_lines(result.stdout):",
530
- " log.write('hq printed nothing. Command: ' + shlex.join(command) + '\\n')",
531
- footer,
634
+ " if result.returncode != 0 and \"unknown option '--trigger'\" in result.stderr:",
635
+ " note = 'This hq has no --trigger option; ran the sync without it.\\n'",
636
+ " command = hq_argv() + LEGACY_ARGS",
637
+ " result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
638
+ " with open(LOG, 'a', encoding='utf-8') as log:",
639
+ header.replace(/^ {8}/, " "),
640
+ " log.write(note)",
641
+ " log.write(result.stderr)",
642
+ " log.write(result.stdout)",
643
+ " if result.returncode != 0 and not output_lines(result.stderr) and not output_lines(result.stdout):",
644
+ " log.write('hq printed nothing. Command: ' + shlex.join(command) + '\\n')",
645
+ footer.replace(/^ {8}/, " "),
646
+ " return result",
647
+ // A network failure is retried a few times before it counts: the job
648
+ // often fires the moment a laptop wakes, before the connection is back.
649
+ " result = sync_once()",
650
+ " for delay in NETWORK_RETRY_DELAYS:",
651
+ " if result.returncode == 0 or classify(result.stdout, result.stderr, result.returncode)[1] != FIXES['network']:",
652
+ " break",
653
+ " with open(LOG, 'a', encoding='utf-8') as log:",
654
+ " log.write('HQ could not reach the network; trying again in %d s.\\n' % delay)",
655
+ " time.sleep(delay)",
656
+ " result = sync_once()",
532
657
  " if result.returncode != 0:",
533
658
  " reason, fix = classify(result.stdout, result.stderr, result.returncode)",
534
- ` sys.stdout.write('The ' + scheduled_time() + ${JSON.stringify(` hot-channel sync for ${input.company} did not finish: `)} + reason + '.\\n')`,
659
+ " alert, failures = note_failure(reason, fix == FIXES['network'])",
660
+ " if not alert:",
661
+ " log_quiet(failures)",
662
+ // Exit 0 so Fleet sends nothing: it turns any non-zero exit into a DM.
663
+ // The failure is in the log and in the sync's own run ledger.
664
+ " sys.exit(0)",
665
+ ` sys.stdout.write('The ' + scheduled_time() + ${JSON.stringify(` hot-channel sync for ${input.company} did not finish: `)} + reason + in_a_row(failures) + '.\\n')`,
535
666
  " sys.stdout.write('Fix: ' + fix + '\\n')",
536
667
  " sys.stdout.write('Log: ' + LOG + ' (run started ' + time.strftime('%Y-%m-%d %H:%M', STARTED) + ')\\n')",
537
668
  " sys.exit(128 - result.returncode if result.returncode < 0 else result.returncode)",
538
669
  " found, errors = signals_failures(result.stderr)",
539
- " if found:",
670
+ " if not found:",
671
+ " clear_streak()",
672
+ " else:",
540
673
  " reasons, fixes = [], []",
541
674
  " for error in errors:",
542
675
  " reason, fix = classify('', error, 1)",
@@ -544,9 +677,13 @@ export function renderFleetHotSignalSyncScript(input) {
544
677
  " reasons.append(reason)",
545
678
  " if fix not in fixes:",
546
679
  " fixes.append(fix)",
547
- ` sys.stdout.write('The ' + scheduled_time() + ${JSON.stringify(` hot-channel sync for ${input.company} landed sources but the signals step failed: `)} + '; '.join(found) + '. Cause: ' + '; '.join(reasons) + '.\\n')`,
548
- " sys.stdout.write('Fix: ' + ' Also, '.join(fixes) + '\\n')",
549
- " sys.stdout.write('Log: ' + LOG + ' (run started ' + time.strftime('%Y-%m-%d %H:%M', STARTED) + ')\\n')",
680
+ " alert, failures = note_failure('signals: ' + '; '.join(reasons), all(f == FIXES['network'] for f in fixes))",
681
+ " if not alert:",
682
+ " log_quiet(failures)",
683
+ " else:",
684
+ ` sys.stdout.write('The ' + scheduled_time() + ${JSON.stringify(` hot-channel sync for ${input.company} landed sources but the signals step failed: `)} + '; '.join(found) + '. Cause: ' + '; '.join(reasons) + in_a_row(failures) + '.\\n')`,
685
+ " sys.stdout.write('Fix: ' + ' Also, '.join(fixes) + '\\n')",
686
+ " sys.stdout.write('Log: ' + LOG + ' (run started ' + time.strftime('%Y-%m-%d %H:%M', STARTED) + ')\\n')",
550
687
  ]
551
688
  : [
552
689
  " with open(LOG, 'a', encoding='utf-8') as log:",
@@ -569,11 +706,15 @@ export function renderFleetHotSignalSyncScript(input) {
569
706
  ...(plainSync
570
707
  ? [
571
708
  `LEGACY_ARGS = ${JSON.stringify(legacyArgs)}`,
709
+ `STATE = ${JSON.stringify(path.join(path.dirname(input.logFile), `hot-signal-sync-${input.company}.state.json`))}`,
710
+ `NETWORK_RETRY_DELAYS = ${JSON.stringify(input.networkRetryDelaysSec ?? HOT_SIGNAL_SYNC_NETWORK_RETRY_DELAYS_SEC)}`,
711
+ `TRANSIENT_ALERT_AFTER = ${HOT_SIGNAL_SYNC_TRANSIENT_ALERT_AFTER}`,
572
712
  `FIXES = ${JSON.stringify(fixes)}`,
573
713
  "FIXES = dict((k, v.replace('DATE', time.strftime('%Y-%m-%d', STARTED))) for k, v in FIXES.items())",
574
714
  HOT_SIGNAL_SYNC_ALERT_HELPERS,
575
715
  `SIGNALS_FAILURE_PREFIX = ${JSON.stringify(SIGNALS_FAILURE_PREFIX)}`,
576
716
  HOT_SIGNAL_SYNC_SIGNALS_FAILURES,
717
+ HOT_SIGNAL_SYNC_STREAK,
577
718
  ]
578
719
  : []),
579
720
  "try:",
@@ -445,8 +445,26 @@ export declare function fleetLocalChannels(state: FleetLocalGatewayState | null,
445
445
  slack: string;
446
446
  telegram: string;
447
447
  };
448
+ /**
449
+ * How long a Fleet cron job's `fire_claim` stays live. This is the HQ Fleet
450
+ * Runtime's own rule (`claim_ttl_seconds` in hq-fleet-runtime
451
+ * `cron/jobs.py`): a running job refreshes its claim every 60 seconds, and
452
+ * the runtime treats a claim older than 300 seconds as abandoned and fires
453
+ * over it. A claim left by a runner that died is never cleared by its holder,
454
+ * so it must age out here too or the bot looks busy forever.
455
+ */
456
+ export declare const FLEET_CRON_FIRE_CLAIM_TTL_MS = 300000;
457
+ /**
458
+ * Whether a Fleet cron job's `fire_claim` is held by a live run, by the
459
+ * runtime's rule: it has a readable `at` that is not in the future and is
460
+ * younger than {@link FLEET_CRON_FIRE_CLAIM_TTL_MS}.
461
+ */
462
+ export declare function fleetCronFireClaimLive(claim: unknown, nowMs: number): boolean;
448
463
  export declare function fleetLocalBusyReason(agentUid: string, deps?: Pick<FleetLocalControlDeps, "fleetHome"> & {
449
464
  isAlive?: (pid: number) => boolean;
465
+ now?: () => number;
466
+ /** Told about a claim or schedule file that does not count as busy, so a stale one is visible. */
467
+ warn?: (message: string) => void;
450
468
  }): string | null;
451
469
  /** Checks the instructions with the runtime's scanner, then makes them the bot's persona. */
452
470
  export declare function refreshFleetLocalInstructions(agentUid: string, systemPrompt: string, deps?: FleetLocalControlDeps): string;
@@ -1963,6 +1963,40 @@ export function fleetLocalChannels(state, gatewayAlive) {
1963
1963
  const lane = (name) => (gatewayAlive && state?.platforms[name]) || "not_connected";
1964
1964
  return { slack: lane("slack"), telegram: lane("telegram") };
1965
1965
  }
1966
+ /**
1967
+ * How long a Fleet cron job's `fire_claim` stays live. This is the HQ Fleet
1968
+ * Runtime's own rule (`claim_ttl_seconds` in hq-fleet-runtime
1969
+ * `cron/jobs.py`): a running job refreshes its claim every 60 seconds, and
1970
+ * the runtime treats a claim older than 300 seconds as abandoned and fires
1971
+ * over it. A claim left by a runner that died is never cleared by its holder,
1972
+ * so it must age out here too or the bot looks busy forever.
1973
+ */
1974
+ export const FLEET_CRON_FIRE_CLAIM_TTL_MS = 300_000;
1975
+ /** The claim's time in epoch ms, or null when it has no readable `at`. */
1976
+ function fireClaimTime(claim) {
1977
+ if (!claim || typeof claim !== "object" || Array.isArray(claim))
1978
+ return null;
1979
+ const at = claim.at;
1980
+ if (typeof at !== "string" || !at)
1981
+ return null;
1982
+ // The runtime writes Python isoformat, which can carry microseconds. Keep
1983
+ // milliseconds so every JS engine parses it. A value with no offset is the
1984
+ // runtime machine's local time, which Date.parse also assumes.
1985
+ const time = Date.parse(at.replace(/(\.\d{3})\d+/, "$1"));
1986
+ return Number.isFinite(time) ? time : null;
1987
+ }
1988
+ /**
1989
+ * Whether a Fleet cron job's `fire_claim` is held by a live run, by the
1990
+ * runtime's rule: it has a readable `at` that is not in the future and is
1991
+ * younger than {@link FLEET_CRON_FIRE_CLAIM_TTL_MS}.
1992
+ */
1993
+ export function fleetCronFireClaimLive(claim, nowMs) {
1994
+ const time = fireClaimTime(claim);
1995
+ if (time === null)
1996
+ return false;
1997
+ const age = nowMs - time;
1998
+ return age >= 0 && age < FLEET_CRON_FIRE_CLAIM_TTL_MS;
1999
+ }
1966
2000
  export function fleetLocalBusyReason(agentUid, deps = {}) {
1967
2001
  const state = readFleetLocalGatewayState(agentUid, deps);
1968
2002
  const alive = deps.isAlive ?? ((pid) => {
@@ -1980,15 +2014,27 @@ export function fleetLocalBusyReason(agentUid, deps = {}) {
1980
2014
  return `${state.activeAgents} turn${state.activeAgents === 1 ? "" : "s"} in progress`;
1981
2015
  if (state.gatewayState === "draining" || state.gatewayState === "starting")
1982
2016
  return `gateway is ${state.gatewayState}`;
2017
+ const file = path.join(fleetLocalProfileDir(agentUid, deps), "cron", "jobs.json");
2018
+ let store;
1983
2019
  try {
1984
- const store = JSON.parse(fs.readFileSync(path.join(fleetLocalProfileDir(agentUid, deps), "cron", "jobs.json"), "utf8"));
1985
- const running = (store.jobs ?? []).find((job) => job && job.fire_claim !== null && job.fire_claim !== undefined);
1986
- if (running)
1987
- return typeof running.name === "string" && running.name ? `scheduled job "${running.name}" is running` : "a scheduled job is running";
2020
+ store = JSON.parse(fs.readFileSync(file, "utf8"));
1988
2021
  }
1989
- catch {
2022
+ catch (error) {
2023
+ if (error.code !== "ENOENT") {
2024
+ deps.warn?.(`could not read the scheduled jobs in ${file} (${error instanceof Error ? error.message : String(error)}); not counting any job as running`);
2025
+ }
1990
2026
  return null;
1991
2027
  }
2028
+ const now = (deps.now ?? Date.now)();
2029
+ const label = (job) => typeof job.name === "string" && job.name ? `scheduled job "${job.name}"` : typeof job.id === "string" && job.id ? `scheduled job ${job.id}` : "a scheduled job";
2030
+ for (const job of Array.isArray(store?.jobs) ? store.jobs : []) {
2031
+ if (!job || job.fire_claim === null || job.fire_claim === undefined)
2032
+ continue;
2033
+ if (fleetCronFireClaimLive(job.fire_claim, now))
2034
+ return `${label(job)} is running`;
2035
+ const at = job.fire_claim?.at;
2036
+ deps.warn?.(`${label(job)} still holds a run claim${typeof at === "string" && at ? ` from ${at}` : ""} that is past the HQ Fleet Runtime's ${FLEET_CRON_FIRE_CLAIM_TTL_MS / 1000}-second limit; its run has stopped, so it does not block this update`);
2037
+ }
1992
2038
  return null;
1993
2039
  }
1994
2040
  /** Checks the instructions with the runtime's scanner, then makes them the bot's persona. */
@@ -1,5 +1,5 @@
1
1
  import { loadCachedTokens } from "@indigoai-us/hq-cloud";
2
- import { createFlagClient, } from "@indigoai-us/hq-flags-client";
2
+ import { createHqFlagClient as createFlagClient } from "../flag-client-headers.js";
3
3
  import { resolveFlagGate, resolveProcessFlagCompanyContext } from "../flag-registry.js";
4
4
  import { resolveFlagRegistryEndpoint } from "../flag-registry-endpoint.js";
5
5
  import { effectiveBotCompanies, effectiveBotKind } from "./config.js";
@@ -1,4 +1,4 @@
1
- import type { CompanyFlagGateDependencies } from "../flag-registry.js";
1
+ import type { CompanyFlagGateDependencies } from "../company-flag-gate.js";
2
2
  export declare const BOT_SIGNALS_ENGINE_JOB_FLAG = "cli.bot-signals-engine-job";
3
3
  export interface SignalsEngineFlagSession {
4
4
  token: string;
@@ -84,7 +84,7 @@ async function readForCompany(company, session, deps) {
84
84
  const signedIn = await session(company);
85
85
  if (!signedIn)
86
86
  return "signed-out";
87
- const { readCompanyFlag } = await import("../flag-registry.js");
87
+ const { readCompanyFlag } = await import("../company-flag-gate.js");
88
88
  return readCompanyFlag(signedIn.companyUid, signedIn.token, BOT_SIGNALS_ENGINE_JOB_FLAG, { fallback: false }, deps.createClient ? { createClient: deps.createClient } : {});
89
89
  })();
90
90
  // A read that loses the race below must not surface later as an unhandled rejection.
@@ -5,7 +5,7 @@ import * as path from "node:path";
5
5
  import { createInterface } from "node:readline/promises";
6
6
  import { isExpiring, isMachineIdentity, loadCachedTokens, } from "../utils/cognito-session.js";
7
7
  import { queueCliInviteNudgeEvent } from "../utils/cli-telemetry.js";
8
- import { resolveCompanyFlagGate } from "./flag-registry.js";
8
+ import { resolveCompanyFlagGate } from "./company-flag-gate.js";
9
9
  import { isHumanInteractiveCliSession } from "./first-sync-next-step.js";
10
10
  import { vaultApiFetch } from "../utils/vault-api.js";
11
11
  export const CLI_INVITE_NUDGE_FLAG = "cli.first-sync-invite-teammate-v1";
@@ -0,0 +1,2 @@
1
+ export declare function readClientVersion(): string | undefined;
2
+ //# sourceMappingURL=client-version.d.ts.map