@indigoai-us/hq-cli 5.345.215-beta.0 → 5.345.217

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 (241) hide show
  1. package/CHANGELOG.md +206 -1
  2. package/README.md +45 -0
  3. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
  4. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  5. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  6. package/dist/command-catalog.generated.d.ts +105 -10
  7. package/dist/command-catalog.generated.js +127 -10
  8. package/dist/command-help.js +3 -1
  9. package/dist/command-registration-plan.d.ts +6 -0
  10. package/dist/command-registration-plan.js +1 -0
  11. package/dist/commands/auth.d.ts +1 -1
  12. package/dist/commands/auth.js +11 -52
  13. package/dist/commands/bot.js +75 -10
  14. package/dist/commands/capacity.d.ts +4 -1
  15. package/dist/commands/capacity.js +46 -10
  16. package/dist/commands/cloud-demote.d.ts +19 -4
  17. package/dist/commands/cloud-demote.js +85 -12
  18. package/dist/commands/cloud-provision.d.ts +5 -1
  19. package/dist/commands/cloud-provision.js +6 -2
  20. package/dist/commands/cloud.d.ts +36 -0
  21. package/dist/commands/cloud.js +110 -27
  22. package/dist/commands/core-delegate-w1b.js +15 -1
  23. package/dist/commands/core-policy.js +67 -8
  24. package/dist/commands/core.js +1 -0
  25. package/dist/commands/daemon.js +9 -1
  26. package/dist/commands/dm.js +7 -0
  27. package/dist/commands/doctor-usage.d.ts +8 -0
  28. package/dist/commands/doctor-usage.js +20 -0
  29. package/dist/commands/doctor.js +7 -1
  30. package/dist/commands/env.d.ts +18 -0
  31. package/dist/commands/env.js +82 -0
  32. package/dist/commands/files-browse.d.ts +11 -4
  33. package/dist/commands/files-browse.js +21 -4
  34. package/dist/commands/files.d.ts +1 -1
  35. package/dist/commands/files.js +25 -11
  36. package/dist/commands/install-global.js +2 -2
  37. package/dist/commands/integrations-auth-rules.d.ts +27 -0
  38. package/dist/commands/integrations-auth-rules.js +79 -0
  39. package/dist/commands/integrations-import.js +124 -12
  40. package/dist/commands/lanes.js +102 -26
  41. package/dist/commands/logout.d.ts +7 -0
  42. package/dist/commands/logout.js +41 -34
  43. package/dist/commands/mesh.d.ts +2 -0
  44. package/dist/commands/mesh.js +60 -35
  45. package/dist/commands/sources.d.ts +8 -2
  46. package/dist/commands/sources.js +65 -9
  47. package/dist/commands/sync-held.js +5 -2
  48. package/dist/commands/whoami.js +26 -1
  49. package/dist/data/command-states.json +15 -0
  50. package/dist/index.js +52 -4
  51. package/dist/lazy-commands.js +5 -6
  52. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  53. package/dist/lib/anywhere-person-setting.js +6 -3
  54. package/dist/lib/billing/usage-card.d.ts +25 -4
  55. package/dist/lib/billing/usage-card.js +76 -9
  56. package/dist/lib/billing/usage-cost.d.ts +3 -3
  57. package/dist/lib/billing/usage-cost.js +35 -13
  58. package/dist/lib/billing/usage-only.js +4 -2
  59. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  60. package/dist/lib/billing/usage-rate-card.js +3 -0
  61. package/dist/lib/bot/fleet-cron.d.ts +8 -0
  62. package/dist/lib/bot/fleet-cron.js +126 -7
  63. package/dist/lib/bot/fleet-daemon.d.ts +46 -0
  64. package/dist/lib/bot/fleet-daemon.js +99 -1
  65. package/dist/lib/bot/inflight.d.ts +9 -0
  66. package/dist/lib/bot/inflight.js +10 -0
  67. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  68. package/dist/lib/bot/probe.js +7 -1
  69. package/dist/lib/bot/run.js +20 -1
  70. package/dist/lib/bot/runtime/codex.js +1 -1
  71. package/dist/lib/bot/runtime/grok-acp.d.ts +6 -1
  72. package/dist/lib/bot/runtime/grok-acp.js +32 -14
  73. package/dist/lib/bot/runtime/grok.js +1 -1
  74. package/dist/lib/bot/runtime/index.js +19 -9
  75. package/dist/lib/bot/runtime/messages-stream.js +2 -2
  76. package/dist/lib/bot/runtime/types.d.ts +15 -0
  77. package/dist/lib/bot/runtime/types.js +9 -0
  78. package/dist/lib/bot/runtime-failure.d.ts +23 -0
  79. package/dist/lib/bot/runtime-failure.js +43 -1
  80. package/dist/lib/capacity/accounts.d.ts +8 -0
  81. package/dist/lib/capacity/accounts.js +19 -0
  82. package/dist/lib/capacity/available.d.ts +154 -0
  83. package/dist/lib/capacity/available.js +905 -0
  84. package/dist/lib/capacity/codex-availability.d.ts +14 -1
  85. package/dist/lib/capacity/codex-availability.js +26 -1
  86. package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
  87. package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
  88. package/dist/lib/capacity/collectors/codex.js +10 -7
  89. package/dist/lib/capacity/ledger.d.ts +37 -1
  90. package/dist/lib/capacity/ledger.js +207 -30
  91. package/dist/lib/capacity/project.d.ts +26 -0
  92. package/dist/lib/capacity/project.js +137 -8
  93. package/dist/lib/capacity/refusal-rows.d.ts +31 -0
  94. package/dist/lib/capacity/refusal-rows.js +61 -0
  95. package/dist/lib/capacity/refusal.d.ts +53 -2
  96. package/dist/lib/capacity/refusal.js +284 -65
  97. package/dist/lib/capacity/route.js +46 -11
  98. package/dist/lib/capacity/widget.d.ts +12 -1
  99. package/dist/lib/capacity/widget.js +91 -3
  100. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  101. package/dist/lib/daemon/flag-monitor.js +17 -6
  102. package/dist/lib/daemon/flag.d.ts +65 -1
  103. package/dist/lib/daemon/flag.js +190 -40
  104. package/dist/lib/daemon/ops/policy.js +62 -5
  105. package/dist/lib/daemon/paths.d.ts +72 -2
  106. package/dist/lib/daemon/paths.js +154 -3
  107. package/dist/lib/daemon/resolver.d.ts +2 -0
  108. package/dist/lib/daemon/resolver.js +3 -0
  109. package/dist/lib/daemon/run.d.ts +9 -0
  110. package/dist/lib/daemon/run.js +79 -21
  111. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  112. package/dist/lib/daemon/selfcheck.js +40 -1
  113. package/dist/lib/daemon/server.d.ts +5 -1
  114. package/dist/lib/daemon/server.js +17 -23
  115. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  116. package/dist/lib/daemon/state-file-switch.js +88 -0
  117. package/dist/lib/daemon/state-file.d.ts +198 -0
  118. package/dist/lib/daemon/state-file.js +419 -0
  119. package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
  120. package/dist/lib/daemon/tcc-eperm.js +310 -0
  121. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  122. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  123. package/dist/lib/delivery/admission.d.ts +86 -0
  124. package/dist/lib/delivery/admission.js +148 -0
  125. package/dist/lib/delivery/artifacts.d.ts +7 -1
  126. package/dist/lib/delivery/artifacts.js +29 -10
  127. package/dist/lib/delivery/attempt-id.d.ts +13 -0
  128. package/dist/lib/delivery/attempt-id.js +16 -0
  129. package/dist/lib/delivery/disposable-target.d.ts +42 -0
  130. package/dist/lib/delivery/disposable-target.js +111 -0
  131. package/dist/lib/delivery/effects.d.ts +136 -0
  132. package/dist/lib/delivery/effects.js +541 -0
  133. package/dist/lib/delivery/enrollment.d.ts +21 -17
  134. package/dist/lib/delivery/enrollment.js +83 -5
  135. package/dist/lib/delivery/escalations.d.ts +51 -0
  136. package/dist/lib/delivery/escalations.js +60 -0
  137. package/dist/lib/delivery/lease.d.ts +80 -0
  138. package/dist/lib/delivery/lease.js +134 -0
  139. package/dist/lib/delivery/migrations.d.ts +120 -4
  140. package/dist/lib/delivery/migrations.js +215 -15
  141. package/dist/lib/delivery/mqtt.d.ts +2 -0
  142. package/dist/lib/delivery/mqtt.js +7 -0
  143. package/dist/lib/delivery/reconciler.d.ts +65 -1
  144. package/dist/lib/delivery/reconciler.js +224 -13
  145. package/dist/lib/delivery/rpc/client.d.ts +22 -0
  146. package/dist/lib/delivery/rpc/client.js +159 -0
  147. package/dist/lib/delivery/rpc/port.d.ts +40 -0
  148. package/dist/lib/delivery/rpc/port.js +16 -0
  149. package/dist/lib/delivery/rpc/server.d.ts +30 -0
  150. package/dist/lib/delivery/rpc/server.js +205 -0
  151. package/dist/lib/delivery/rpc/wire.d.ts +85 -0
  152. package/dist/lib/delivery/rpc/wire.js +143 -0
  153. package/dist/lib/delivery/store.d.ts +2 -0
  154. package/dist/lib/delivery/store.js +4 -0
  155. package/dist/lib/delivery/windows-service-install.d.ts +262 -0
  156. package/dist/lib/delivery/windows-service-install.js +892 -0
  157. package/dist/lib/delivery/workers/macos.d.ts +16 -1
  158. package/dist/lib/delivery/workers/macos.js +54 -12
  159. package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
  160. package/dist/lib/delivery/workers/windows-service-live.js +711 -0
  161. package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
  162. package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
  163. package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
  164. package/dist/lib/delivery/workers/windows-service.js +584 -0
  165. package/dist/lib/delivery/workers/windows.d.ts +32 -22
  166. package/dist/lib/delivery/workers/windows.js +50 -64
  167. package/dist/lib/doctor/checks/host-core.d.ts +50 -0
  168. package/dist/lib/doctor/checks/host-core.js +269 -0
  169. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  170. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  171. package/dist/lib/doctor/registry.js +4 -0
  172. package/dist/lib/environment/profile.d.ts +239 -0
  173. package/dist/lib/environment/profile.js +251 -0
  174. package/dist/lib/hook-engine/reconcile.js +39 -13
  175. package/dist/lib/hook-engine/registration.d.ts +9 -0
  176. package/dist/lib/hook-engine/registration.js +19 -0
  177. package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
  178. package/dist/lib/hot-channels/adapters/meetings.js +36 -3
  179. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  180. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  181. package/dist/lib/hot-channels/alert.d.ts +2 -0
  182. package/dist/lib/hot-channels/alert.js +8 -1
  183. package/dist/lib/hot-channels/contract.d.ts +12 -0
  184. package/dist/lib/hot-channels/contract.js +7 -0
  185. package/dist/lib/hot-channels/loop.js +1 -0
  186. package/dist/lib/hot-channels/run.d.ts +6 -0
  187. package/dist/lib/hot-channels/run.js +4 -0
  188. package/dist/lib/hot-channels/signals-pass.d.ts +74 -1
  189. package/dist/lib/hot-channels/signals-pass.js +82 -41
  190. package/dist/lib/hot-channels/signals-redo.js +10 -2
  191. package/dist/lib/install/claude-targets.d.ts +12 -1
  192. package/dist/lib/install/claude-targets.js +57 -5
  193. package/dist/lib/install/codex-targets.d.ts +2 -2
  194. package/dist/lib/install/codex-targets.js +36 -6
  195. package/dist/lib/install/hook-target.d.ts +3 -0
  196. package/dist/lib/install/hook-target.js +11 -0
  197. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  198. package/dist/lib/lanes/canonical-host.js +65 -0
  199. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  200. package/dist/lib/lanes/host-capacity.js +29 -3
  201. package/dist/lib/lanes/watcher.js +35 -0
  202. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  203. package/dist/lib/mesh/live/daemon/run.js +5 -2
  204. package/dist/lib/mesh/live/flush.d.ts +5 -1
  205. package/dist/lib/mesh/live/flush.js +12 -6
  206. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  207. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  208. package/dist/lib/mesh/live/spool.d.ts +7 -0
  209. package/dist/lib/mesh/live/spool.js +25 -0
  210. package/dist/lib/person-setting-cache.d.ts +38 -0
  211. package/dist/lib/person-setting-cache.js +98 -0
  212. package/dist/lib/safe-store.d.ts +245 -0
  213. package/dist/lib/safe-store.js +777 -0
  214. package/dist/lib/signals/engine.d.ts +29 -2
  215. package/dist/lib/signals/engine.js +103 -4
  216. package/dist/lib/signals/reply.js +73 -18
  217. package/dist/lib/signals/steps/adapters.js +7 -2
  218. package/dist/lib/signals/steps/extract.d.ts +13 -0
  219. package/dist/lib/signals/steps/extract.js +122 -6
  220. package/dist/main.js +46 -3
  221. package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
  222. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  223. package/dist/utils/auth-expiry.d.ts +8 -0
  224. package/dist/utils/auth-expiry.js +53 -0
  225. package/dist/utils/catalog-runtime-paths.d.ts +34 -0
  226. package/dist/utils/catalog-runtime-paths.js +53 -0
  227. package/dist/utils/cli-telemetry.d.ts +21 -0
  228. package/dist/utils/cli-telemetry.js +34 -0
  229. package/dist/utils/command-usage.d.ts +275 -0
  230. package/dist/utils/command-usage.js +797 -0
  231. package/dist/utils/files-browse-acl.js +1 -1
  232. package/dist/utils/hook-trust.d.ts +7 -0
  233. package/dist/utils/hook-trust.js +31 -4
  234. package/dist/utils/host-registration.d.ts +126 -0
  235. package/dist/utils/host-registration.js +378 -0
  236. package/dist/utils/resident-package-preload.js +2 -0
  237. package/package.json +10 -8
  238. package/scripts/bench-core.mjs +1096 -0
  239. package/scripts/check-function-manifest.mjs +702 -0
  240. package/dist/lib/delivery/workers/windows-boundary.d.ts +0 -453
  241. package/dist/lib/delivery/workers/windows-boundary.js +0 -693
