@indigoai-us/hq-cli 5.345.215 → 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 (135) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/README.md +45 -0
  3. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  4. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  5. package/dist/command-catalog.generated.d.ts +59 -4
  6. package/dist/command-catalog.generated.js +74 -4
  7. package/dist/command-help.js +3 -1
  8. package/dist/command-registration-plan.d.ts +6 -0
  9. package/dist/command-registration-plan.js +1 -0
  10. package/dist/commands/auth.d.ts +1 -1
  11. package/dist/commands/auth.js +11 -52
  12. package/dist/commands/bot.js +11 -4
  13. package/dist/commands/cloud-demote.d.ts +19 -4
  14. package/dist/commands/cloud-demote.js +85 -12
  15. package/dist/commands/cloud-provision.d.ts +5 -1
  16. package/dist/commands/cloud-provision.js +6 -2
  17. package/dist/commands/cloud.d.ts +36 -0
  18. package/dist/commands/cloud.js +109 -26
  19. package/dist/commands/core.js +1 -0
  20. package/dist/commands/daemon.js +4 -1
  21. package/dist/commands/dm.js +7 -0
  22. package/dist/commands/doctor-usage.d.ts +8 -0
  23. package/dist/commands/doctor-usage.js +20 -0
  24. package/dist/commands/doctor.js +7 -1
  25. package/dist/commands/env.d.ts +18 -0
  26. package/dist/commands/env.js +82 -0
  27. package/dist/commands/install-global.js +2 -2
  28. package/dist/commands/lanes.js +100 -24
  29. package/dist/commands/logout.d.ts +7 -0
  30. package/dist/commands/logout.js +41 -34
  31. package/dist/commands/sources.d.ts +8 -2
  32. package/dist/commands/sources.js +65 -9
  33. package/dist/commands/whoami.js +26 -1
  34. package/dist/data/command-states.json +15 -0
  35. package/dist/index.js +52 -4
  36. package/dist/lazy-commands.js +2 -1
  37. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  38. package/dist/lib/anywhere-person-setting.js +6 -3
  39. package/dist/lib/billing/usage-card.d.ts +25 -4
  40. package/dist/lib/billing/usage-card.js +76 -9
  41. package/dist/lib/billing/usage-cost.d.ts +3 -3
  42. package/dist/lib/billing/usage-cost.js +35 -13
  43. package/dist/lib/billing/usage-only.js +4 -2
  44. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  45. package/dist/lib/billing/usage-rate-card.js +3 -0
  46. package/dist/lib/bot/fleet-cron.js +93 -6
  47. package/dist/lib/bot/inflight.d.ts +9 -0
  48. package/dist/lib/bot/inflight.js +10 -0
  49. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  50. package/dist/lib/bot/runtime/grok-acp.d.ts +1 -0
  51. package/dist/lib/bot/runtime/grok-acp.js +26 -11
  52. package/dist/lib/bot/runtime/grok.js +1 -1
  53. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  54. package/dist/lib/daemon/flag-monitor.js +17 -6
  55. package/dist/lib/daemon/flag.d.ts +65 -1
  56. package/dist/lib/daemon/flag.js +190 -40
  57. package/dist/lib/daemon/ops/policy.js +62 -5
  58. package/dist/lib/daemon/paths.d.ts +72 -2
  59. package/dist/lib/daemon/paths.js +154 -3
  60. package/dist/lib/daemon/run.js +25 -20
  61. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  62. package/dist/lib/daemon/selfcheck.js +40 -1
  63. package/dist/lib/daemon/server.d.ts +3 -1
  64. package/dist/lib/daemon/server.js +7 -22
  65. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  66. package/dist/lib/daemon/state-file-switch.js +88 -0
  67. package/dist/lib/daemon/state-file.d.ts +198 -0
  68. package/dist/lib/daemon/state-file.js +419 -0
  69. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  70. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  71. package/dist/lib/doctor/checks/host-core.d.ts +50 -0
  72. package/dist/lib/doctor/checks/host-core.js +269 -0
  73. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  74. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  75. package/dist/lib/doctor/registry.js +4 -0
  76. package/dist/lib/environment/profile.d.ts +239 -0
  77. package/dist/lib/environment/profile.js +251 -0
  78. package/dist/lib/hook-engine/reconcile.js +39 -13
  79. package/dist/lib/hook-engine/registration.d.ts +9 -0
  80. package/dist/lib/hook-engine/registration.js +19 -0
  81. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  82. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  83. package/dist/lib/hot-channels/alert.d.ts +2 -0
  84. package/dist/lib/hot-channels/alert.js +8 -1
  85. package/dist/lib/hot-channels/contract.d.ts +12 -0
  86. package/dist/lib/hot-channels/contract.js +7 -0
  87. package/dist/lib/hot-channels/loop.js +1 -0
  88. package/dist/lib/hot-channels/run.d.ts +6 -0
  89. package/dist/lib/hot-channels/run.js +4 -0
  90. package/dist/lib/hot-channels/signals-pass.d.ts +64 -1
  91. package/dist/lib/hot-channels/signals-pass.js +21 -49
  92. package/dist/lib/install/claude-targets.d.ts +12 -1
  93. package/dist/lib/install/claude-targets.js +57 -5
  94. package/dist/lib/install/codex-targets.d.ts +2 -2
  95. package/dist/lib/install/codex-targets.js +36 -6
  96. package/dist/lib/install/hook-target.d.ts +3 -0
  97. package/dist/lib/install/hook-target.js +11 -0
  98. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  99. package/dist/lib/lanes/canonical-host.js +65 -0
  100. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  101. package/dist/lib/lanes/host-capacity.js +29 -3
  102. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  103. package/dist/lib/mesh/live/daemon/run.js +5 -2
  104. package/dist/lib/mesh/live/flush.d.ts +5 -1
  105. package/dist/lib/mesh/live/flush.js +12 -6
  106. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  107. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  108. package/dist/lib/mesh/live/spool.d.ts +7 -0
  109. package/dist/lib/mesh/live/spool.js +25 -0
  110. package/dist/lib/person-setting-cache.d.ts +38 -0
  111. package/dist/lib/person-setting-cache.js +98 -0
  112. package/dist/lib/safe-store.d.ts +245 -0
  113. package/dist/lib/safe-store.js +777 -0
  114. package/dist/lib/signals/engine.d.ts +29 -2
  115. package/dist/lib/signals/engine.js +103 -4
  116. package/dist/lib/signals/reply.js +73 -18
  117. package/dist/lib/signals/steps/adapters.js +7 -2
  118. package/dist/lib/signals/steps/extract.d.ts +13 -0
  119. package/dist/lib/signals/steps/extract.js +84 -4
  120. package/dist/main.js +46 -3
  121. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  122. package/dist/utils/auth-expiry.d.ts +8 -0
  123. package/dist/utils/auth-expiry.js +53 -0
  124. package/dist/utils/cli-telemetry.d.ts +21 -0
  125. package/dist/utils/cli-telemetry.js +34 -0
  126. package/dist/utils/command-usage.d.ts +275 -0
  127. package/dist/utils/command-usage.js +797 -0
  128. package/dist/utils/hook-trust.d.ts +7 -0
  129. package/dist/utils/hook-trust.js +31 -4
  130. package/dist/utils/host-registration.d.ts +126 -0
  131. package/dist/utils/host-registration.js +378 -0
  132. package/dist/utils/resident-package-preload.js +2 -0
  133. package/package.json +10 -8
  134. package/scripts/bench-core.mjs +1096 -0
  135. package/scripts/check-function-manifest.mjs +702 -0
