@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
@@ -3,7 +3,7 @@ import { localDate } from "./local-date.js";
3
3
  import { type LockTakeover } from "./run-lock.js";
4
4
  import { type UploadDeps } from "./steps/upload.js";
5
5
  import { type SignalsRunAlertSenders } from "./failure-alert.js";
6
- import type { RaiseSignalsFailureAlertsResult } from "../hot-channels/alert.js";
6
+ import { type RaiseSignalsFailureAlertsResult } from "../hot-channels/alert.js";
7
7
  import type { ErrorKind, HotChannelSyncFn, SignalsStep, SpawnSyncFn, StepFailure, StepName, StepStatus } from "./steps/types.js";
8
8
  import type { AdapterFlagReader } from "./adapters-catalog.js";
9
9
  export declare const SIGNALS_TRIGGERS: readonly ["job", "chat", "manual", "brief"];
@@ -77,7 +77,11 @@ export interface RunRecord {
77
77
  partialReason: string | null;
78
78
  /** v1 name of partialReason, kept for older readers. */
79
79
  partial: string | null;
80
- /** In-memory only: this call found the day's job already ran and did nothing. */
80
+ /**
81
+ * A later `--trigger job` call found the day's job already ran and ran no
82
+ * step. Written to the record on disk (US-002 AC4); a later non-job run
83
+ * writes a fresh record with false.
84
+ */
81
85
  alreadyRanToday: boolean;
82
86
  counts: {
83
87
  sourcesIn: number;
@@ -203,4 +207,27 @@ export declare function runSignals(opts: RunSignalsOptions): Promise<RunSignalsR
203
207
  * else 0 (complete, partial, skipped, already ran).
204
208
  */
205
209
  export declare function signalsExitCode(result: RunSignalsResult): 0 | 1 | 3;
210
+ /**
211
+ * The stopped-run check (US-018 AC1). The end-of-run alert in `runSignals`
212
+ * never fires for a run that hangs or dies, so each bot job fire and retry
213
+ * calls this first: when today's record for the company is still `running`
214
+ * with no live run lock, or `failed`, it is judged as a failed run by the
215
+ * same rule, formatter, owner DM and hourly dedupe as the end-of-run alert
216
+ * (`raiseSignalsRunAlerts`). A run whose extract step never finished alerts
217
+ * only when its adapters step landed sources, as the end-of-run alert does.
218
+ * One run is alerted once: when the shared dedupe file already holds an
219
+ * alert sent at or after the run started, nothing is sent. Never throws.
220
+ */
221
+ export declare function raiseStoppedRunAlert(input: {
222
+ hqRoot: string;
223
+ company: string;
224
+ now: () => Date;
225
+ senders: SignalsRunAlertSenders;
226
+ isPidAlive?: (pid: number) => boolean;
227
+ /**
228
+ * 1 checks yesterday's record instead of today's: a run that hung after the
229
+ * morning fire usually has no later fire that day. Default 0 (today).
230
+ */
231
+ daysAgo?: 0 | 1;
232
+ }): Promise<RaiseSignalsFailureAlertsResult | null>;
206
233
  //# sourceMappingURL=engine.d.ts.map
@@ -16,12 +16,13 @@ import { loadSignalsSettings, loadIncrementalSettings } from "./settings.js";
16
16
  import { createIncrementalStep } from "./incremental.js";
17
17
  import { localDate } from "./local-date.js";
18
18
  import { guardedWrite, WriteGuardError } from "./write-guard.js";
19
- import { acquireCompanyLock, withSummaryLock } from "./run-lock.js";
19
+ import { LOCK_STALE_MS, acquireCompanyLock, companyLockRel, defaultIsPidAlive, withSummaryLock, } from "./run-lock.js";
20
20
  import { gardenStep } from "./steps/garden.js";
21
21
  import { adaptersStep } from "./steps/adapters.js";
22
22
  import { extractStep, redoItemChannel } from "./steps/extract.js";
23
23
  import { uploadStep } from "./steps/upload.js";
24
- import { raiseSignalsRunAlerts } from "./failure-alert.js";
24
+ import { SIGNALS_RUN_ALERT_ADAPTER, raiseSignalsRunAlerts, resolveSignedInAlertPerson, } from "./failure-alert.js";
25
+ import { signalsAlertKey, signalsAlertStatePath } from "../hot-channels/alert.js";
25
26
  export const SIGNALS_TRIGGERS = ["job", "chat", "manual", "brief"];
26
27
  export const SIGNALS_STEP_CHOICES = ["garden", "extract", "adapters", "upload", "all"];
27
28
  export const STEP_ORDER = ["garden", "adapters", "extract", "garden", "upload"];
@@ -360,12 +361,26 @@ export async function runSignals(opts) {
360
361
  if (takeover) {
361
362
  process.stderr.write(`hq signals: ${company}: took over a stale lock (${takeover.reason}) from pid ${takeover.pid}, started ${takeover.startedAt}\n`);
362
363
  }
363
- // 2. The day's job already ran: do nothing and leave the record as it is.
364
+ // 2. The day's job already ran: run no step. The record keeps the
365
+ // earlier run's outcome and is only marked alreadyRanToday (US-002 AC4).
364
366
  const prior = readJson(hqRoot, rel);
365
367
  const priorJobRanAt = typeof prior?.jobRanAt === "string" ? prior.jobRanAt : null;
366
368
  if (!opts.incremental && trigger === "job" && !opts.force && prior && priorJobRanAt) {
367
369
  process.stderr.write(`hq signals: ${company}: already-ran (the job ran at ${priorJobRanAt})\n`);
368
- records.push({ ...prior, alreadyRanToday: true });
370
+ const marked = { ...prior, alreadyRanToday: true };
371
+ if (!dryRun && prior.alreadyRanToday !== true) {
372
+ // The marker is a note on the earlier run's record. A failed write must
373
+ // not reach the catch below, which would replace that record (often
374
+ // complete) with a failed one; the record stays as it was.
375
+ try {
376
+ write(rel, `${JSON.stringify(marked, null, 2)}\n`);
377
+ }
378
+ catch (err) {
379
+ const msg = err instanceof Error ? err.message : String(err);
380
+ process.stderr.write(`hq signals: ${company}: could not mark the run record alreadyRanToday: ${msg}\n`);
381
+ }
382
+ }
383
+ records.push(marked);
369
384
  continue;
370
385
  }
371
386
  record.jobRanAt = priorJobRanAt;
@@ -521,4 +536,88 @@ export function signalsExitCode(result) {
521
536
  return 3;
522
537
  return 0;
523
538
  }
539
+ /** Why today's record counts as stopped, or null when it does not. */
540
+ function stoppedRunReason(hqRoot, record, date, nowMs, isPidAlive) {
541
+ if (record.status === "failed")
542
+ return record.failureReason ?? "The run failed.";
543
+ if (record.status !== "running")
544
+ return null;
545
+ // The run lock's own staleness rule (run-lock.ts): no lock, a dead pid, or a
546
+ // lock older than LOCK_STALE_MS. A live lock is a run still in progress.
547
+ const holder = readJson(hqRoot, companyLockRel(date, record.company));
548
+ const step = record.currentStep ? ` at the ${record.currentStep} step` : "";
549
+ const lead = `The run that started ${record.startedAt} stopped${step} and never finished`;
550
+ if (!holder || typeof holder.pid !== "number" || typeof holder.startedAt !== "string")
551
+ return `${lead}: it holds no run lock.`;
552
+ if (!isPidAlive(holder.pid))
553
+ return `${lead}: its process (pid ${holder.pid}) is gone.`;
554
+ if (nowMs - Date.parse(holder.startedAt) > LOCK_STALE_MS) {
555
+ return `${lead}: it has held the run lock for more than ${LOCK_STALE_MS / 3_600_000} hours.`;
556
+ }
557
+ return null;
558
+ }
559
+ /**
560
+ * The stopped-run check (US-018 AC1). The end-of-run alert in `runSignals`
561
+ * never fires for a run that hangs or dies, so each bot job fire and retry
562
+ * calls this first: when today's record for the company is still `running`
563
+ * with no live run lock, or `failed`, it is judged as a failed run by the
564
+ * same rule, formatter, owner DM and hourly dedupe as the end-of-run alert
565
+ * (`raiseSignalsRunAlerts`). A run whose extract step never finished alerts
566
+ * only when its adapters step landed sources, as the end-of-run alert does.
567
+ * One run is alerted once: when the shared dedupe file already holds an
568
+ * alert sent at or after the run started, nothing is sent. Never throws.
569
+ */
570
+ export async function raiseStoppedRunAlert(input) {
571
+ const log = input.senders.log ?? (() => { });
572
+ try {
573
+ const at = input.now();
574
+ const day = input.daysAgo === 1 ? new Date(at.getFullYear(), at.getMonth(), at.getDate() - 1, 12) : at;
575
+ const date = localDate(day);
576
+ const record = readJson(input.hqRoot, runRecordRel(date, input.company));
577
+ if (!record || typeof record !== "object" || record.dryRun || !Array.isArray(record.steps))
578
+ return null;
579
+ if (record.company !== input.company || typeof record.startedAt !== "string")
580
+ return null;
581
+ const reason = stoppedRunReason(input.hqRoot, record, date, at.getTime(), input.isPidAlive ?? defaultIsPidAlive);
582
+ if (reason === null)
583
+ return null;
584
+ const person = await (input.senders.resolvePerson ?? resolveSignedInAlertPerson)(input.company);
585
+ if (!person) {
586
+ log(`signals alert for ${input.company} skipped: no signed-in person to alert`);
587
+ return null;
588
+ }
589
+ if (alertedSince(input.hqRoot, input.company, person, record.startedAt))
590
+ return null;
591
+ // Judge the record as the failed run it is: a running record never wrote
592
+ // its outcome, and an extract that never ran is a failed extract.
593
+ const steps = record.steps.some((s) => s.name === "extract")
594
+ ? record.steps
595
+ : [...record.steps, { name: "extract", itemsIn: 0, itemsOut: 0, durationMs: 0, status: "failed", error: reason }];
596
+ const judged = { ...record, status: "failed", alreadyRanToday: false, steps };
597
+ const out = await raiseSignalsRunAlerts({
598
+ hqRoot: input.hqRoot,
599
+ records: [judged],
600
+ senders: { ...input.senders, resolvePerson: () => person },
601
+ now: input.now,
602
+ });
603
+ return out[input.company] ?? null;
604
+ }
605
+ catch (err) {
606
+ log(`signals alert for ${input.company} failed: ${err instanceof Error ? err.message : String(err)}`);
607
+ return null;
608
+ }
609
+ }
610
+ /** True when the shared dedupe file records a signals-run alert sent at or after `startedAt`. */
611
+ function alertedSince(hqRoot, company, person, startedAt) {
612
+ const file = signalsAlertStatePath(path.join(hqRoot, "companies", company), person.personKey);
613
+ let last;
614
+ try {
615
+ const state = JSON.parse(fs.readFileSync(file, "utf8"));
616
+ last = state.lastAlertAt?.[signalsAlertKey({ adapter: SIGNALS_RUN_ALERT_ADAPTER, connectionId: null })];
617
+ }
618
+ catch {
619
+ return false;
620
+ }
621
+ return typeof last === "string" && Date.parse(last) >= Date.parse(startedAt);
622
+ }
524
623
  //# sourceMappingURL=engine.js.map
@@ -154,24 +154,71 @@ function listInWords(parts) {
154
154
  function capitalize(text) {
155
155
  return text ? text[0].toUpperCase() + text.slice(1) : text;
156
156
  }
157
+ /** The extract step that stopped because the run reached its spend cap, if any. */
158
+ function budgetStopStep(record) {
159
+ return record.steps.find((s) => s.name === "extract" && (s.status === "partial" || s.status === "failed") && s.error === "budget-exceeded");
160
+ }
161
+ /** "$2.00", or null when the record carries no usable cap. */
162
+ function capInWords(record) {
163
+ return Number.isFinite(record.maxBudgetUsd) && record.maxBudgetUsd >= 0 ? `$${record.maxBudgetUsd.toFixed(2)}` : null;
164
+ }
165
+ /** The run's first problem, picked the way finalizeRecord picks the step behind failureReason. */
166
+ function firstProblem(record) {
167
+ const problems = record.steps.filter((s) => s.status === "failed" || s.status === "partial");
168
+ return problems.find((s) => s.status === "failed") ?? problems[0];
169
+ }
170
+ /**
171
+ * The per-run way to raise the cap. Only the flag is named: the default lives
172
+ * in core/settings/signals.yaml, which is release-owned and replaced on
173
+ * update, so a member edit there would be lost. The flag also sets the cap of
174
+ * an --incremental run.
175
+ */
176
+ function raiseCapLine(record) {
177
+ return `To raise the cap for one run, use hq signals run --company ${record.company} --max-budget-usd <amount>.`;
178
+ }
179
+ /**
180
+ * A budget stop in words: the source it stopped at (detail.budgetStoppedAt),
181
+ * that the rest waits for the next run, and how to raise the cap for a run.
182
+ */
183
+ function budgetGuidance(record, stopped) {
184
+ const raw = stopped.detail?.budgetStoppedAt;
185
+ const at = typeof raw === "string" && raw.trim() ? raw.trim() : null;
186
+ const cap = capInWords(record);
187
+ const reached = cap ? `its spend cap of ${cap}` : "its spend cap";
188
+ return [
189
+ at ? `Finding signals stopped at ${at} because the run reached ${reached}.` : `Finding signals stopped because the run reached ${reached}.`,
190
+ at ? "That source and any after it wait for the next run." : "The sources it did not reach wait for the next run.",
191
+ raiseCapLine(record),
192
+ ].join(" ");
193
+ }
157
194
  /**
158
195
  * What the member can do about a failed or partial run. The detail
159
196
  * (reconnect, signed-out) is on the failing step; the record carries only the
160
197
  * coarse v2 kind (auth, config, transient).
198
+ *
199
+ * `main` answers the run's first problem. A budget stop that is not the first
200
+ * problem is added as a short `note` after it, so neither problem goes unsaid.
161
201
  */
162
202
  function failureGuidance(record, failed, company) {
203
+ const stopped = budgetStopStep(record);
204
+ const budgetFirst = stopped !== undefined && firstProblem(record) === stopped;
205
+ const cap = capInWords(record);
206
+ const shortNote = `Finding signals also reached ${cap ? `its ${cap} spend cap` : "its spend cap"}, so some sources wait for the next run. ${raiseCapLine(record)}`;
163
207
  const stepKind = failed?.errorKind ?? record.steps.find((s) => s.status === "failed" || s.status === "partial")?.errorKind;
164
- if (stepKind === "reconnect")
165
- return `A connection for ${company} needs reconnecting.`;
166
- if (stepKind === "signed-out")
167
- return "You are signed out of HQ. Sign in again with hq login.";
168
- if (record.errorKind === "auth")
169
- return `A connection for ${company} needs signing in again.`;
170
- if (record.errorKind === "config")
171
- return `Something in the signals setup for ${company} needs fixing first.`;
172
- if (record.errorKind === "transient")
173
- return "This looks temporary.";
174
- return failed ? `${STEP_DOING[failed.name]} for ${company} failed.` : `Signals for ${company} failed.`;
208
+ // Sign-in and setup problems come first; a budget stop is then added after them.
209
+ const urgent = stepKind === "reconnect" ? `A connection for ${company} needs reconnecting.`
210
+ : stepKind === "signed-out" ? "You are signed out of HQ. Sign in again with hq login."
211
+ : record.errorKind === "auth" ? `A connection for ${company} needs signing in again.`
212
+ : record.errorKind === "config" ? `Something in the signals setup for ${company} needs fixing first.`
213
+ : null;
214
+ if (urgent)
215
+ return { main: urgent, note: stopped ? (budgetFirst ? budgetGuidance(record, stopped) : shortNote) : null };
216
+ if (budgetFirst)
217
+ return { main: budgetGuidance(record, stopped), note: null };
218
+ const main = record.errorKind === "transient" ? "This looks temporary."
219
+ : failed ? `${STEP_DOING[failed.name]} for ${company} failed.`
220
+ : `Signals for ${company} failed.`;
221
+ return { main, note: stopped ? shortNote : null };
175
222
  }
176
223
  /** First sentence of an error, trimmed to one plain line. */
177
224
  function oneSentence(text) {
@@ -242,7 +289,8 @@ export function formatRunReply(record, summary, opts) {
242
289
  ? "This was the automatic retry, so I do not try again before the next scheduled run."
243
290
  : "I do not retry this on my own.";
244
291
  const guidance = failureGuidance(record, failedStep, company);
245
- const body = [retry && record.errorKind === "transient" ? `${guidance} Nothing for you to do.` : guidance, brief, retryLine].join(" ");
292
+ const main = retry && record.errorKind === "transient" && !guidance.note ? `${guidance.main} Nothing for you to do.` : guidance.main;
293
+ const body = [main, ...(guidance.note ? [guidance.note] : []), brief, retryLine].join(" ");
246
294
  blocks.push({ kind: "callout", tone: "danger", title, body });
247
295
  const idx = failedStep ? record.steps.indexOf(failedStep) : record.steps.length;
248
296
  const done = record.steps.slice(0, idx).filter((s) => s.status === "ok" || s.status === "partial");
@@ -298,12 +346,19 @@ export function formatRunReply(record, summary, opts) {
298
346
  ], "late-start");
299
347
  }
300
348
  if (record.status === "partial") {
301
- const title = record.failureReason
302
- ? oneSentence(record.failureReason)
303
- : partialReason
304
- ? partialReasonInWords(partialReason)
305
- : null;
306
- const body = `${failureGuidance(record, failedStep, company)} Your brief builds with what came in. Say "Try now" to run signals again.`;
349
+ // The budget title only when the budget stop is the run's first problem
350
+ // (the step finalizeRecord builds failureReason from).
351
+ const first = firstProblem(record);
352
+ const budgetCap = first && first === budgetStopStep(record) ? capInWords(record) : null;
353
+ const title = budgetCap
354
+ ? `Finding signals reached the ${budgetCap} spend cap.`
355
+ : record.failureReason
356
+ ? oneSentence(record.failureReason)
357
+ : partialReason
358
+ ? partialReasonInWords(partialReason)
359
+ : null;
360
+ const guidance = failureGuidance(record, failedStep, company);
361
+ const body = [guidance.main, ...(guidance.note ? [guidance.note] : []), 'Your brief builds with what came in. Say "Try now" to run signals again.'].join(" ");
307
362
  return build(`${job} finished with problems at ${finished}.`, [
308
363
  { kind: "badge", label: "Finished with problems", tone: "warning" },
309
364
  ...(record.catchUp ? [catchUpBadge] : []),
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import * as fs from "node:fs";
14
14
  import * as path from "node:path";
15
+ import { TEMPORARY_ADAPTER_ERROR_CODES } from "../../hot-channels/contract.js";
15
16
  import { FLAG_OFF_REASON, gateAdapters, readSignalsAdaptersCatalog } from "../adapters-catalog.js";
16
17
  import { assertNoEscapingLinks } from "../write-guard.js";
17
18
  export const defaultHotChannelSync = async (input) => {
@@ -67,9 +68,13 @@ export function mapSyncReport(report) {
67
68
  }
68
69
  else if (failed > 0) {
69
70
  result.status = ok > 0 ? "partial" : "failed";
70
- const first = report.outcomes.find((o) => o.status === "failed");
71
+ const failures = report.outcomes.filter((o) => o.status === "failed");
72
+ const first = failures[0];
71
73
  result.error = first?.message ?? "adapter failed";
72
- result.errorKind = reconnect ? "reconnect" : "other";
74
+ // A rate limit clears on its own (US-009 AC9): when every failure is one,
75
+ // the step is transient, so the run keeps its retry and says so.
76
+ const temporary = failures.every((o) => o.errorCode !== undefined && TEMPORARY_ADAPTER_ERROR_CODES.has(o.errorCode));
77
+ result.errorKind = reconnect ? "reconnect" : temporary ? "transient" : "other";
73
78
  }
74
79
  else if (reconnect) {
75
80
  result.errorKind = "reconnect";
@@ -126,6 +126,19 @@ export declare function parseTurnOutput(stdout: string): {
126
126
  turns: number;
127
127
  costUsd: number;
128
128
  };
129
+ /**
130
+ * How many of this item's new signal candidates in this company carry no
131
+ * citation marker. Counting only: nothing is changed or removed, and entity
132
+ * candidates are not looked at. Run before validateNewCandidates, which may
133
+ * rewrite or remove the files. A candidate counted here can still be rejected
134
+ * by validation for another reason, so the count can slightly overstate the
135
+ * uncited signals that are kept.
136
+ */
137
+ export declare function countUncitedSignals(files: string[], scope: {
138
+ hqRoot: string;
139
+ company: string;
140
+ sourceRef: string;
141
+ }): number;
129
142
  /**
130
143
  * Clean up the new candidate files a turn produced.
131
144
  *
@@ -183,6 +183,20 @@ export function claudeAllowedTools(channelDir, wrapperPath) {
183
183
  // A rule path that starts with `//` is absolute.
184
184
  return [`Read(/${channelDir}/**)`, `Bash(bash ${wrapperPath} *)`];
185
185
  }
186
+ /**
187
+ * A citation marker in a signal body. The extract prompt asks for
188
+ * (cite: "a quote") or (cite: 00:12:31). Near variants are also taken as a
189
+ * citation: square or full-width brackets, "cited" or "citation", a full-width
190
+ * colon. The check proves a marker with something after it exists. It does not
191
+ * check that the quote is in the source, and a marker in another language or
192
+ * a bare quote is counted as uncited.
193
+ *
194
+ * Uncited signal candidates are counted, not rejected: no real run has shown
195
+ * yet how often each runtime writes the marker.
196
+ */
197
+ const SIGNAL_CITATION_RE = /[([(]\s*cit(?:e|ed|ation)\s*[::]\s*[^\s)\])]/i;
198
+ /** The result subtype claude prints when --max-budget-usd ends the turn. Only claude is given a budget. */
199
+ const CLAUDE_BUDGET_STOP_SUBTYPE = "error_max_budget_usd";
186
200
  /** The Executive bot's runtime (lib/bot/executive.ts), or null when there is no personal bot. */
187
201
  export function defaultResolveBotRuntime(root = botsRoot()) {
188
202
  const main = resolveExecutiveBot({ root })?.config ?? null;
@@ -506,6 +520,34 @@ function companyHasSourceItem(hqRoot, company, sourceRef) {
506
520
  return false;
507
521
  return fs.existsSync(path.join(hqRoot, "companies", company, "sources", channel, name));
508
522
  }
523
+ /**
524
+ * How many of this item's new signal candidates in this company carry no
525
+ * citation marker. Counting only: nothing is changed or removed, and entity
526
+ * candidates are not looked at. Run before validateNewCandidates, which may
527
+ * rewrite or remove the files. A candidate counted here can still be rejected
528
+ * by validation for another reason, so the count can slightly overstate the
529
+ * uncited signals that are kept.
530
+ */
531
+ export function countUncitedSignals(files, scope) {
532
+ let uncited = 0;
533
+ for (const f of files) {
534
+ let text;
535
+ try {
536
+ text = fs.readFileSync(f, "utf8");
537
+ }
538
+ catch {
539
+ continue;
540
+ }
541
+ const fm = frontmatter(text);
542
+ if (fm?.kind !== "signal" || fm.source_ref !== scope.sourceRef)
543
+ continue;
544
+ if (!realRelPath(scope.hqRoot, f)?.startsWith(`companies/${scope.company}/signals/_candidates/`))
545
+ continue;
546
+ if (!SIGNAL_CITATION_RE.test(splitFrontmatter(text).body))
547
+ uncited += 1;
548
+ }
549
+ return uncited;
550
+ }
509
551
  /**
510
552
  * Clean up the new candidate files a turn produced.
511
553
  *
@@ -1091,6 +1133,12 @@ function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
1091
1133
  return { ok: false, error: `${runtime} timed out after ${opts.turnTimeoutMs}ms`, errorKind: "transient", turns: parsed.turns, costUsd: parsed.costUsd };
1092
1134
  return { ok: false, error: `${runtime} could not start: ${res.error.message}`.slice(0, 300), errorKind: "other", turns: 0, costUsd: 0 };
1093
1135
  }
1136
+ // The runtime stopped the turn at its own budget cap (claude: result subtype
1137
+ // error_max_budget_usd, with a non-zero exit). That is the run's budget stop,
1138
+ // not a failed item.
1139
+ if (runtime === "claude" && parsed.result?.subtype === CLAUDE_BUDGET_STOP_SUBTYPE) {
1140
+ return { ok: false, error: "budget-exceeded", budgetExceeded: true, turns: parsed.turns, costUsd: parsed.costUsd };
1141
+ }
1094
1142
  if (res.status !== 0) {
1095
1143
  const c = classifyFailure(all, `${runtime} exited ${String(res.status)}: ${res.stderr.trim().slice(0, 200)}`);
1096
1144
  return { ok: false, ...c, turns: parsed.turns, costUsd: parsed.costUsd };
@@ -1131,11 +1179,36 @@ export async function extractPartialDocument(ctx, doc, prior) {
1131
1179
  finally {
1132
1180
  fs.rmSync(cwd, { recursive: true, force: true });
1133
1181
  }
1182
+ // One parse of the JSON envelope, used for the budget-stop check and the success path.
1183
+ const envelope = (() => {
1184
+ if (run.error)
1185
+ return null;
1186
+ try {
1187
+ const parsed = JSON.parse(run.stdout);
1188
+ return parsed && typeof parsed === "object" ? parsed : null;
1189
+ }
1190
+ catch {
1191
+ // Not a JSON envelope; handled below.
1192
+ return null;
1193
+ }
1194
+ })();
1195
+ // claude stopped the turn at --max-budget-usd. That is a budget stop, not a
1196
+ // login problem; the caller leaves the cursor where it was.
1197
+ if (envelope?.subtype === CLAUDE_BUDGET_STOP_SUBTYPE) {
1198
+ return {
1199
+ status: "partial",
1200
+ error: "budget-exceeded",
1201
+ itemsIn: 1,
1202
+ itemsOut: 0,
1203
+ modelTurns: typeof envelope.num_turns === "number" ? envelope.num_turns : 1,
1204
+ estimatedSpendUsd: typeof envelope.total_cost_usd === "number" ? envelope.total_cost_usd : 0,
1205
+ };
1206
+ }
1134
1207
  if (run.error || run.status !== 0)
1135
1208
  throw new Error("Signal extraction failed; the cursor was not advanced. Check the coding-tool login and retry.");
1209
+ // parseClaudeSignals throws its own error for output that is not a usable envelope.
1136
1210
  const signals = parseClaudeSignals(run.stdout);
1137
- const envelope = JSON.parse(run.stdout);
1138
- return { status: "ok", itemsIn: 1, itemsOut: signals.length, modelTurns: envelope.num_turns ?? 1, estimatedSpendUsd: envelope.total_cost_usd ?? 0, detail: { signals } };
1211
+ return { status: "ok", itemsIn: 1, itemsOut: signals.length, modelTurns: envelope?.num_turns ?? 1, estimatedSpendUsd: envelope?.total_cost_usd ?? 0, detail: { signals } };
1139
1212
  }
1140
1213
  export function createExtractStep(options = {}) {
1141
1214
  return {
@@ -1198,6 +1271,15 @@ export function createExtractStep(options = {}) {
1198
1271
  let skipped = 0;
1199
1272
  let processedAny = false;
1200
1273
  let budgetStop = false;
1274
+ /**
1275
+ * The first source a budget stop left unfinished, which the next run takes first: the source whose
1276
+ * turn the runtime stopped at its cap, or, when the run stops between sources, the next source it
1277
+ * did not start. Named in the record so a source that never fits is findable.
1278
+ */
1279
+ let budgetStoppedAt;
1280
+ /** Signal candidates with no citation marker, and the sources they came from. Counted, not rejected. */
1281
+ let uncitedCandidates = 0;
1282
+ const uncitedSources = [];
1201
1283
  let errorKind;
1202
1284
  const failures = unrunRedo.map((file) => ({
1203
1285
  file,
@@ -1287,6 +1369,8 @@ export function createExtractStep(options = {}) {
1287
1369
  }
1288
1370
  const remaining = ctx.maxBudgetUsd - spent;
1289
1371
  if (spent > 0 && (spent >= ctx.maxBudgetUsd || remaining < lastCost)) {
1372
+ // This source is not started and not marked done; the next run takes it first.
1373
+ budgetStoppedAt = item.file;
1290
1374
  budgetStop = true;
1291
1375
  break outer;
1292
1376
  }
@@ -1333,17 +1417,37 @@ export function createExtractStep(options = {}) {
1333
1417
  spent += turn.costUsd;
1334
1418
  lastCost = turn.costUsd;
1335
1419
  const created = [...allCandidateFiles(ctx.hqRoot)].filter((f) => !before.has(f));
1336
- if (!turn.ok && priorSignals.length) {
1420
+ if (!turn.ok && (priorSignals.length || turn.budgetExceeded)) {
1337
1421
  // Failed model turns must not leave structured duplicates for garden.
1422
+ // A budget-stopped source runs again next time and would write its
1423
+ // candidates a second time, so the stopped turn's are removed too:
1424
+ // its signal candidates and its entity candidates. A failed turn
1425
+ // with prior signals keeps the scope it had, signal candidates only.
1426
+ const stores = turn.budgetExceeded ? ["signals", "ontology"] : ["signals"];
1338
1427
  for (const file of created) {
1339
1428
  const rel = realRelPath(ctx.hqRoot, file);
1340
- if (rel?.startsWith(`companies/${ctx.company}/signals/_candidates/`) && frontmatter(fs.readFileSync(file, "utf8"))?.source_ref === sourceRef) {
1341
- guardedRemove(ctx.hqRoot, rel, { company: ctx.company });
1429
+ if (!rel || !stores.some((store) => rel.startsWith(`companies/${ctx.company}/${store}/_candidates/`)))
1430
+ continue;
1431
+ let text;
1432
+ try {
1433
+ text = fs.readFileSync(file, "utf8");
1342
1434
  }
1435
+ catch {
1436
+ // Gone already (a concurrent garden moved it), or unreadable; nothing to remove.
1437
+ continue;
1438
+ }
1439
+ if (frontmatter(text)?.source_ref === sourceRef)
1440
+ guardedRemove(ctx.hqRoot, rel, { company: ctx.company });
1343
1441
  }
1344
1442
  }
1443
+ // Only a finished turn's candidates are counted; a failed turn's are not the source's result.
1444
+ const uncitedHere = turn.ok ? countUncitedSignals(created, { hqRoot: ctx.hqRoot, company: ctx.company, sourceRef }) : 0;
1345
1445
  const v = validateNewCandidates(created, item.audience_key, { hqRoot: ctx.hqRoot, company: ctx.company, sourceRef }, turn.ok ? priorSignals : [], ctx.now());
1346
1446
  rejected += v.rejected;
1447
+ if (uncitedHere > 0) {
1448
+ uncitedCandidates += uncitedHere;
1449
+ uncitedSources.push(item.file);
1450
+ }
1347
1451
  updated += v.updated ?? 0;
1348
1452
  skipped += v.skipped ?? 0;
1349
1453
  if (priorSignals.length && v.rejected > 0 && turn.ok) {
@@ -1355,8 +1459,20 @@ export function createExtractStep(options = {}) {
1355
1459
  failures.push({ file: item.file, error: `candidate written outside ${ctx.company} (deleted): ${v.foreign.join(", ")}`.slice(0, 300) });
1356
1460
  if (!errorKind)
1357
1461
  errorKind = "other";
1462
+ if (turn.budgetExceeded) {
1463
+ // The breach is recorded above; the runtime's budget stop still ends the run.
1464
+ budgetStoppedAt = item.file;
1465
+ budgetStop = true;
1466
+ break outer;
1467
+ }
1358
1468
  continue;
1359
1469
  }
1470
+ if (!turn.ok && turn.budgetExceeded) {
1471
+ // The item is not marked done, so the next run takes it again.
1472
+ budgetStoppedAt = item.file;
1473
+ budgetStop = true;
1474
+ break outer;
1475
+ }
1360
1476
  if (!turn.ok) {
1361
1477
  failures.push({ file: item.file, error: turn.error ?? "turn failed" });
1362
1478
  if (turn.errorKind === "signed-out" || !errorKind)
@@ -1383,7 +1499,7 @@ export function createExtractStep(options = {}) {
1383
1499
  ...(failures.length ? { failures } : {}),
1384
1500
  ...(skippedItems.length ? { skippedItems } : {}),
1385
1501
  ...(rejected ? { rejectedCandidates: rejected } : {}),
1386
- detail: { new: itemsOut, updated, skipped, runtime, ...(choice.fallback ? { fallback: choice.fallback } : {}) },
1502
+ detail: { new: itemsOut, updated, skipped, runtime, ...(choice.fallback ? { fallback: choice.fallback } : {}), ...(budgetStoppedAt ? { budgetStoppedAt } : {}), ...(uncitedCandidates ? { uncitedCandidates, uncitedSources } : {}) },
1387
1503
  };
1388
1504
  if (budgetStop) {
1389
1505
  result.status = "partial";
package/dist/main.js CHANGED
@@ -9,7 +9,7 @@ import "./node-network-compat.js";
9
9
  import fs from "node:fs";
10
10
  import path from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
- import { Command } from "commander";
12
+ import { Command, Help, Option } from "commander";
13
13
  import { closeSentryTransport, finishSentrySession, initSentry, Sentry } from "./sentry.js";
14
14
  import { addCommandBreadcrumb } from "./utils/command-breadcrumb.js";
15
15
  import { environmentalFsErrorMessage, filesystemErrorCaptureContext, filesystemErrorMessage, } from "./utils/environmental-error.js";
@@ -29,7 +29,8 @@ import { qmdExitCaptureContext } from "./lib/search-index/qmd-exit-diagnostics.j
29
29
  import { hqStateWriteErrorMessage } from "./utils/hq-state-write-error.js";
30
30
  import { checkpointStampWriteCaptureContext, checkpointStampWriteMessage, } from "./utils/checkpoint-stamp-write-error.js";
31
31
  import { incompleteInstallMessage, incompleteInstallCaptureContext, } from "./utils/incomplete-install-error.js";
32
- import { isExpectedUserError } from "./utils/expected-cli-error.js";
32
+ import { isExpectedUserError, markExpectedUserError } from "./utils/expected-cli-error.js";
33
+ import { admitCommandRun, commandPathOf, takeStillUseFlag, STILL_USE_FLAG, STILL_USE_FLAG_DESCRIPTION, } from "./utils/command-usage.js";
33
34
  import { isVarlockEnvError } from "./run/env-graph-guard.js";
34
35
  import { isEpipe } from "./utils/epipe.js";
35
36
  import { installStreamErrorBoundary } from "./stream-error-boundary.js";
@@ -48,7 +49,7 @@ import { autoUpdateAndReexec } from "./utils/self-update.js";
48
49
  import { CLI_VERSION } from "./cli-version.js";
49
50
  import { findLazyCommand, registerCommandCatalog } from "./lazy-commands.js";
50
51
  import { argvWithoutHelpOnUnknownCommand } from "./unknown-command.js";
51
- import { emitCliFirstSyncNextStepOutcome, emitCliFeatureUsed, emitCliLimitNoticeEngagement, emitCliLimitNoticeExposure, emitCliInviteNudgeEvent, emitCliSessionStarted, emitPlanLimitInviteTeammateExposure, isCliLimitResourceKind, queueCliLimitNoticeEngagement, queueCliLimitNoticeExposure, takeFirstSyncStepOutcomes, takeCliFeatureUsages, takeCliLimitNoticeEngagements, takeCliLimitNoticeExposures, takeCliInviteNudgeEvents, takePlanLimitInviteTeammateExposures, maybeShowFirstSyncNextStep, } from "./utils/cli-telemetry.js";
52
+ import { emitCliFirstSyncNextStepOutcome, emitCliFeatureUsed, emitCliLimitNoticeEngagement, emitCliLimitNoticeExposure, emitCliInviteNudgeEvent, emitCliSessionStarted, emitPlanLimitInviteTeammateExposure, isCliLimitResourceKind, queueCliLimitNoticeEngagement, queueCliLimitNoticeExposure, takeFirstSyncStepOutcomes, takeCliFeatureUsages, takeCliLimitNoticeEngagements, takeCliLimitNoticeExposures, takeCliInviteNudgeEvents, takePlanLimitInviteTeammateExposures, maybeShowFirstSyncNextStep, maybeDiscloseLocalCommandUsage, } from "./utils/cli-telemetry.js";
52
53
  import { reportCliClientHealthInvocation } from "./utils/client-health.js";
53
54
  import { settleWithin } from "./utils/settle-with-timeout.js";
54
55
  import { isVersionRequest } from "./version-request.js";
@@ -138,6 +139,42 @@ program
138
139
  .description("HQ management CLI — modules, packages, and cloud sync")
139
140
  .version(CLI_VERSION)
140
141
  .option("--verbose", "Show verbose diagnostics, including SDK runtime warnings");
142
+ // --i-still-use-this is listed in the root help but is not a Commander option.
143
+ // Commander reads a root option anywhere on the command line, so it would take
144
+ // the flag out of a child command's arguments (`hq run tool
145
+ // --i-still-use-this`). takeStillUseFlag reads it instead, before the parse,
146
+ // and only where it is hq's.
147
+ const stillUseHelpOption = new Option(STILL_USE_FLAG, STILL_USE_FLAG_DESCRIPTION);
148
+ program.configureHelp({
149
+ visibleOptions(command) {
150
+ const options = Help.prototype.visibleOptions.call(this, command);
151
+ if (command !== program)
152
+ return options;
153
+ const helpAt = options.findIndex((option) => option.long === "--help");
154
+ return helpAt === -1
155
+ ? [...options, stillUseHelpOption]
156
+ : [...options.slice(0, helpAt), stillUseHelpOption, ...options.slice(helpAt)];
157
+ },
158
+ });
159
+ /** Whether this run carries --i-still-use-this where hq reads it. Set just before the parse. */
160
+ let stillUseRun = false;
161
+ // Registered before the hook below, so a retiring command would be refused
162
+ // before any network work. Counts the run in the local usage file (one short
163
+ // append, synchronous and swallowed on error) and applies the retiring gate,
164
+ // which is switched off (RETIRING_GATE_ENABLED in utils/command-usage.ts).
165
+ program.hook("preAction", (_program, actionCommand) => {
166
+ let refusal = null;
167
+ try {
168
+ refusal = admitCommandRun({ ...commandPathOf(actionCommand), stillUse: stillUseRun });
169
+ if (refusal === null)
170
+ maybeDiscloseLocalCommandUsage();
171
+ }
172
+ catch {
173
+ // The count and its notice are best effort: they never fail a command.
174
+ }
175
+ if (refusal !== null)
176
+ throw markExpectedUserError(new Error(refusal));
177
+ });
141
178
  program.hook("preAction", async () => {
142
179
  // A host that pinned HQ_AGENT_DIR has declared that it IS that agent, so
143
180
  // every command — `hq dm`, `hq secrets`, not only `hq agent …` — must
@@ -308,6 +345,12 @@ export async function runCli() {
308
345
  return;
309
346
  }
310
347
  await releasePackageUseLeaseAfterCommandLoad(process.argv);
348
+ // Read --i-still-use-this now that the selected command is registered, and
349
+ // take it out of process.argv: Commander and a command that forwards its
350
+ // raw arguments must not see it. A flag among the command's own arguments
351
+ // stays. This runs after the update and install-recovery re-runs, which
352
+ // need the flag kept.
353
+ stillUseRun = takeStillUseFlag(process.argv, program);
311
354
  await program.parseAsync(argvWithoutHelpOnUnknownCommand(process.argv));
312
355
  commandParsed = true;
313
356
  if (process.exitCode === undefined || process.exitCode === 0) {