@@ -4,6 +4,8 @@ import { legacyProviderLoginProbe } from "../lib/bot/legacy-provider-login.js";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { CLI_VERSION } from "../cli-version.js";
6
6
  import { runSignals } from "../lib/signals/engine.js";
7
+ // The main bot's runtime, the same one the signals engine's extract step uses.
8
+ import { defaultResolveBotRuntime } from "../lib/signals/steps/extract.js";
7
9
  import { BOT_SIGNALS_ENGINE_JOB_FLAG, signalsEngineForJob } from "../lib/bot/signals-engine-flag.js";
8
10
  import { resolveProcessFlagGate } from "../lib/flag-registry.js";
9
11
  import { currentHotSignalSyncCompany, readActiveCompanySlug, registerHotSignalSyncOnStart, runHotSignalSyncJob } from "../lib/bot/jobs/hot-signal-sync.js";
@@ -12,7 +14,7 @@ import { machineTimeZone } from "../lib/bot/job-run.js";
12
14
  import { runCompanyHotChannelSync } from "./sources.js";
13
15
  import { OwnerContextCache, lookupOwnerContext } from "../lib/bot/owner-context.js";
14
16
  import { hasActivePromotion } from "../lib/bot/promotion-receipt.js";
15
- import { readInflightTurns } from "../lib/bot/inflight.js";
17
+ import { botBusyState, readInflightTurns } from "../lib/bot/inflight.js";
16
18
  import { hasPromotionHold, promotionHoldSummary } from "../lib/bot/promotion-hold.js";