@@ -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,18 @@ 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;
186
198
  /** The result subtype claude prints when --max-budget-usd ends the turn. Only claude is given a budget. */
187
199
  const CLAUDE_BUDGET_STOP_SUBTYPE = "error_max_budget_usd";
188
200
  /** The Executive bot's runtime (lib/bot/executive.ts), or null when there is no personal bot. */
@@ -508,6 +520,34 @@ function companyHasSourceItem(hqRoot, company, sourceRef) {
508
520
  return false;
509
521
  return fs.existsSync(path.join(hqRoot, "companies", company, "sources", channel, name));
510
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
+ }
511
551
  /**
512
552
  * Clean up the new candidate files a turn produced.
513
553
  *
@@ -1139,11 +1179,36 @@ export async function extractPartialDocument(ctx, doc, prior) {
1139
1179
  finally {
1140
1180
  fs.rmSync(cwd, { recursive: true, force: true });
1141
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
+ }
1142
1207
  if (run.error || run.status !== 0)
1143
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.
1144
1210
  const signals = parseClaudeSignals(run.stdout);
1145
- const envelope = JSON.parse(run.stdout);
1146
- 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 } };
1147
1212
  }
1148
1213
  export function createExtractStep(options = {}) {
1149
1214
  return {
@@ -1206,8 +1271,15 @@ export function createExtractStep(options = {}) {
1206
1271
  let skipped = 0;
1207
1272
  let processedAny = false;
1208
1273
  let budgetStop = false;
1209
- /** The source a runtime budget stop cut short, named in the record so a source that never fits is findable. */
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
+ */
1210
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 = [];
1211
1283
  let errorKind;
1212
1284
  const failures = unrunRedo.map((file) => ({
1213
1285
  file,
@@ -1297,6 +1369,8 @@ export function createExtractStep(options = {}) {
1297
1369
  }
1298
1370
  const remaining = ctx.maxBudgetUsd - spent;
1299
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;
1300
1374
  budgetStop = true;
1301
1375
  break outer;
1302
1376
  }
@@ -1366,8 +1440,14 @@ export function createExtractStep(options = {}) {
1366
1440
  guardedRemove(ctx.hqRoot, rel, { company: ctx.company });
1367
1441
  }
1368
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;
1369
1445
  const v = validateNewCandidates(created, item.audience_key, { hqRoot: ctx.hqRoot, company: ctx.company, sourceRef }, turn.ok ? priorSignals : [], ctx.now());
1370
1446
  rejected += v.rejected;
1447
+ if (uncitedHere > 0) {
1448
+ uncitedCandidates += uncitedHere;
1449
+ uncitedSources.push(item.file);
1450
+ }
1371
1451
  updated += v.updated ?? 0;
1372
1452
  skipped += v.skipped ?? 0;
1373
1453
  if (priorSignals.length && v.rejected > 0 && turn.ok) {
@@ -1419,7 +1499,7 @@ export function createExtractStep(options = {}) {
1419
1499
  ...(failures.length ? { failures } : {}),
1420
1500
  ...(skippedItems.length ? { skippedItems } : {}),
1421
1501
  ...(rejected ? { rejectedCandidates: rejected } : {}),
1422
- detail: { new: itemsOut, updated, skipped, runtime, ...(choice.fallback ? { fallback: choice.fallback } : {}), ...(budgetStoppedAt ? { budgetStoppedAt } : {}) },
1502
+ detail: { new: itemsOut, updated, skipped, runtime, ...(choice.fallback ? { fallback: choice.fallback } : {}), ...(budgetStoppedAt ? { budgetStoppedAt } : {}), ...(uncitedCandidates ? { uncitedCandidates, uncitedSources } : {}) },
1423
1503
  };
1424
1504
  if (budgetStop) {
1425
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) {