@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
@@ -27,11 +27,18 @@
27
27
  * `slack_participants`.
28
28
  *
29
29
  * Slack pauses event delivery to an app that exceeds its rate limit and sends
30
- * `app_rate_limited`. A marker newer than the cursor (`_app_rate_limited.json`
31
- * or a document with `type: app_rate_limited` in `sources/slack/`, without a
32
- * `resolved_at`) fails the adapter with `SlackAppRateLimitedError`, whose
33
- * message lands in the run ledger's `error`. The cursor does not move.
34
- * Writing that marker from the webhook is an hq-pro-agents follow-up.
30
+ * `app_rate_limited`. hq-pro-agents' Slack receiver writes that as
31
+ * `_app_rate_limited.json` in `sources/slack/`: `at` is the first pause of an
32
+ * unresolved run, `last_at` the newest, and `resolved_at` is set once a later
33
+ * event for the same team arrives. A landed document with
34
+ * `type: app_rate_limited` counts the same way. A marker fails the adapter
35
+ * with `SlackAppRateLimitedError`, whose message lands in the run ledger's
36
+ * `error`, while all of these hold: it has no `resolved_at`, its newest pause
37
+ * (newest readable of `last_at`, `at`, `ingested_at`) is under an hour old,
38
+ * and that newest pause is after the cursor. The cursor does not move. A
39
+ * marker time more than five minutes ahead of now is ignored on its own. The
40
+ * hour limit exists because a quiet company may never send the later event
41
+ * that sets `resolved_at`.
35
42
  */
36
43
  import { type PollHotChannelAdapter } from "../contract.js";
37
44
  export declare const SLACK_ADAPTER_ID = "slack";
@@ -66,5 +73,14 @@ export interface SlackAdapterOptions {
66
73
  /** Threads newer than the cursor per page. Default 100. */
67
74
  pageSize?: number;
68
75
  }
76
+ /**
77
+ * An open marker whose newest pause is older than this is treated as resolved.
78
+ * While Slack keeps an app paused it sends `app_rate_limited` about once a
79
+ * minute and the receiver moves `last_at` forward, so an ongoing pause stays
80
+ * well inside this window. The receiver only sets `resolved_at` when a later
81
+ * event for the team arrives, so a quiet company would otherwise keep an open
82
+ * marker, and a failing Slack sync, forever.
83
+ */
84
+ export declare const SLACK_RATE_LIMIT_MARKER_MAX_AGE_MS: number;
69
85
  export declare function createSlackAdapter(options: SlackAdapterOptions): PollHotChannelAdapter;
70
86
  //# sourceMappingURL=slack.d.ts.map
@@ -27,11 +27,18 @@
27
27
  * `slack_participants`.
28
28
  *
29
29
  * Slack pauses event delivery to an app that exceeds its rate limit and sends
30
- * `app_rate_limited`. A marker newer than the cursor (`_app_rate_limited.json`
31
- * or a document with `type: app_rate_limited` in `sources/slack/`, without a
32
- * `resolved_at`) fails the adapter with `SlackAppRateLimitedError`, whose
33
- * message lands in the run ledger's `error`. The cursor does not move.
34
- * Writing that marker from the webhook is an hq-pro-agents follow-up.
30
+ * `app_rate_limited`. hq-pro-agents' Slack receiver writes that as
31
+ * `_app_rate_limited.json` in `sources/slack/`: `at` is the first pause of an
32
+ * unresolved run, `last_at` the newest, and `resolved_at` is set once a later
33
+ * event for the same team arrives. A landed document with
34
+ * `type: app_rate_limited` counts the same way. A marker fails the adapter
35
+ * with `SlackAppRateLimitedError`, whose message lands in the run ledger's
36
+ * `error`, while all of these hold: it has no `resolved_at`, its newest pause
37
+ * (newest readable of `last_at`, `at`, `ingested_at`) is under an hour old,
38
+ * and that newest pause is after the cursor. The cursor does not move. A
39
+ * marker time more than five minutes ahead of now is ignored on its own. The
40
+ * hour limit exists because a quiet company may never send the later event
41
+ * that sets `resolved_at`.
35
42
  */
36
43
  import * as fs from "node:fs/promises";
37
44
  import * as path from "node:path";