17
19
  /**
18
20
  * `hq bot` — personal local bots (local-bots US-003/US-004/US-005).
@@ -79,7 +81,7 @@ import { clearPendingSwitch, recoverPendingSwitchSafely, writePendingSwitch } fr
79
81
  import { classifyRuntimeFailure, isRuntimeUsageLimit, runtimeFailureReason, usageLimitResetsAt } from "../lib/bot/runtime-failure.js";
80
82
  import { PROBE_DEFAULT_TIMEOUT_MS, probeBotRuntime } from "../lib/bot/probe.js";
81
83
  import { BOT_LOGIN_RUNTIMES, botAuthEnv, botRuntimeAuth, capacityAccountHome, defaultSpawnBrowserSignIn, describeBotAuth, formatBotAuth, isBotLoginRuntime, restoreBotSessions, setAsideBotSessions, discardHeldBotLogin, holdPreviousBotLogin, restoreHeldBotLogin, signInBotRuntime, signOutBotRuntime, withRuntimeAuth, } from "../lib/bot/runtime-auth.js";
82
- import { BotApi, BotApiError, BOT_RESTORE_DEFAULTS, buildBotLocalConfig, describeBotLocalConfig, orphanBotRunMessage, parseBotLocalConfig, removeOrphanBotDaemon, botDaemonStatus, botDir, botCredsPath, botLogPath, botsRoot, botTokenStateDir, botWorkerRelDir, buildBotDaemonPaths, createBotLogger, deleteBotCreds, installBotDaemon, repairBotDaemonIfStale, healBotDaemonNodeFromJob, introDmText, isBotMemoryMode, botLocalMemoryDir, botMemoryMode, resolveBotMemoryDir, validateBotIntro, validateBotDisplayName, validateBotKickoff, validateBotEffort, validateBotModel, effectiveBotEffort, BOT_EFFORT_LEVELS, DEFAULT_BOT_EFFORT, BOT_MEMORY_MODES, BOT_KINDS, isBotKind, effectiveBotKind, effectiveBotCompanies, normalizeBotCompanies, SETUP_BOT_WORKER_ID, isBotRuntimeId, botRuntimeFromBrainName, localNameForRemoteBot, remoteBotRunnability, isPidAlive, listBotWorkerOptions, patchBotConfig, readBotConfig, readBotCredsIdentity, readBotStatus, patchBotStatus, runtimeCrashSinceStart, resolveBotWorker, runBot, runtimeFor, scaffoldBotMemory, scaffoldBotWorker, startBotDaemon, stopBotDaemon, uninstallBotDaemon, validateBotName, writeBotConfig, writeBotCreds, BOT_RUNTIMES, BOT_INTRO_MAX_CHARS, BOT_DISPLAY_NAME_MAX_CHARS, BOT_KICKOFF_MAX_CHARS, detectBotPlatform, withBotLock, localBotRole, remoteBotRole, remoteBotDisplayName, personFacingName, writeCloudDisplayName, setupSlugFor, ASSISTANT_ROLE, HQ_FLEET_RUNTIME_ENGINE_ID, HQ_FLEET_LOCAL_RELEASE, authenticateFleetLocalBot, bootstrapFleetLocalBot, buildSystemPrompt, controlFleetBot as controlFleetLocalBot, fleetBotUnitId, fleetBotsManagedByDaemon, fleetLocalGatewayPid, fleetLocalProfileNeedsAdoption, fleetLocalServiceInstalled, fleetProviderForRuntime, importFleetLocalMachineCredential, importFleetLocalProviderLogin, fleetProviderNeedsSignIn, fleetOwnerCompanies, refreshFleetLocalInstructions, fleetLocalPromotionRuntime, installPinnedFleetLocalDistribution, installTargetFleetLocalDistribution, resolveFleetLocalPointerTarget, resolveFleetLocalTargetRelease, fleetLocalProfileDir, fleetProfileOwnerCompanies, fleetLocalChannels, readFleetLocalGatewayState, readFleetLocalIntroSentAt, readFleetLocalSignInNeeded, readPromptSources, removeFleetLocalBot, } from "../lib/bot/index.js";
84
+ import { BotApi, BotApiError, BOT_RESTORE_DEFAULTS, buildBotLocalConfig, describeBotLocalConfig, orphanBotRunMessage, parseBotLocalConfig, removeOrphanBotDaemon, botDaemonStatus, botDir, botCredsPath, botLogPath, botsRoot, botTokenStateDir, botWorkerRelDir, buildBotDaemonPaths, createBotLogger, deleteBotCreds, installBotDaemon, repairBotDaemonIfStale, healBotDaemonNodeFromJob, introDmText, isBotMemoryMode, botLocalMemoryDir, botMemoryMode, resolveBotMemoryDir, validateBotIntro, validateBotDisplayName, validateBotKickoff, validateBotEffort, validateBotModel, effectiveBotEffort, BOT_EFFORT_LEVELS, DEFAULT_BOT_EFFORT, BOT_MEMORY_MODES, BOT_KINDS, isBotKind, effectiveBotKind, effectiveBotCompanies, normalizeBotCompanies, SETUP_BOT_WORKER_ID, isBotRuntimeId, botRuntimeFromBrainName, localNameForRemoteBot, remoteBotRunnability, isPidAlive, listBotWorkerOptions, patchBotConfig, readBotConfig, readBotCredsIdentity, readBotStatus, patchBotStatus, runtimeCrashSinceStart, resolveBotWorker, runBot, runtimeFor, scaffoldBotMemory, scaffoldBotWorker, startBotDaemon, stopBotDaemon, uninstallBotDaemon, validateBotName, writeBotConfig, writeBotCreds, BOT_RUNTIMES, BOT_INTRO_MAX_CHARS, BOT_DISPLAY_NAME_MAX_CHARS, BOT_KICKOFF_MAX_CHARS, detectBotPlatform, withBotLock, localBotRole, remoteBotRole, remoteBotDisplayName, personFacingName, writeCloudDisplayName, setupSlugFor, ASSISTANT_ROLE, HQ_FLEET_RUNTIME_ENGINE_ID, HQ_FLEET_LOCAL_RELEASE, authenticateFleetLocalBot, bootstrapFleetLocalBot, buildSystemPrompt, controlFleetBot as controlFleetLocalBot, ensureFleetBotDaemon, FleetDaemonStoppedError, fleetBotUnitId, fleetBotsManagedByDaemon, fleetLocalGatewayPid, fleetLocalProfileNeedsAdoption, fleetLocalServiceInstalled, fleetProviderForRuntime, importFleetLocalMachineCredential, importFleetLocalProviderLogin, fleetProviderNeedsSignIn, fleetOwnerCompanies, refreshFleetLocalInstructions, fleetLocalPromotionRuntime, installPinnedFleetLocalDistribution, installTargetFleetLocalDistribution, resolveFleetLocalPointerTarget, resolveFleetLocalTargetRelease, fleetLocalProfileDir, fleetProfileOwnerCompanies, fleetLocalChannels, readFleetLocalGatewayState, readFleetLocalIntroSentAt, readFleetLocalSignInNeeded, readPromptSources, removeFleetLocalBot, } from "../lib/bot/index.js";
83
85
  import { gatedInteractiveLogin } from "../utils/interactive-caller.js";
84
86
  import { brainSignInStatus, fleetInstallProgressReporter, fleetRuntimeStatus, runBotAuthStatus, runBotRuntimeInstall, runBotRuntimeStatus, runBotSignIn } from "./bot-runtime.js";
85
87
  import { ensureFleetRuntimeInstalled } from "../lib/bot/fleet-local.js";
@@ -381,6 +383,28 @@ function allBotDirs() {
381
383
  return [];
382
384
  }
383
385
  }
386
+ /**
387
+ * Before a command that hands a bot to hq daemon: make sure the daemon is
388
+ * running (start it when its login item is installed but it is off). When it
389
+ * still is not up, fail with one plain sentence, and under --json leave the
390
+ * failure document on stdout first.
391
+ */
392
+ function requireLiveBotDaemon(name, json) {
393
+ reportDaemonStopped(name, json, () => ensureFleetBotDaemon(name));
394
+ }
395
+ /** Run a hand-off; under --json, a daemon that could not be started leaves its failure document on stdout before the error exits non-zero. */
396
+ function reportDaemonStopped(name, json, run) {
397
+ try {
398
+ return run();
399
+ }
400
+ catch (err) {
401
+ if (json && err instanceof FleetDaemonStoppedError && err.jsonReported !== true) {
402
+ console.log(JSON.stringify({ ok: false, name, running: false, reason: err.reason, message: err.message }, null, 2));
403
+ Object.assign(err, { jsonReported: true });
404
+ }
405
+ throw err;
406
+ }
407
+ }
384
408
  function refuseHeldFleetBot(dir) {
385
409
  if (hasPromotionHold(dir))
386
410
  throw new Error("This bot is held for cloud promotion. Continue its promotion before changing local settings or lifecycle.");
@@ -433,7 +457,7 @@ function runFleetRuntimeControl(name, config, action, output) {
433
457
  syncFleetRuntimeJobs(name, botDir(name), config);
434
458
  }
435
459
  const installService = action === "install" || (config.fleetServiceInstallPending === true && (action === "start" || action === "restart"));
436
- const result = controlFleetLocalBot(config.agentUid, installService ? "install" : action);
460
+ const result = reportDaemonStopped(name, json, () => controlFleetLocalBot(config.agentUid, installService ? "install" : action));
437
461
  if (installService && result.ok)
438
462
  patchBotConfig(botDir(name), { fleetServiceInstallPending: false, enabled: true });
439
463
  if (output === "silent")
@@ -563,6 +587,11 @@ function rowFor(name, opts = {}) {
563
587
  });
564
588
  // Turns this bot has taken and not finished: what "thinking" means.
565
589
  const inflightTurns = readInflightTurns(dir);
590
+ // A gateway that is still starting can carry a dead predecessor's
591
+ // active_agents; the runtime counts turns only once it is running.
592
+ const gatewayState = fleet ? readFleetLocalGatewayState(config.agentUid) : null;
593
+ const gatewayTurns = gatewayState && (gatewayState.gatewayState === "running" || gatewayState.gatewayState === "draining") ? gatewayState.activeAgents : 0;
594
+ const { busy, busySince } = botBusyState(processAlive, inflightTurns, gatewayTurns);
566
595
  let daemonInstalled = false;
567
596
  let daemonLoaded = false;
568
597
  let daemonNodeMissing = null;
@@ -598,8 +627,8 @@ function rowFor(name, opts = {}) {
598
627
  lastHeartbeatOk: status?.lastHeartbeatOk ?? null,
599
628
  lastInboxPollAt: status?.lastInboxPollAt ?? null,
600
629
  lastInboxPollOk: status?.lastInboxPollOk ?? null,
601
- busy: processAlive && inflightTurns.length > 0,
602
- busySince: processAlive ? (inflightTurns[0]?.startedAt ?? null) : null,
630
+ busy,
631
+ busySince,
603
632
  runtimeSignIn: status?.runtimeSignIn ?? null,
604
633
  runtimeSignInCheck: status?.runtimeSignInCheck ?? null,
605
634
  runtimeSignedIn: config.fleetAuthPending === true ? false : runtimeSignedIn(status, processAlive),
@@ -997,7 +1026,7 @@ async function startFleetRuntimeBot(name, dir, config, output, extra) {
997
1026
  const before = readBotStatus(dir);
998
1027
  const alreadyRunning = !!before && before.state === "running" && isPidAlive(before.pid);
999
1028
  const installService = adopted || config.fleetServiceInstallPending === true;
1000
- const result = controlFleetLocalBot(config.agentUid, installService ? "install" : alreadyRunning ? "restart" : "start");
1029
+ const result = reportDaemonStopped(name, output === "json", () => controlFleetLocalBot(config.agentUid, installService ? "install" : alreadyRunning ? "restart" : "start"));
1001
1030
  if (installService && result.ok)
1002
1031
  patchBotConfig(dir, { fleetServiceInstallPending: false, enabled: true });
1003
1032
  const how = alreadyRunning ? "restarted by the HQ Fleet Runtime" : "started by the HQ Fleet Runtime";
@@ -1535,6 +1564,11 @@ async function runBotCreateLocked(name, opts) {
1535
1564
  const fleetProvider = fleetProviderForRuntime(runtime, model);
1536
1565
  if (fleetProvider.id === "anthropic")
1537
1566
  requireClaudeCodeLoginForCreate(name);
1567
+ // A bot that starts now is handed to hq daemon where it runs this Mac's bots:
1568
+ // make sure it is up before HQ makes an identity for a bot that would never come online.
1569
+ // A ChatGPT or Grok bot starts now only when a login on this computer is found below.
1570
+ if (opts.start !== false && !fleetProviderNeedsSignIn(fleetProvider))
1571
+ requireLiveBotDaemon(name, opts.json);
1538
1572
  const token = await ownerToken();
1539
1573
  const owner = await resolveCallerPersonUid(token, undefined, { command: "hq bot create" });
1540
1574
  if (!owner)
@@ -1635,6 +1669,8 @@ async function runBotCreateLocked(name, opts) {
1635
1669
  ? await botCreateSeams.brainSignIn(runtime === "grok" ? "grok" : "chatgpt", { target: async () => fleetTarget })
1636
1670
  : null;
1637
1671
  const fleetAuthPending = brainLogin !== null && !brainLogin.signedIn;
1672
+ if (opts.start !== false && brainLogin?.signedIn === true)
1673
+ requireLiveBotDaemon(name, opts.json);
1638
1674
  const runtimeStatus = await botCreateSeams.runtimeStatus({ target: fleetTarget });
1639
1675
  if (!opts.json)
1640
1676
  console.log(chalk.dim(`Setting up ${name} takes ${runtimeStatus.estimate}.`));
@@ -1828,7 +1864,20 @@ async function runBotCreateLocked(name, opts) {
1828
1864
  throw Object.assign(new Error(`${name} was created, but the ${runtimeDisplayName(runtime)} login on this computer could not be reused (${cause}). Sign it in with ${fleetAuthCommand(name, { ...config, fleetAuthPending: true })}.`), { expected: true });
1829
1865
  }
1830
1866
  }
1831
- const startedByDaemon = startNow && daemonRunsFleetBots && controlFleetLocalBot(agentUid, "install").ok === true;
1867
+ let startedByDaemon = false;
1868
+ // The daemon was checked before the identity was made; if it stopped during
1869
+ // setup, the bot is created but reported offline with the reason, never as started.
1870
+ let daemonStopped = null;
1871
+ if (startNow && daemonRunsFleetBots) {
1872
+ try {
1873
+ startedByDaemon = controlFleetLocalBot(agentUid, "install").ok === true;
1874
+ }
1875
+ catch (err) {
1876
+ if (!(err instanceof FleetDaemonStoppedError))
1877
+ throw err;
1878
+ daemonStopped = err.message;
1879
+ }
1880
+ }
1832
1881
  const startedByRuntime = startNow && !daemonRunsFleetBots && brainLogin !== null && controlFleetLocalBot(agentUid, "install").ok === true;
1833
1882
  syncFleetRuntimeJobs(name, dir, config);
1834
1883
  const running = fleetBootstrap.running || startedByDaemon || startedByRuntime;
@@ -1894,6 +1943,8 @@ async function runBotCreateLocked(name, opts) {
1894
1943
  if (fleetAuthPending) {
1895
1944
  console.log(chalk.yellow(` sign it in before it can answer: hq bot auth ${name} --provider ${runtime === "grok" ? "grok" : "chatgpt"}`));
1896
1945
  }
1946
+ if (daemonStopped)
1947
+ console.log(chalk.yellow(` ${daemonStopped}`));
1897
1948
  const readyLine = createReadyLine(name, readiness, readyWait, readyTimeoutMs);
1898
1949
  if (readyLine)
1899
1950
  console.log(readyLine);
@@ -1918,7 +1969,7 @@ async function runBotCreateLocked(name, opts) {
1918
1969
  message: createReadyMessage(name, readiness, readyWait, readyTimeoutMs),
1919
1970
  state: status?.state ?? "unknown",
1920
1971
  pid: status?.pid ?? null,
1921
- lastError: status?.lastError ?? null,
1972
+ lastError: daemonStopped ?? status?.lastError ?? null,
1922
1973
  }, null, 2));
1923
1974
  }
1924
1975
  }