@@ -173,24 +180,46 @@ function toEvent(t) {
173
180
  function byTimeThenName(a, b) {
174
181
  return a.tsMs - b.tsMs || (a.file < b.file ? -1 : a.file > b.file ? 1 : 0);
175
182
  }
176
- /** When an unresolved `app_rate_limited` marker is set, the time it was set. */
177
- function rateLimitedAt(record) {
183
+ /**
184
+ * An open marker whose newest pause is older than this is treated as resolved.
185
+ * While Slack keeps an app paused it sends `app_rate_limited` about once a
186
+ * minute and the receiver moves `last_at` forward, so an ongoing pause stays
187
+ * well inside this window. The receiver only sets `resolved_at` when a later
188
+ * event for the team arrives, so a quiet company would otherwise keep an open
189
+ * marker, and a failing Slack sync, forever.
190
+ */
191
+ export const SLACK_RATE_LIMIT_MARKER_MAX_AGE_MS = 60 * 60 * 1000;
192
+ /** Clock skew allowed on a marker time; a time further ahead is ignored. */
193
+ const MARKER_FUTURE_SKEW_MS = 5 * 60 * 1000;
194
+ /**
195
+ * The open pause a record describes, or null when the record is not a marker,
196
+ * is resolved, has no usable time, or its newest pause is an hour or more
197
+ * before `nowMs`. A time that does not parse, or is more than a few minutes
198
+ * ahead of `nowMs`, is dropped on its own; the marker's other times still count.
199
+ */
200
+ function rateLimitPause(record, nowMs) {
178
201
  if (record.type !== SLACK_APP_RATE_LIMITED && record.error !== SLACK_APP_RATE_LIMITED)
179
- return NaN;
202
+ return null;
180
203
  if (nonEmptyString(record.resolved_at) !== undefined)
181
- return NaN;
182
- const at = parseTime(record.at);
183
- return Number.isNaN(at) ? parseTime(record.ingested_at) : at;
204
+ return null;
205
+ const usable = (t) => !Number.isNaN(t) && t <= nowMs + MARKER_FUTURE_SKEW_MS;
206
+ const times = [record.at, record.ingested_at, record.last_at].map(parseTime).filter(usable);
207
+ if (times.length === 0)
208
+ return null;
209
+ const newestMs = Math.max(...times);
210
+ if (nowMs - newestMs >= SLACK_RATE_LIMIT_MARKER_MAX_AGE_MS)
211
+ return null;
212
+ return { startedMs: times[0], newestMs };
184
213
  }
185
- async function readMarker(file) {
214
+ async function readMarker(file, nowMs) {
186
215
  try {
187
216
  const parsed = JSON.parse(await fs.readFile(file, "utf8"));
188
217
  return parsed && typeof parsed === "object" && !Array.isArray(parsed)
189
- ? rateLimitedAt(parsed)
190
- : NaN;
218
+ ? rateLimitPause(parsed, nowMs)
219
+ : null;
191
220
  }
192
221
  catch {
193
- return NaN;
222
+ return null;
194
223
  }
195
224
  }
196
225
  export function createSlackAdapter(options) {
@@ -214,7 +243,22 @@ export function createSlackAdapter(options) {
214
243
  const sinceMs = Date.parse(ctx.since);
215
244
  const cursorMs = cursor === null ? NaN : Date.parse(cursor);
216
245
  const floorMs = Number.isNaN(cursorMs) ? sinceMs : cursorMs;
217
- let pausedMs = names.includes(SLACK_RATE_LIMIT_MARKER) ? await readMarker(path.join(dir, SLACK_RATE_LIMIT_MARKER)) : NaN;
246
+ const ctxNowMs = ctx.now === undefined ? NaN : Date.parse(ctx.now);
247
+ const nowMs = Number.isNaN(ctxNowMs) ? Date.now() : ctxNowMs;
248
+ // A pause blocks when its newest pause is after the cursor: an unresolved
249
+ // run keeps its first `at`, so a later pause in it only moves `last_at`.
250
+ // The error names the first paused time after the cursor.
251
+ let pausedMs = NaN;
252
+ const notePause = (pause) => {
253
+ if (!pause || pause.newestMs <= floorMs)
254
+ return;
255
+ const at = pause.startedMs > floorMs ? pause.startedMs : pause.newestMs;
256
+ if (Number.isNaN(pausedMs) || at < pausedMs)
257
+ pausedMs = at;
258
+ };
259
+ if (names.includes(SLACK_RATE_LIMIT_MARKER)) {
260
+ notePause(await readMarker(path.join(dir, SLACK_RATE_LIMIT_MARKER), nowMs));
261
+ }
218
262
  const candidates = [];
219
263
  for (const file of names.filter((n) => n.endsWith(".md")).sort()) {
220
264
  let text;
@@ -227,10 +271,9 @@ export function createSlackAdapter(options) {
227
271
  const fm = readFrontmatter(text);
228
272
  if (!fm)
229
273
  continue;
230
- const marker = rateLimitedAt(fm);
231
- if (!Number.isNaN(marker)) {
232
- if (Number.isNaN(pausedMs) || marker > pausedMs)
233
- pausedMs = marker;
274
+ const pause = rateLimitPause(fm, nowMs);
275
+ if (pause) {
276
+ notePause(pause);
234
277
  continue;
235
278
  }
236
279
  const t = toThread(file, fm);
@@ -244,7 +287,7 @@ export function createSlackAdapter(options) {
244
287
  continue;
245
288
  candidates.push(t);
246
289
  }
247
- if (!Number.isNaN(pausedMs) && pausedMs > floorMs) {
290
+ if (!Number.isNaN(pausedMs)) {
248
291
  throw new SlackAppRateLimitedError(new Date(pausedMs).toISOString());
249
292
  }
250
293
  candidates.sort(byTimeThenName);
@@ -30,6 +30,8 @@ export declare const SLACK_POST_TOOL = "slack.messages.post";
30
30
  export declare function findSignalsFailures(entries: readonly RunLedgerEntry[]): RunLedgerEntry[];
31
31
  /** The dedupe key: one adapter on one connection. */
32
32
  export declare function signalsAlertKey(entry: Pick<RunLedgerEntry, "adapter" | "connectionId">): string;
33
+ /** The first words of every signals-failure alert; the Fleet job script finds the alert by them. */
34
+ export declare const SIGNALS_FAILURE_PREFIX = "Signals failure for ";
33
35
  export declare function formatSignalsFailureAlert(entry: RunLedgerEntry, options?: {
34
36
  personName?: string;
35
37
  }): string;
@@ -17,6 +17,8 @@ import * as fs from "node:fs";
17
17
  import * as path from "node:path";
18
18
  import { assertNotIntegrationSecretsPath, personDirName } from "./cursors.js";
19
19
  import { writeFileAtomic } from "./landing.js";
20
+ import { CODEX_BOT_NEEDS_CLAUDE_TEXT } from "./signals-pass.js";
21
+ const CODEX_BOT_NEEDS_CLAUDE_CODE = "claude-logged-out-codex-bot";
20
22
  export const SIGNALS_HEALTH_RULE = 'Owner rule: "sync and build feels wrong. we should be logging sources and signals generated." ' +
21
23
  "A run that lands sources and generates no signals is a failure.";
22
24
  /** One alert per adapter and connection per hour. */
@@ -37,16 +39,21 @@ export function findSignalsFailures(entries) {
37
39
  export function signalsAlertKey(entry) {
38
40
  return `${entry.adapter}:${entry.connectionId ?? "-"}`;
39
41
  }
42
+ /** The first words of every signals-failure alert; the Fleet job script finds the alert by them. */
43
+ export const SIGNALS_FAILURE_PREFIX = "Signals failure for ";
40
44
  export function formatSignalsFailureAlert(entry, options = {}) {
41
45
  const who = options.personName ?? entry.personUid;
42
46
  const lines = [
43
- `Signals failure for ${who}: ${entry.adapter}${entry.connectionId ? ` (${entry.connectionId})` : ""} ` +
47
+ `${SIGNALS_FAILURE_PREFIX}${who}: ${entry.adapter}${entry.connectionId ? ` (${entry.connectionId})` : ""} ` +
44
48
  `landed ${entry.sourcesLanded} source${entry.sourcesLanded === 1 ? "" : "s"} and generated ` +
45
49
  `${entry.signalsGenerated} signal${entry.signalsGenerated === 1 ? "" : "s"}.`,
46
50
  `Run ${entry.runId} (${entry.trigger}, status ${entry.status}) finished ${entry.finishedAt}.`,
47
51
  ];
48
52
  if (entry.error)
49
53
  lines.push(`Error: ${entry.error}`);
54
+ // A Codex bot cannot fix this by signing in to its own tool; say what works.
55
+ if (entry.error === CODEX_BOT_NEEDS_CLAUDE_CODE)
56
+ lines.push(CODEX_BOT_NEEDS_CLAUDE_TEXT);
50
57
  // The rule is about a run with no signals; a partial pass fails on its error alone.
51
58
  if (entry.signalsGenerated === 0)
52
59
  lines.push(SIGNALS_HEALTH_RULE);
@@ -70,6 +70,11 @@ export interface HotChannelGateway {
70
70
  export interface PollContext {
71
71
  /** ISO time: now minus the adapter's catch-up window. */
72
72
  since: string;
73
+ /**
74
+ * ISO time the loop fetched this page, from the run's clock. An adapter
75
+ * that needs the current time reads it here; unset means use `Date.now()`.
76
+ */
77
+ now?: string;
73
78
  personUid: string;
74
79
  /** Present when the run is bound to a connection (on-demand and scheduled syncs). */
75
80
  gateway?: HotChannelGateway;
@@ -161,4 +166,11 @@ export interface CatalogEntry {
161
166
  /** Companion connections (see `companionProviders`) handed to this entry's run. */
162
167
  companionConnectionIds?: readonly string[];
163
168
  }
169
+ /**
170
+ * Adapter error codes for a rate limit, which clears on its own: Slack's
171
+ * `app_rate_limited` (event delivery paused) and the Linear, Attio and Gmail
172
+ * adapters' `rate_limited` (429 after every retry). These are temporary, not a
173
+ * reconnect: the run is retried and the person is not asked to reconnect.
174
+ */
175
+ export declare const TEMPORARY_ADAPTER_ERROR_CODES: ReadonlySet<string>;
164
176
  //# sourceMappingURL=contract.d.ts.map
@@ -18,4 +18,11 @@ export const SUGGESTION_RULE_KINDS = [
18
18
  "owned-by-me",
19
19
  ];
20
20
  export const WATERMARK_KINDS = ["cursor", "timestamp", "webhook"];
21
+ /**
22
+ * Adapter error codes for a rate limit, which clears on its own: Slack's
23
+ * `app_rate_limited` (event delivery paused) and the Linear, Attio and Gmail
24
+ * adapters' `rate_limited` (429 after every retry). These are temporary, not a
25
+ * reconnect: the run is retried and the person is not asked to reconnect.
26
+ */
27
+ export const TEMPORARY_ADAPTER_ERROR_CODES = new Set(["app_rate_limited", "rate_limited"]);
21
28
  //# sourceMappingURL=contract.js.map
@@ -140,6 +140,7 @@ async function runPoll(ctx, adapter, result, key, gateway, gateways = [], select
140
140
  const since = new Date(now.getTime() - adapter.catchUpWindow.maxLookbackMs).toISOString();
141
141
  const response = await adapter.fetch(cursor, {
142
142
  since,
143
+ now: now.toISOString(),
143
144
  personUid: ctx.personUid,
144
145
  beforeWrite: ctx.beforeWrite,
145
146
  ...(gateway ? { gateway } : {}),
@@ -131,6 +131,12 @@ export interface SyncOutcome {
131
131
  reason: ReconnectReason;
132
132
  prompt: string;
133
133
  };
134
+ /**
135
+ * The adapter's error code when the run failed and the error carried one
136
+ * (for example `app_rate_limited` or `rate_limited`). Lets callers tell a
137
+ * temporary failure from others without parsing the message.
138
+ */
139
+ errorCode?: string;
134
140
  /**
135
141
  * Which token the run used for this connection (US-010): `user` when the
136
142
  * signed-in person created the connection, `workspace` when it is a shared
@@ -344,6 +344,10 @@ export async function runOnDemandSync(input) {
344
344
  };
345
345
  if (p.app)
346
346
  outcome.tokenLevel = tokenLevelOf(p.app);
347
+ // Set with or without a connection, so a channel that runs with no app
348
+ // (a personal Slack account) carries the code too.
349
+ if (failed && result?.error?.code)
350
+ outcome.errorCode = result.error.code;
347
351
  if (failed && p.app) {
348
352
  const reason = reconnects.get(p.app.connectionId) ?? (p.app.status === "needs-attention" ? "revoked" : undefined);
349
353
  if (reason)
@@ -1,3 +1,52 @@
1
+ /**
2
+ * The local signals pass (US-011). After each hot-channel adapter run, the
3
+ * pass takes the adapter's channel through the ontology worklist, asks
4
+ * `claude -p` for signals one document at a time, and writes those signals to
5
+ * `companies/{co}/signals/`. It returns the count for the run ledger.
6
+ *
7
+ * Work comes from the worklist, not only from this run's landings: when the
8
+ * worklist script exits 0, the pass takes the channel's unprocessed items in
9
+ * the worklist's order (newest first) up to the run's document cap. Items the
10
+ * cap leaves over stay unmarked, and a later run picks them up, including a
11
+ * run that landed nothing (a bounded backlog drain: at most
12
+ * DEFAULT_MAX_SIGNAL_DOCS claude calls per run, and no claude call at all when
13
+ * the backlog is empty). A channel with no source.yaml (worklist exit 2, the
14
+ * usual case for a hot channel such as `meeting-events`) has no worklist, so
15
+ * the pass keeps its own backlog: landed documents it has not processed yet
16
+ * are listed in `sources/_signals-pending/{channel}.json` and drained, newest
17
+ * first by `when` (else `created_at`), on later runs under the same cap. A
18
+ * cloud-run source (exit 4) is skipped.
19
+ *
20
+ * A landed document with both `payload_ref` and `raw_ref` is a pointer (the
21
+ * meetings, Slack and Attio adapters land these). For it, claude gets the
22
+ * pointer followed by the document `payload_ref` names, capped at
23
+ * MAX_PAYLOAD_BYTES. A payload outside `sources/`, missing or unreadable falls
24
+ * back to the pointer alone, and the reason is warned and kept on the signal.
25
+ *
26
+ * Billing: policy hq-no-headless-print-subscription-billing forbids headless
27
+ * `claude -p` in general. This is its allowed case, per the owner decision of
28
+ * 2026-10-21: the owner's own `claude` login, on their own machine, in a
29
+ * bounded single-turn call. Cloud Claude is not the bot brain, and no model is
30
+ * called from the poller itself. Do not reuse this pass for a shared, fleet or
31
+ * hosted identity.
32
+ *
33
+ * Failures: a pass that fails keeps the real class as its ledger code (see
34
+ * SignalsPassErrorCode), and writes the provider's own reason, redacted and
35
+ * cut, to `warn`. The reason stays out of the ledger because the ledger syncs
36
+ * with the company vault. A failed document is never marked done, so a later
37
+ * run picks it up. No account is picked and no other provider is called here.
38
+ *
39
+ * Unusable replies: a document whose reply is `claude-bad-output` is sent
40
+ * again, up to BAD_OUTPUT_ATTEMPTS calls in all. If every reply is unusable the
41
+ * pass leaves that document for a later run, goes on to the next one, and
42
+ * fails with `claude-bad-output` at the end. Every other failure class stops
43
+ * the pass at once, because it would fail the next document the same way. A
44
+ * reply with no stdout is not sent again, and BAD_OUTPUT_STOP_AFTER documents
45
+ * in a row with unusable replies stop the pass, for the same reason. So a run
46
+ * makes at most the document cap (`maxDocs`) × BAD_OUTPUT_ATTEMPTS calls, and
47
+ * BAD_OUTPUT_STOP_AFTER × BAD_OUTPUT_ATTEMPTS when every reply is unusable.
48
+ */
49
+ import type { BotRuntimeId } from "../bot/config.js";
1
50
  import type { HotChannelRunResult, WriteGuard } from "./loop.js";
2
51
  /**
3
52
  * Ledger `error` values a failed pass records:
@@ -6,8 +55,10 @@ import type { HotChannelRunResult, WriteGuard } from "./loop.js";
6
55
  * - `claude-timeout`: the call ran past its budget.
7
56
  * - `claude-provider-error`: claude reported or exited with some other error.
8
57
  * - `claude-bad-output`: claude finished cleanly and its reply is unusable.
58
+ * - `claude-logged-out-codex-bot`: claude is missing or signed out, and the
59
+ * main bot runs on Codex (see CODEX_BOT_NEEDS_CLAUDE_TEXT).
9
60
  */
10
- export type SignalsPassErrorCode = "claude-usage-limit" | "claude-logged-out" | "claude-timeout" | "claude-provider-error" | "claude-bad-output";
61
+ export type SignalsPassErrorCode = "claude-usage-limit" | "claude-logged-out" | "claude-logged-out-codex-bot" | "claude-timeout" | "claude-provider-error" | "claude-bad-output";
11
62
  /**
12
63
  * A pass failure the run ledger records as `status: failed` with `error` set
13
64
  * to the code. Any other error thrown from the pass is a crash.
@@ -20,6 +71,12 @@ export declare class SignalsPassError extends Error {
20
71
  noRetry: boolean;
21
72
  constructor(code: SignalsPassErrorCode, message: string);
22
73
  }
74
+ /**
75
+ * What the owner of a Codex main bot is told when this pass finds claude
76
+ * missing or signed out. The pass always runs Claude Code, whatever the main
77
+ * bot runs.
78
+ */
79
+ export declare const CODEX_BOT_NEEDS_CLAUDE_TEXT: string;
23
80
  /** Signal types the pass accepts; the same type folders existing signals use. */
24
81
  export declare const SIGNAL_TYPES: readonly ["action_item", "commitment", "decision", "key_point", "participant_contribution", "question", "risk", "summary"];
25
82
  export type SignalType = (typeof SIGNAL_TYPES)[number];
@@ -88,6 +145,12 @@ export interface ClaudeSignalsPassOptions {
88
145
  env?: NodeJS.ProcessEnv;
89
146
  /** Where payload fallbacks are reported. Defaults to one line on stderr. */
90
147
  warn?: (message: string) => void;
148
+ /**
149
+ * The main bot's runtime, read only when claude is missing or signed out. When it
150
+ * is codex, that failure becomes `claude-logged-out-codex-bot` with
151
+ * CODEX_BOT_NEEDS_CLAUDE_TEXT. Unset: the failure is reported as is.
152
+ */
153
+ botRuntime?: () => BotRuntimeId | null;
91
154
  }
92
155
  /** Why the pass sent claude the pointer alone. */
93
156
  export type PayloadFallbackReason = "payload-out-of-bounds" | "payload-missing" | "payload-unreadable";
@@ -1,52 +1,4 @@
1
1
  import { prepareSignalPublication, flushSignalPublications } from "../bot/jobs/signal-to-lane.js";
2
- /**
3
- * The local signals pass (US-011). After each hot-channel adapter run, the
4
- * pass takes the adapter's channel through the ontology worklist, asks
5
- * `claude -p` for signals one document at a time, and writes those signals to
6
- * `companies/{co}/signals/`. It returns the count for the run ledger.
7
- *
8
- * Work comes from the worklist, not only from this run's landings: when the
9
- * worklist script exits 0, the pass takes the channel's unprocessed items in
10
- * the worklist's order (newest first) up to the run's document cap. Items the
11
- * cap leaves over stay unmarked, and a later run picks them up, including a
12
- * run that landed nothing (a bounded backlog drain: at most
13
- * DEFAULT_MAX_SIGNAL_DOCS claude calls per run, and no claude call at all when
14
- * the backlog is empty). A channel with no source.yaml (worklist exit 2, the
15
- * usual case for a hot channel such as `meeting-events`) has no worklist, so
16
- * the pass keeps its own backlog: landed documents it has not processed yet
17
- * are listed in `sources/_signals-pending/{channel}.json` and drained, newest
18
- * first by `when` (else `created_at`), on later runs under the same cap. A
19
- * cloud-run source (exit 4) is skipped.
20
- *
21
- * A landed document with both `payload_ref` and `raw_ref` is a pointer (the
22
- * meetings, Slack and Attio adapters land these). For it, claude gets the
23
- * pointer followed by the document `payload_ref` names, capped at
24
- * MAX_PAYLOAD_BYTES. A payload outside `sources/`, missing or unreadable falls
25
- * back to the pointer alone, and the reason is warned and kept on the signal.
26
- *
27
- * Billing: policy hq-no-headless-print-subscription-billing forbids headless
28
- * `claude -p` in general. This is its allowed case, per the owner decision of
29
- * 2026-10-21: the owner's own `claude` login, on their own machine, in a
30
- * bounded single-turn call. Cloud Claude is not the bot brain, and no model is
31
- * called from the poller itself. Do not reuse this pass for a shared, fleet or
32
- * hosted identity.
33
- *
34
- * Failures: a pass that fails keeps the real class as its ledger code (see
35
- * SignalsPassErrorCode), and writes the provider's own reason, redacted and
36
- * cut, to `warn`. The reason stays out of the ledger because the ledger syncs
37
- * with the company vault. A failed document is never marked done, so a later
38
- * run picks it up. No account is picked and no other provider is called here.
39
- *
40
- * Unusable replies: a document whose reply is `claude-bad-output` is sent
41
- * again, up to BAD_OUTPUT_ATTEMPTS calls in all. If every reply is unusable the
42
- * pass leaves that document for a later run, goes on to the next one, and
43
- * fails with `claude-bad-output` at the end. Every other failure class stops
44
- * the pass at once, because it would fail the next document the same way. A
45
- * reply with no stdout is not sent again, and BAD_OUTPUT_STOP_AFTER documents
46
- * in a row with unusable replies stop the pass, for the same reason. So a run
47
- * makes at most the document cap (`maxDocs`) × BAD_OUTPUT_ATTEMPTS calls, and
48
- * BAD_OUTPUT_STOP_AFTER × BAD_OUTPUT_ATTEMPTS when every reply is unusable.
49
- */
50
2
  import { isRuntimeUsageLimit } from "../bot/runtime-failure.js";
51
3
  import { redactErrorText } from "../../utils/redact-error-text.js";
52
4
  import { acquireSyncLock } from "./sync-lock.js";
@@ -76,6 +28,13 @@ export class SignalsPassError extends Error {
76
28
  this.code = code;
77
29
  }
78
30
  }
31
+ /**
32
+ * What the owner of a Codex main bot is told when this pass finds claude
33
+ * missing or signed out. The pass always runs Claude Code, whatever the main
34
+ * bot runs.
35
+ */
36
+ export const CODEX_BOT_NEEDS_CLAUDE_TEXT = "Your main bot runs on Codex, but signals from hot-channel sync need Claude Code, which is not installed or not signed in on this computer. " +
37
+ "Sign in to Claude Code here (`claude auth login`).";
79
38
  /** Signal types the pass accepts; the same type folders existing signals use. */
80
39
  export const SIGNAL_TYPES = [
81
40
  "action_item",
@@ -606,6 +565,15 @@ export function createClaudeSignalsPass(options) {
606
565
  let preflight;
607
566
  let prompt;
608
567
  let docsSent = 0;
568
+ const codexBot = () => {
569
+ try {
570
+ return options.botRuntime?.() === "codex";
571
+ }
572
+ catch {
573
+ // An unreadable bot config keeps the plain claude message.
574
+ return false;
575
+ }
576
+ };
609
577
  const checkLogin = async () => {
610
578
  const run = await runBounded(claude, ["auth", "status"], { timeoutMs: authTimeoutMs, cwd: claudeCwd, env });
611
579
  if (run.timedOut)
@@ -896,7 +864,11 @@ export function createClaudeSignalsPass(options) {
896
864
  try {
897
865
  await runPass(result, guard, progress);
898
866
  }
899
- catch (err) {
867
+ catch (caught) {
868
+ let err = caught;
869
+ if (err instanceof SignalsPassError && err.code === "claude-logged-out" && codexBot()) {
870
+ err = new SignalsPassError("claude-logged-out-codex-bot", CODEX_BOT_NEEDS_CLAUDE_TEXT);
871
+ }
900
872
  if (err instanceof SignalsPassError) {
901
873
  err.written = progress.written;
902
874
  warn(`signals pass failed (${err.code}): ${err.message}`);
@@ -1,4 +1,5 @@
1
1
  import { type NativeTarget } from '../hook-engine/registration.js';
2
+ import { type CoreNextTarget } from '../../utils/host-registration.js';
2
3
  /** Name of the HQ MCP server entry in ~/.claude.json. */
3
4
  export declare const HQ_MCP_SERVER_NAME = "hq";
4
5
  /** `_hqPack` provenance stamped on the HQ MCP server entry. */
@@ -22,7 +23,7 @@ export declare function masterHookPath(hqRoot: string): string;
22
23
  /** hqd hook shim (US-010): registered instead of master-hook.sh once hqd is installed. */
23
24
  export declare function shimPath(hqRoot: string): string;
24
25
  /** Which HQ hook script the user-scope install registers. */
25
- export type HookTarget = 'master' | 'shim' | NativeTarget;
26
+ export type HookTarget = 'master' | 'shim' | NativeTarget | CoreNextTarget;
26
27
  export declare function charterPath(hqRoot: string): string;
27
28
  export declare function hqSkillsSource(hqRoot: string): string;
28
29
  /** The exact hook command registered for one event (absolute path, quoted). */
@@ -32,6 +33,16 @@ export declare function addClaudeMdBlock(current: string | null, hqRoot: string)
32
33
  /** Strip the HQ block, plus the separator `addClaudeMdBlock` put before it. */
33
34
  export declare function removeClaudeMdBlock(current: string): string;
34
35
  type Doc = Record<string, unknown>;
36
+ type HookGroup = {
37
+ matcher?: string;
38
+ hooks?: Array<Record<string, unknown>>;
39
+ };
40
+ /**
41
+ * `groups` with `want` in the place of the first entry `ours` matches, every
42
+ * other matching entry removed (a group it leaves empty is dropped), and
43
+ * everything else where it was. Null when no entry matches.
44
+ */
45
+ export declare function replaceInPlace(groups: HookGroup[], want: Record<string, unknown>, ours: (entry: unknown) => boolean): HookGroup[] | null;
35
46
  /**
36
47
  * Add one HQ hook group per event; idempotent. An HQ entry for the other
37
48
  * target (master-hook.sh vs the hqd shim) is swapped out. Foreign hooks are untouched.
@@ -5,7 +5,8 @@
5
5
  * safe-write substrate.
6
6
  */
7
7
  import * as path from 'path';
8
- import { engineArgs, isNativeEntry } from '../hook-engine/registration.js';
8
+ import { engineArgs, isCoreNextEntry, isNativeEntry } from '../hook-engine/registration.js';
9
+ import { coreNextArgs, targetForEvent } from '../../utils/host-registration.js';
9
10
  /** Events master-hook.sh is registered for at user scope. */
10
11
  const GLOBAL_HOOK_EVENTS = [
11
12
  'SessionStart',
@@ -99,13 +100,49 @@ export function removeClaudeMdBlock(current) {
99
100
  function isHqHookEntry(entry, hqRoot) {
100
101
  if (!entry || typeof entry !== 'object')
101
102
  return false;
102
- if (isNativeEntry(entry, hqRoot))
103
+ if (isNativeEntry(entry, hqRoot) || isCoreNextEntry(entry, hqRoot))
103
104
  return true;
104
105
  const cmd = entry.command;
105
106
  if (typeof cmd !== 'string')
106
107
  return false;
107
108
  return [masterHookPath(hqRoot), shimPath(hqRoot)].some((target) => cmd.includes(target) || cmd.includes(JSON.stringify(target)) || cmd.includes(shellQuote(target)));
108
109
  }
110
+ function isCoreNext(target) {
111
+ return typeof target === 'object' && 'coreNext' in target;
112
+ }
113
+ /**
114
+ * `groups` with `want` in the place of the first entry `ours` matches, every
115
+ * other matching entry removed (a group it leaves empty is dropped), and
116
+ * everything else where it was. Null when no entry matches.
117
+ */
118
+ export function replaceInPlace(groups, want, ours) {
119
+ let placed = false;
120
+ const out = [];
121
+ for (const group of groups) {
122
+ if (!group || !Array.isArray(group.hooks)) {
123
+ out.push(group);
124
+ continue;
125
+ }
126
+ let touched = false;
127
+ const hooks = [];
128
+ for (const entry of group.hooks) {
129
+ if (!ours(entry)) {
130
+ hooks.push(entry);
131
+ continue;
132
+ }
133
+ touched = true;
134
+ if (!placed) {
135
+ hooks.push(want);
136
+ placed = true;
137
+ }
138
+ }
139
+ if (!touched)
140
+ out.push(group);
141
+ else if (hooks.length > 0)
142
+ out.push({ ...group, hooks });
143
+ }
144
+ return placed ? out : null;
145
+ }
109
146
  /**
110
147
  * Add one HQ hook group per event; idempotent. An HQ entry for the other
111
148
  * target (master-hook.sh vs the hqd shim) is swapped out. Foreign hooks are untouched.
@@ -114,13 +151,28 @@ export function addHqHooks(doc, hqRoot, target = 'master') {
114
151
  const hooks = { ...(doc.hooks ?? {}) };
115
152
  let changed = false;
116
153
  for (const event of GLOBAL_HOOK_EVENTS) {
117
- const want = typeof target === 'object'
118
- ? { type: 'command', command: target.engine, args: engineArgs(hqRoot, event, 'claude', true), timeout: 300 }
119
- : { type: 'command', command: hookCommand(hqRoot, event, target), timeout: 300 };
154
+ // With the new core (US-017), an event it cannot take yet keeps the
155
+ // flag-off target.
156
+ const t = targetForEvent(target, event);
157
+ const want = typeof t !== 'object'
158
+ ? { type: 'command', command: hookCommand(hqRoot, event, t), timeout: 300 }
159
+ : 'coreNext' in t
160
+ ? { type: 'command', command: t.coreNext, args: coreNextArgs('claude', event, hqRoot, 'global'), timeout: 300 }
161
+ : { type: 'command', command: t.engine, args: engineArgs(hqRoot, event, 'claude', true), timeout: 300 };
120
162
  let groups = Array.isArray(hooks[event]) ? [...hooks[event]] : [];
121
163
  const present = groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => h.command === want.command && JSON.stringify(h.args) === JSON.stringify('args' in want ? want.args : undefined)));
122
164
  if (present)
123
165
  continue;
166
+ // To or from the new core, the HQ entry keeps its place among the user's
167
+ // own entries, so their positions (and Codex's position-keyed trust) do
168
+ // not move. Other target swaps keep today's behaviour.
169
+ const inPlace = isCoreNext(target) || groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => isCoreNextEntry(h, hqRoot)));
170
+ const replaced = inPlace ? replaceInPlace(groups, want, (h) => isHqHookEntry(h, hqRoot)) : null;
171
+ if (replaced) {
172
+ hooks[event] = replaced;
173
+ changed = true;
174
+ continue;
175
+ }
124
176
  groups = removeHqHooks({ hooks: { [event]: groups } }, hqRoot).hooks?.[event] ?? [];
125
177
  groups.push({ hooks: [want] });
126
178
  hooks[event] = groups;
@@ -73,9 +73,9 @@ export declare function codexUserHookClaimed(hqRoot: string, target: HookTarget,
73
73
  * The user-scope hooks.json entry: {@link codexHookEntry} behind
74
74
  * {@link codexUserHookClaimed}. `commandWindows` is unchanged.
75
75
  */
76
- export declare function codexUserHookEntry(hqRoot: string, event: string, target?: HookTarget): Record<string, unknown>;
76
+ export declare function codexUserHookEntry(hqRoot: string, event: string, eventTarget?: HookTarget): Record<string, unknown>;
77
77
  /** The HQ hooks.json entry for one event and target. */
78
- export declare function codexHookEntry(hqRoot: string, event: string, target?: HookTarget): Record<string, unknown>;
78
+ export declare function codexHookEntry(hqRoot: string, event: string, eventTarget?: HookTarget): Record<string, unknown>;
79
79
  /**
80
80
  * Add one HQ hook group per event; idempotent. An HQ entry for the other
81
81
  * target (adapter vs the hqd shim) is swapped out, and so is an HQ entry