@@ -2061,7 +2112,7 @@ async function runBotResident(nameArg) {
2061
2112
  ...(signals ? { signals } : {}),
2062
2113
  sync: (syncInput) => runCompanyHotChannelSync({ hqRoot: config.hqRoot, ...syncInput }),
2063
2114
  // A new pass per run: the login preflight and the 20-document cap are per run.
2064
- signalsPass: createClaudeSignalsPass({ hqRoot: config.hqRoot, company: input.company }),
2115
+ signalsPass: createClaudeSignalsPass({ hqRoot: config.hqRoot, company: input.company, botRuntime: defaultResolveBotRuntime }),
2065
2116
  }));
2066
2117
  // Prefer the Executive bot for daily hot-channel sync. Other personal bots
2067
2118
  // keep their company covered until the Executive has a replacement job.
@@ -3679,6 +3730,9 @@ export async function runBotAdopt(nameArg, opts) {
3679
3730
  }
3680
3731
  throw Object.assign(new Error(runnable.message), { expected: true });
3681
3732
  }
3733
+ // Before new credentials are issued for a bot that would start under a stopped hq daemon.
3734
+ if (opts.start !== false)
3735
+ requireLiveBotDaemon(name, opts.json);
3682
3736
  await withBotLock(name, async () => {
3683
3737
  if (readBotConfig(dir)) {
3684
3738
  throw Object.assign(new Error(`Bot "${name}" is already set up on this computer (${dir}). Start it with: hq bot start ${name}`), {
@@ -3742,7 +3796,15 @@ async function repairLocalBot(name, api, bot, daemon) {
3742
3796
  const adopted = await adoptFleetRuntimeProfile(name, dir, config);
3743
3797
  if (!adopted)
3744
3798
  importFleetLocalMachineCredential(bot.agentUid, botCredsPath(dir));
3745
- const restarted = controlFleetLocalBot(bot.agentUid, adopted ? "install" : "restart").ok === true;
3799
+ let restarted;
3800
+ try {
3801
+ restarted = controlFleetLocalBot(bot.agentUid, adopted ? "install" : "restart").ok === true;
3802
+ }
3803
+ catch (err) {
3804
+ if (!(err instanceof FleetDaemonStoppedError))
3805
+ throw err;
3806
+ return `new credentials; the HQ Fleet Runtime did not restart: ${err.message}`;
3807
+ }
3746
3808
  return restarted ? "new credentials, HQ Fleet Runtime restarted" : "new credentials; the HQ Fleet Runtime did not restart (hq bot start " + name + ")";
3747
3809
  }
3748
3810
  if (daemon && process.platform === "darwin") {
@@ -3763,6 +3825,9 @@ export async function runBotRestore(opts) {
3763
3825
  json: opts.json,
3764
3826
  emptyResult: { dryRun: opts.dryRun === true, restored: 0, repaired: 0, skipped: 0, failed: 0, bots: [] },
3765
3827
  }));
3828
+ // Restored bots start under hq daemon where it runs this Mac's bots; make sure it is up first.
3829
+ if (opts.dryRun !== true && opts.start !== false && bots.length > 0)
3830
+ requireLiveBotDaemon("", opts.json);
3766
3831
  const rows = [];
3767
3832
  for (const bot of bots) {
3768
3833
  const name = localNameForRemoteBot(bot);
@@ -12,6 +12,7 @@ import { Command } from "commander";
12
12
  import { type CapacityState, type LedgerEvent, type LedgerOptions, type NowView, type ParserFailureEvent, type Reading, type ReadingSource } from "../lib/capacity/ledger.js";
13
13
  import { type CapacityAccount } from "../lib/capacity/accounts.js";
14
14
  import { type ClaudeRefreshLastEntry } from "../lib/capacity/collectors/claude-oauth.js";
15
+ import type { AvailableDeps } from "../lib/capacity/available.js";
15
16
  export declare const CAPACITY_SCHEMA_VERSION: "hq-capacity-now-view.v1";
16
17
  export declare const DOCTOR_SCHEMA_VERSION = "hq-capacity-doctor.v1";
17
18
  export declare const PARSER_FAILURE_WINDOW_MS: number;
@@ -92,5 +93,7 @@ export declare function formatCapacityTable(view: NowView, nowMs: number, accoun
92
93
  export declare function formatHistory(readings: Reading[]): string;
93
94
  export declare function buildDoctorReport(options?: LedgerOptions): DoctorReport;
94
95
  export declare function formatDoctor(report: DoctorReport): string;
95
- export declare function registerCapacityCommand(program: Command): Command;
96
+ export declare function registerCapacityCommand(program: Command, deps?: {
97
+ available?: AvailableDeps;
98
+ }): Command;
96
99
  //# sourceMappingURL=capacity.d.ts.map
@@ -4,12 +4,12 @@ import * as fs from "node:fs";
4
4
  import * as os from "node:os";
5
5
  import * as path from "node:path";
6
6
  import * as readline from "node:readline";
7
- import { LedgerCorrupt, LedgerMissing, READING_SOURCES, capacityOptionsFromEnv, capacityRoot, nowViewJsonSchema, readCollectorMark, readLedgerEvents, readNow, rebuildNow, redactProviderTokens, setCollectorEnabled, } from "../lib/capacity/ledger.js";
7
+ import { LedgerCorrupt, LedgerMissing, READING_SOURCES, capacityOptionsFromEnv, capacityRoot, nowViewJsonSchema, readCollectorMark, readLedgerEvents, rebuildNow, redactProviderTokens, setCollectorEnabled, readCurrentNow, } from "../lib/capacity/ledger.js";
8
8
  import { listCapacityAccounts, registryAccountIds } from "../lib/capacity/accounts.js";
9
9
  import { claudeIdentityKeys, readClaudeRefreshLast } from "../lib/capacity/collectors/claude-oauth.js";
10
10
  import { projectCapacityView } from "../lib/capacity/project.js";
11
11
  import { capacityViewAge } from "../lib/capacity/freshness.js";
12
- import { capacityWidgetTimeZone, renderCapacityWidget } from "../lib/capacity/widget.js";
12
+ import { accountScopeName, bankedResets, capacityWidgetTimeZone, renderCapacityWidget, resetGrantName } from "../lib/capacity/widget.js";
13
13
  import { resolveLanesHqRoot } from "../lib/lanes/hq-root.js";
14
14
  import { loadLanesConfig } from "../lib/lanes/config.js";
15
15
  import { readAllLanes } from "../lib/lanes/store.js";
@@ -120,7 +120,11 @@ export function formatCapacityTable(view, nowMs, accounts = []) {
120
120
  && account.limits.some((limit) => limit.state === "exhausted")
121
121
  && hasCodexCreditRoom(account.limits, nowMs)
122
122
  ? " — usable on Codex credits (ranked last)" : "";
123
- return `${title}${creditNote}\n${formatLimitTable(account.limits, nowMs)}`;
123
+ const banked = bankedResets(account, nowMs);
124
+ const resetNote = banked.length === 0
125
+ ? ""
126
+ : `\nresets banked: ${banked.map((credit) => `${(credit.remaining ?? 1) > 1 ? `${credit.remaining} x ` : ""}${resetGrantName(credit, accountScopeName(account))}${credit.expiresAt === null ? "" : ` (expires ${new Date(credit.expiresAt).toISOString().slice(0, 10)})`}`).join("; ")}`;
127
+ return `${title}${creditNote}\n${formatLimitTable(account.limits, nowMs)}${resetNote}`;
124
128
  });
125
129
  return [head, ...blocks].join("\n");
126
130
  }).join("\n\n");
@@ -296,7 +300,7 @@ function formatSignedSpan(ms) {
296
300
  const span = formatSpan(Math.floor(Math.abs(ms) / 1000));
297
301
  return ms < 0 ? `-${span}` : span;
298
302
  }
299
- export function registerCapacityCommand(program) {
303
+ export function registerCapacityCommand(program, deps = {}) {
300
304
  const capacity = program
301
305
  .command("capacity")
302
306
  .description("Show provider capacity from the local ledger (read-only; enable, login, and ingest write to it)")
@@ -359,6 +363,36 @@ export function registerCapacityCommand(program) {
359
363
  process.exitCode = 1;
360
364
  });
361
365
  });
366
+ capacity
367
+ .command("available")
368
+ .description("What AI can run now, as one token-free hq-available-ai.v1 document (read-only; a stale view starts one background read)")
369
+ .option("--json", "Print the document as JSON")
370
+ .option("--fresh", "Start a read and wait for it, at most 3 seconds")
371
+ .option("--include-other", "Also list capacity-only accounts, each with its organization")
372
+ .action(async (_opts, command) => {
373
+ const opts = command.optsWithGlobals();
374
+ const { readAvailable, formatAvailableText } = await import("../lib/capacity/available.js");
375
+ const document = await readAvailable({ options: capacityOptionsFromEnv(), includeOther: opts.includeOther, fresh: opts.fresh }, deps.available);
376
+ console.log(opts.json ? JSON.stringify(document, null, 2) : formatAvailableText(document));
377
+ });
378
+ capacity
379
+ .command("collect-once", { hidden: true })
380
+ .description("One capacity read, started in the background by hq capacity available")
381
+ .action(async () => {
382
+ const { COLLECT_TOKEN_ENV, releaseCollectMark } = await import("../lib/capacity/available.js");
383
+ try {
384
+ const { collectCapacityOnce } = await import("../lib/capacity/collect.js");
385
+ await collectCapacityOnce({ env: process.env, hqRoot: process.env.HQ_ROOT });
386
+ }
387
+ catch {
388
+ // Failure classes stay in hq capacity doctor and logs.
389
+ }
390
+ finally {
391
+ // Free this collect's own single-flight mark, so the next read starts a
392
+ // collect at once. A mark a later collect holds is left alone.
393
+ releaseCollectMark(capacityOptionsFromEnv(), process.env[COLLECT_TOKEN_ENV]);
394
+ }
395
+ });
362
396
  capacity
363
397
  .command("route")
364
398
  .description("Pick the account with the most capacity for a new lane (read-only; port of boss-route)")
@@ -475,11 +509,11 @@ export function registerCapacityCommand(program) {
475
509
  });
476
510
  ingest
477
511
  .command("refusal")
478
- .description("Record a classified provider rate-limit refusal as an exhausted reading")
512
+ .description("Record a classified provider refusal as a hold on one named account")
479
513
  .option("--provider <name>", "claude, codex, or grok")
480
- .option("--limit-id <id>", "Limit to mark; default is the provider's weekly_all id in now.json, else weekly")
481
- .option("--resets-at <when>", "UTC timestamp or epoch when this limit resets")
482
- .option("--account <hash>", "Hashed account id; default is the account on the chosen limit")
514
+ .option("--limit-id <id>", "The account's limit this refusal is about; without it the refusal claims no window")
515
+ .option("--resets-at <when>", "UTC timestamp or epoch when the hold ends")
516
+ .option("--account <hash>", "Hashed account id of the account that refused. Required unless --limit-id names a limit exactly one account has")
483
517
  .option("--json", "Print the recorded limit as JSON")
484
518
  .addHelpText("after", `\n${REFUSAL_HELP}\n`)
485
519
  .action((opts, command) => {
@@ -494,7 +528,9 @@ export function registerCapacityCommand(program) {
494
528
  console.log(JSON.stringify(record, null, 2));
495
529
  return;
496
530
  }
497
- console.log(`Recorded refusal for ${record.provider} ${record.limitId}; state ${record.state}.`);
531
+ console.log(record.inForce
532
+ ? `Recorded refusal for ${record.provider} ${record.limitId}; state ${record.state}.`
533
+ : `Recorded refusal for ${record.provider} ${record.limitId}; the hold is not in force: its reset has passed or a newer reading answers it.`);
498
534
  });
499
535
  });
500
536
  capacity
@@ -741,7 +777,7 @@ function runCli(action) {
741
777
  }
742
778
  function loadNow(options) {
743
779
  try {
744
- return readNow(options);
780
+ return readCurrentNow(options);
745
781
  }
746
782
  catch (err) {
747
783
  if (!(err instanceof LedgerCorrupt))
@@ -17,10 +17,19 @@
17
17
  * 3. Strip `cloud_uid` + `bucket_name` from `companies/manifest.yaml`'s
18
18
  * `companies.<slug>` entry. The slug entry + other fields stay.
19
19
  *
20
- * Safety check (default on): `findCompanyBySlug` MUST return an entity with
21
- * `deleted: true`. A live entity, or no entity at all, refuses with code 2.
22
- * `--force` skips the network call (AppBar passes it because Path A just
23
- * checked).
20
+ * Safety check (default on): `findCompanyBySlug` returning an entity with
21
+ * `deleted: true` passes; a live entity refuses with code 2. hq-pro hides a
22
+ * retired company from by-slug, so on a miss demote reads `companyUid` and
23
+ * `companySlug` from the company's own `.hq/config.json`. It refuses if
24
+ * either is missing or the slug differs, then calls `getCompanyByUid`:
25
+ * - 200 with `deleted: true` and matching slug/uid passes; live refuses;
26
+ * - 404 passes, because hq-pro answers 404 for a retired company. The
27
+ * result's `cloud_check` names the 404 and says demote proceeded because
28
+ * the company is retired or gone;
29
+ * - any other error (403, 5xx, network) refuses.
30
+ * Every refusal names `--force`, which skips the network calls (AppBar
31
+ * passes it because Path A just checked). Nothing in the cloud is deleted
32
+ * or detached by demote.
24
33
  *
25
34
  * Exit codes (mirrors cloud-provision):
26
35
  * 0 — success or idempotent no-op.
@@ -45,6 +54,12 @@ export interface DemoteResult {
45
54
  * a non-deleted entity throws code 2 before reaching the result.)
46
55
  */
47
56
  cloud_was_deleted: boolean | null;
57
+ /**
58
+ * Set only when demote proceeded on a 404 from GET /entity/{uid} for the
59
+ * locally recorded uid (hq-pro returns 404 for a retired company). Says
60
+ * what was checked and why demote went ahead.
61
+ */
62
+ cloud_check?: string;
48
63
  }
49
64
  export interface DemoteCompanyOptions {
50
65
  slug: string;
@@ -17,10 +17,19 @@
17
17
  * 3. Strip `cloud_uid` + `bucket_name` from `companies/manifest.yaml`'s
18
18
  * `companies.<slug>` entry. The slug entry + other fields stay.
19
19
  *
20
- * Safety check (default on): `findCompanyBySlug` MUST return an entity with
21
- * `deleted: true`. A live entity, or no entity at all, refuses with code 2.
22
- * `--force` skips the network call (AppBar passes it because Path A just
23
- * checked).
20
+ * Safety check (default on): `findCompanyBySlug` returning an entity with
21
+ * `deleted: true` passes; a live entity refuses with code 2. hq-pro hides a
22
+ * retired company from by-slug, so on a miss demote reads `companyUid` and
23
+ * `companySlug` from the company's own `.hq/config.json`. It refuses if
24
+ * either is missing or the slug differs, then calls `getCompanyByUid`:
25
+ * - 200 with `deleted: true` and matching slug/uid passes; live refuses;
26
+ * - 404 passes, because hq-pro answers 404 for a retired company. The
27
+ * result's `cloud_check` names the 404 and says demote proceeded because
28
+ * the company is retired or gone;
29
+ * - any other error (403, 5xx, network) refuses.
30
+ * Every refusal names `--force`, which skips the network calls (AppBar
31
+ * passes it because Path A just checked). Nothing in the cloud is deleted
32
+ * or detached by demote.
24
33
  *
25
34
  * Exit codes (mirrors cloud-provision):
26
35
  * 0 — success or idempotent no-op.
@@ -32,6 +41,7 @@ import * as path from "node:path";
32
41
  import * as yaml from "js-yaml";
33
42
  import { parseUserYaml } from "../utils/user-yaml-error.js";
34
43
  import chalk from "chalk";
44
+ import { readLocalCompanyUid } from "./cloud-retire.js";
35
45
  import { ProvisionError, companyConfigPath, companyDirPath, createDefaultVaultClient, manifestPath, validateManifestAndDir, validateSlug, } from "./cloud-provision.js";
36
46
  import { DEFAULT_HQ_ROOT, DEFAULT_VAULT_API_URL, ensureCognitoToken, } from "../utils/cognito-session.js";
37
47
  // ── Helpers ──────────────────────────────────────────────────────────────────
@@ -106,6 +116,7 @@ export async function demoteCompany(options) {
106
116
  // be a silent no-op (all helpers return false but we'd still report ok=true).
107
117
  validateManifestAndDir(options.hqRoot, options.slug);
108
118
  let cloudWasDeleted = null;
119
+ let cloudCheck;
109
120
  if (!options.force) {
110
121
  const accessToken = options.resolveAccessToken
111
122
  ? await options.resolveAccessToken()
@@ -117,17 +128,55 @@ export async function demoteCompany(options) {
117
128
  entity = await client.findCompanyBySlug(options.slug);
118
129
  }
119
130
  catch (err) {
120
- if (err instanceof ProvisionError)
121
- throw err;
122
- throw new ProvisionError(1, `Vault GET by-slug failed: ${err instanceof Error ? err.message : String(err)}`);
131
+ throw refusal(options.slug, err, "the by-slug lookup failed");
123
132
  }
124
133
  if (!entity) {
125
- throw new ProvisionError(2, `Refusing to demote '${options.slug}': no cloud entity found. Pass --force to demote anyway.`);
134
+ // The by-slug route filters out soft-tombstoned entities, so a miss
135
+ // right after `hq cloud retire company` is the expected shape of a
136
+ // retired company. Fall back to the uid recorded locally in
137
+ // `.hq/config.json` (the same fallback retire uses) and read the
138
+ // entity by uid instead.
139
+ const localUid = readLocalCompanyUid(options.hqRoot, options.slug);
140
+ if (!localUid) {
141
+ throw new ProvisionError(2, `Refusing to demote '${options.slug}': no cloud entity found by slug and no local cloud uid in the company's .hq/config.json. Pass --force to demote anyway.`);
142
+ }
143
+ // A copied or stale config can carry another company's uid. The 404
144
+ // rule below trusts the uid only when the same file names this slug.
145
+ const localSlug = readLocalCompanySlug(options.hqRoot, options.slug);
146
+ if (localSlug !== options.slug) {
147
+ throw new ProvisionError(2, `Refusing to demote '${options.slug}': its .hq/config.json records companySlug '${localSlug ?? "(missing)"}', not '${options.slug}'. Nothing was changed. Fix the config, or pass --force to demote anyway.`);
148
+ }
149
+ let byUid;
150
+ try {
151
+ byUid = await client.getCompanyByUid(localUid);
152
+ }
153
+ catch (err) {
154
+ if (!(err instanceof ProvisionError && err.httpStatus === 404)) {
155
+ throw refusal(options.slug, err, `GET /entity/${localUid} failed`);
156
+ }
157
+ // hq-pro answers GET /entity/{uid} with 404 for a tombstoned
158
+ // (retired) company and has no caller-readable tombstone route. The
159
+ // uid and slug both come from this company's own .hq/config.json and
160
+ // the by-slug lookup also missed, so treat the 404 as retired or
161
+ // gone. Demote only touches local files; nothing in the cloud is
162
+ // deleted or detached. Any other error (403, 5xx, network) refuses.
163
+ cloudCheck = `No cloud entity found by slug, and GET /entity/${localUid} (the uid in this company's .hq/config.json) returned 404. Demote proceeded because the company is retired or gone.`;
164
+ }
165
+ if (byUid) {
166
+ // Retire is a soft delete: the entity row keeps its slug and uid.
167
+ // Require both to match before treating it as this slug's entity.
168
+ if (byUid.slug !== options.slug || byUid.uid !== localUid) {
169
+ throw new ProvisionError(2, `Refusing to demote '${options.slug}': the cloud uid in its .hq/config.json (${localUid}) belongs to a different company (slug '${byUid.slug}'). Nothing was changed. Fix the config, or pass --force to demote anyway.`);
170
+ }
171
+ entity = byUid;
172
+ }
126
173
  }
127
- // `deleted` is added by hq-pro and isn't in the static VaultEntity type.
128
- const deleted = entity.deleted === true;
129
- if (!deleted) {
130
- throw new ProvisionError(2, `Refusing to demote '${options.slug}': cloud entity is not deleted (uid=${entity.uid}). Pass --force to demote anyway.`);
174
+ if (entity) {
175
+ // `deleted` is added by hq-pro and isn't in the static VaultEntity type.
176
+ const deleted = entity.deleted === true;
177
+ if (!deleted) {
178
+ throw new ProvisionError(2, `Refusing to demote '${options.slug}': cloud entity is not deleted (uid=${entity.uid}). Pass --force to demote anyway.`);
179
+ }
131
180
  }
132
181
  cloudWasDeleted = true;
133
182
  }
@@ -146,8 +195,29 @@ export async function demoteCompany(options) {
146
195
  yaml_flipped: yamlFlipped,
147
196
  manifest_stripped: manifestStripped,
148
197
  cloud_was_deleted: cloudWasDeleted,
198
+ ...(cloudCheck ? { cloud_check: cloudCheck } : {}),
149
199
  };
150
200
  }
201
+ /** Wrap a failed safety-check call into a refusal that keeps the --force hint. */
202
+ function refusal(slug, err, what) {
203
+ const detail = err instanceof Error ? err.message : String(err);
204
+ return new ProvisionError(err instanceof ProvisionError ? err.code : 1, `Refusing to demote '${slug}': ${what} (${detail}). Nothing was changed. Pass --force to demote anyway.`);
205
+ }
206
+ /** `companySlug` from `companies/<slug>/.hq/config.json`, or null. */
207
+ function readLocalCompanySlug(hqRoot, slug) {
208
+ const cPath = companyConfigPath(hqRoot, slug);
209
+ if (!fs.existsSync(cPath))
210
+ return null;
211
+ try {
212
+ const parsed = JSON.parse(fs.readFileSync(cPath, "utf-8"));
213
+ return typeof parsed.companySlug === "string" && parsed.companySlug.length > 0
214
+ ? parsed.companySlug
215
+ : null;
216
+ }
217
+ catch {
218
+ return null;
219
+ }
220
+ }
151
221
  // ── Commander wiring ─────────────────────────────────────────────────────────
152
222
  /**
153
223
  * Register `demote company <slug>` under the `cloud` command group. Wired in
@@ -176,6 +246,9 @@ export function registerCloudDemoteCommands(program) {
176
246
  vaultApiUrl: options.vaultApiUrl,
177
247
  force: options.force,
178
248
  });
249
+ if (result.cloud_check) {
250
+ process.stderr.write(chalk.yellow(`[hq cloud demote] ${result.cloud_check}\n`));
251
+ }
179
252
  process.stdout.write(JSON.stringify(result) + "\n");
180
253
  process.exit(0);
181
254
  }
@@ -163,7 +163,11 @@ export interface VaultClient {
163
163
  export declare class ProvisionError extends Error {
164
164
  readonly code: 1 | 2 | 3;
165
165
  readonly partial?: Partial<ProvisionResult> | undefined;
166
- constructor(code: 1 | 2 | 3, message: string, partial?: Partial<ProvisionResult> | undefined);
166
+ /** HTTP status of the failed vault response, when there was one. */
167
+ readonly httpStatus?: number | undefined;
168
+ constructor(code: 1 | 2 | 3, message: string, partial?: Partial<ProvisionResult> | undefined,
169
+ /** HTTP status of the failed vault response, when there was one. */
170
+ httpStatus?: number | undefined);
167
171
  }
168
172
  /**
169
173
  * Validate a company slug per the contract: alphanumeric / dot / dash / underscore,
@@ -57,10 +57,14 @@ function hasLocalSharedStarterPath(hqRoot, slug) {
57
57
  export class ProvisionError extends Error {
58
58
  code;
59
59
  partial;
60
- constructor(code, message, partial) {
60
+ httpStatus;
61
+ constructor(code, message, partial,
62
+ /** HTTP status of the failed vault response, when there was one. */
63
+ httpStatus) {
61
64
  super(message);
62
65
  this.code = code;
63
66
  this.partial = partial;
67
+ this.httpStatus = httpStatus;
64
68
  this.name = "ProvisionError";
65
69
  }
66
70
  }
@@ -364,7 +368,7 @@ export function createDefaultVaultClient(apiUrl, accessToken) {
364
368
  return withVaultRequest(url, { method: "GET", headers }, async (res) => {
365
369
  if (!res.ok) {
366
370
  const body = await safeBody(res);
367
- throw new ProvisionError(1, `Vault GET /entity/${uid} failed: ${res.status} ${res.statusText} — ${body}`);
371
+ throw new ProvisionError(1, `Vault GET /entity/${uid} failed: ${res.status} ${res.statusText} — ${body}`, undefined, res.status);
368
372
  }
369
373
  const data = (await res.json());
370
374
  if (!data.entity) {
@@ -490,6 +490,10 @@ export interface ShareCallResult {
490
490
  filesUploaded: number;
491
491
  bytesUploaded: number;
492
492
  filesSkipped: number;
493
+ /** Per-kind skip counts from hq-cloud; absent on an older engine. */
494
+ filesSkippedDetail?: PushSkipDetail;
495
+ /** Non-up-to-date skip reasons this CLI tallied from the push's `reconciled` events. */
496
+ skipReasons?: PushSkipReasonCounts;
493
497
  filesDeleted: number;
494
498
  filesExcludedByScope: number;
495
499
  filesRefusedStale?: number;
@@ -773,5 +777,37 @@ export declare function printReadOnlyLocalOnly(hqRoot: string, journals: Readonl
773
777
  export declare function printServerOwnedLocalOnly(hqRoot: string, journals: ReadonlyArray<StatusJournal>, log?: (line: string) => void, opts?: {
774
778
  all?: boolean;
775
779
  }): number;
780
+ interface PushSkipDetail {
781
+ upToDate: number;
782
+ conflict: number;
783
+ brokenLink: number;
784
+ other: number;
785
+ }
786
+ export type PushSkipReasonCounts = Partial<Record<string, number>>;
787
+ /** Tallies push `reconciled` skip reasons (other than up to date) so every summary can name them. */
788
+ export declare function createPushSkipReasonTracker(): {
789
+ observe: (event: {
790
+ type: string;
791
+ direction?: unknown;
792
+ reason?: unknown;
793
+ }) => void;
794
+ counts: () => PushSkipReasonCounts | undefined;
795
+ };
796
+ /**
797
+ * The one summary every push print site uses. Up-to-date skips read "already
798
+ * up to date" and each other reason is named in words. Conflicts, broken
799
+ * links and reasons that need a look are grouped as "N skipped (...)" and
800
+ * set `warn` so callers can mark the line. Skips with no named reason are
801
+ * counted as a plain "N skipped" and never warn. The counts always add up
802
+ * to filesSkipped.
803
+ */
804
+ export declare function describePushSkips(result: {
805
+ filesSkipped: number;
806
+ filesSkippedDetail?: PushSkipDetail;
807
+ skipReasons?: PushSkipReasonCounts;
808
+ }): {
809
+ text: string;
810
+ warn: boolean;
811
+ };
776
812
  export {};
777
813
  //# sourceMappingURL=cloud.d.ts.map