@indigoai-us/hq-cli 5.345.270 → 5.345.272

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 (52) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/contracts/host-canary-release.json +7 -7
  3. package/dist/command-catalog.generated.d.ts +2 -2
  4. package/dist/command-catalog.generated.js +2 -2
  5. package/dist/commands/core-checkpoint-stop-gate-native.js +2 -13
  6. package/dist/commands/core-session-journal-native.js +20 -4
  7. package/dist/commands/signals-run.d.ts +4 -1
  8. package/dist/commands/signals-run.js +6 -8
  9. package/dist/commands/sync-core.js +2 -1
  10. package/dist/lib/daemon/daemon-restart.d.ts +70 -0
  11. package/dist/lib/daemon/daemon-restart.js +114 -0
  12. package/dist/lib/daemon/hook-requests-work-mesh-shims.d.ts +41 -0
  13. package/dist/lib/daemon/hook-requests-work-mesh-shims.js +237 -0
  14. package/dist/lib/daemon/hook-requests.d.ts +4 -1
  15. package/dist/lib/daemon/hook-requests.js +23 -1
  16. package/dist/lib/daemon/hq-child-bootstrap.mjs +1 -0
  17. package/dist/lib/daemon/installed-cli-restart.js +14 -4
  18. package/dist/lib/daemon/run.d.ts +1 -1
  19. package/dist/lib/daemon/run.js +65 -51
  20. package/dist/lib/daemon/supervisor.js +0 -2
  21. package/dist/lib/hook-engine/coverage.d.ts +21 -0
  22. package/dist/lib/hook-engine/coverage.js +98 -5
  23. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  24. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  25. package/dist/lib/hot-channels/signals-pass.d.ts +10 -2
  26. package/dist/lib/hot-channels/signals-pass.js +13 -3
  27. package/dist/lib/signals/engine.d.ts +0 -2
  28. package/dist/lib/signals/engine.js +12 -7
  29. package/dist/lib/signals/reply.js +35 -82
  30. package/dist/lib/signals/run-lock.d.ts +8 -0
  31. package/dist/lib/signals/run-lock.js +42 -7
  32. package/dist/lib/signals/run-record.js +2 -1
  33. package/dist/lib/signals/settings.d.ts +9 -4
  34. package/dist/lib/signals/settings.js +7 -5
  35. package/dist/lib/signals/steps/extract.d.ts +37 -10
  36. package/dist/lib/signals/steps/extract.js +88 -111
  37. package/dist/lib/signals/steps/types.d.ts +3 -2
  38. package/dist/lib/sync-core/reconcile.d.ts +7 -1
  39. package/dist/lib/sync-core/reconcile.js +105 -18
  40. package/dist/lib/sync-core/release.d.ts +52 -2
  41. package/dist/lib/sync-core/release.js +172 -11
  42. package/dist/lib/sync-core/rollout-state.d.ts +11 -0
  43. package/dist/lib/sync-core/rollout-state.js +16 -0
  44. package/dist/utils/client-health-contract.d.ts +32 -0
  45. package/dist/utils/client-health-contract.js +35 -0
  46. package/dist/utils/client-health.d.ts +43 -0
  47. package/dist/utils/client-health.js +106 -3
  48. package/dist/utils/login-browser.d.ts +1 -0
  49. package/dist/utils/login-browser.js +31 -6
  50. package/dist/utils/spawn-detached-hidden.d.ts +66 -0
  51. package/dist/utils/spawn-detached-hidden.js +222 -0
  52. package/package.json +7 -7
@@ -1,20 +1,25 @@
1
1
  export interface SignalsSettings {
2
2
  maxTurns: number;
3
- maxBudgetUsd: number;
4
3
  lateStartHour: number;
5
4
  briefWaitMinutes: number;
6
5
  /**
7
- * What one source counts as against maxBudgetUsd when the coding tool reports
8
- * no cost for it (Codex always, Grok sometimes). 0 turns the charge off.
6
+ * What one source adds to a run's estimated spend when the coding tool
7
+ * reports no cost for it (Codex always, Grok sometimes). 0 turns it off.
8
+ * The estimate is reported as information; no run stops on it.
9
9
  */
10
10
  unpricedSourceEstimateUsd: number;
11
11
  }
12
12
  export declare const DEFAULT_SIGNALS_SETTINGS: SignalsSettings;
13
13
  export declare const SIGNALS_SETTINGS_REL: string;
14
+ /**
15
+ * Keys in core/settings/signals.yaml that are not settings here are ignored
16
+ * without a message. That covers `maxBudgetUsd` and
17
+ * `incremental.max_budget_usd`, which older settings files still carry from
18
+ * when runs had a spend cap.
19
+ */
14
20
  export declare function loadSignalsSettings(hqRoot: string): SignalsSettings;
15
21
  /** Per-pass limits for a growing source; normal runs retain their own defaults. */
16
22
  export declare function loadIncrementalSettings(hqRoot: string): {
17
23
  maxTurns: number;
18
- maxBudgetUsd: number;
19
24
  };
20
25
  //# sourceMappingURL=settings.d.ts.map
@@ -4,7 +4,6 @@ import * as path from "node:path";
4
4
  import yaml from "js-yaml";
5
5
  export const DEFAULT_SIGNALS_SETTINGS = {
6
6
  maxTurns: 40,
7
- maxBudgetUsd: 2.0,
8
7
  lateStartHour: 22,
9
8
  briefWaitMinutes: 20,
10
9
  unpricedSourceEstimateUsd: 0.1,
@@ -12,12 +11,17 @@ export const DEFAULT_SIGNALS_SETTINGS = {
12
11
  /** maxTurns: whole number >= 1. lateStartHour: whole hour 1-24 (0 would make every job late; 24 turns it off). */
13
12
  const VALID = {
14
13
  maxTurns: (v) => Number.isInteger(v) && v >= 1,
15
- maxBudgetUsd: (v) => Number.isFinite(v) && v >= 0,
16
14
  lateStartHour: (v) => Number.isInteger(v) && v >= 1 && v <= 24,
17
15
  briefWaitMinutes: (v) => Number.isFinite(v) && v >= 0,
18
16
  unpricedSourceEstimateUsd: (v) => Number.isFinite(v) && v >= 0,
19
17
  };
20
18
  export const SIGNALS_SETTINGS_REL = path.join("core", "settings", "signals.yaml");
19
+ /**
20
+ * Keys in core/settings/signals.yaml that are not settings here are ignored
21
+ * without a message. That covers `maxBudgetUsd` and
22
+ * `incremental.max_budget_usd`, which older settings files still carry from
23
+ * when runs had a spend cap.
24
+ */
21
25
  export function loadSignalsSettings(hqRoot) {
22
26
  const out = { ...DEFAULT_SIGNALS_SETTINGS };
23
27
  let raw;
@@ -49,14 +53,12 @@ export function loadSignalsSettings(hqRoot) {
49
53
  }
50
54
  /** Per-pass limits for a growing source; normal runs retain their own defaults. */
51
55
  export function loadIncrementalSettings(hqRoot) {
52
- const out = { maxTurns: 12, maxBudgetUsd: 0.4 };
56
+ const out = { maxTurns: 12 };
53
57
  try {
54
58
  const raw = yaml.load(fs.readFileSync(path.join(hqRoot, SIGNALS_SETTINGS_REL), "utf8"));
55
59
  const v = raw?.incremental;
56
60
  if (typeof v?.max_turns === "number" && VALID.maxTurns(v.max_turns))
57
61
  out.maxTurns = v.max_turns;
58
- if (typeof v?.max_budget_usd === "number" && VALID.maxBudgetUsd(v.max_budget_usd))
59
- out.maxBudgetUsd = v.max_budget_usd;
60
62
  }
61
63
  catch (err) {
62
64
  if (err.code !== "ENOENT")
@@ -13,6 +13,16 @@ export declare const WORKLIST_ITEM_TIMEOUT_MS = 10000;
13
13
  * fixed script budget plus WORKLIST_ITEM_TIMEOUT_MS per item.
14
14
  */
15
15
  export declare function worklistTimeoutMs(limit: number): number;
16
+ /**
17
+ * The longest the step can go between two refreshes of the run lock, which it
18
+ * refreshes when a source starts and when it finishes: one channel's redo and
19
+ * listing calls before the first source, then one source's turn on the Fleet
20
+ * helper, its second turn on the claude CLI when the helper refuses it as too
21
+ * large, and its mark-done call. With the defaults: 60 s + 260 s + 600 s +
22
+ * 600 s + 60 s = 1,580 s, about 26 minutes. LOCK_STALE_MS (3 hours) is more
23
+ * than six times that.
24
+ */
25
+ export declare const MAX_SOURCE_GAP_MS: number;
16
26
  export declare const CODEX_PERMISSION_PROFILE = "hq_signals_extract";
17
27
  export declare const CANDIDATE_WRAPPER_NAME = "write-candidate.sh";
18
28
  /** The sandbox profile the step writes to <turn dir>/.grok/sandbox.toml for a grok turn. */
@@ -44,7 +54,7 @@ export interface PartialDocument {
44
54
  audience: string[];
45
55
  }
46
56
  export interface ExtractStepOptions {
47
- /** Charge per source when the runtime reports no cost. Default UNPRICED_SOURCE_ESTIMATE_USD. */
57
+ /** Estimated spend per source when the runtime reports no cost. Default UNPRICED_SOURCE_ESTIMATE_USD. */
48
58
  unpricedSourceEstimateUsd?: number;
49
59
  documentOverride?: PartialDocument;
50
60
  priorSignals?: readonly PriorSignal[];
@@ -85,18 +95,17 @@ interface WorkItem {
85
95
  skip?: string;
86
96
  }
87
97
  /**
88
- * What one source is charged against the run budget when the runtime reports
89
- * no cost for it. `codex exec` has no turn or budget option and its event
90
- * stream carries no cost, and a grok end event can omit total_cost_usd. Without
91
- * a charge the run's spend stays 0 and the budget stop never fires.
98
+ * What one source adds to the run's estimated spend when the runtime reports
99
+ * no cost for it. `codex exec` reports no cost in its event stream, and a grok
100
+ * end event can omit total_cost_usd. The figure is reported as information
101
+ * only: nothing stops a run on it.
92
102
  *
93
103
  * 0.10 USD (owner decision, 2026-11-16) is an assumption, not a measurement:
94
- * no priced codex or grok extract run exists to derive it from. With the
95
- * default 2.00 USD run budget it lets at most 20 such sources run. A codex turn
96
- * that fails or is refused is not charged. The run record marks the spend as
104
+ * no priced codex or grok extract run exists to derive it from. A codex turn
105
+ * that fails or is refused adds nothing. The run record marks the spend as
97
106
  * estimated.
98
107
  * Set `unpricedSourceEstimateUsd` in core/settings/signals.yaml to change it;
99
- * 0 turns the charge off.
108
+ * 0 turns the estimate off.
100
109
  */
101
110
  export declare const UNPRICED_SOURCE_ESTIMATE_USD = 0.1;
102
111
  /** The Executive bot's runtime (lib/bot/executive.ts), or null when there is no personal bot. */
@@ -247,6 +256,24 @@ export declare function validateNewCandidates(files: string[], expectedAudienceK
247
256
  updated?: number;
248
257
  skipped?: number;
249
258
  };
259
+ /**
260
+ * Whether a claude turn was refused for a provider limit, read from claude's
261
+ * own result event and nothing else. stderr and the turn's output are never
262
+ * read: they can carry the source's words, and a source that says "429" or
263
+ * "rate limit" must not stop a run.
264
+ *
265
+ * The event must be one claude marked as failed (`is_error`, or an `error*`
266
+ * subtype). Then:
267
+ * - `rate`: its `api_error_status` field is the number 429.
268
+ * - `usage`: its whole `result` is the provider's usage-limit sentence, by the
269
+ * rule the hot-channel signals pass uses (isUsageLimitSentence: short, opens
270
+ * as the sentence, no clause after it). claude gives a plan limit no code of
271
+ * its own, so this one field is read as text.
272
+ *
273
+ * codex and grok report no code for a limit, so a limit on those tools is not
274
+ * detected here: each remaining source fails and the run ends as it did before.
275
+ */
276
+ export declare function claudeProviderLimit(result: Record<string, unknown> | null): "usage" | "rate" | null;
250
277
  /** Paths a turn may touch, all resolved through symlinks. */
251
278
  export interface TurnScope {
252
279
  hqRoot: string;
@@ -364,7 +391,7 @@ export declare function chooseExtractRuntime(main: BotRuntimeId, avail: {
364
391
  grok: () => GrokAvailability;
365
392
  claude: () => ToolAvailability;
366
393
  }, platform?: NodeJS.Platform): ExtractRuntimeChoice;
367
- export declare function claudeTurnArgs(prompt: string, scope: TurnScope, maxTurns: number, budgetUsd: number): string[];
394
+ export declare function claudeTurnArgs(prompt: string, scope: TurnScope, maxTurns: number): string[];
368
395
  /**
369
396
  * argv for one codex turn. The prompt goes on stdin (`-`), which keeps a long
370
397
  * transcript off argv; the reply comes back in `outputFile`.
@@ -29,7 +29,7 @@
29
29
  * --permission-mode dontAsk --permission-prompts none --restricted
30
30
  * --tools Read,Bash --strict-mcp-config --mcp-config {"mcpServers":{}}
31
31
  * --disable-slash-commands --no-session-persistence
32
- * --max-turns <n> --max-budget-usd <x> --add-dir <channel dir>
32
+ * --max-turns <n> --add-dir <channel dir>
33
33
  * --allowedTools Read(//<channel dir>/**) "Bash(bash <wrapper> *)"
34
34
  * dontAsk denies every tool call no allow rule covers. --restricted ignores
35
35
  * the user, project and local settings files (so no HQ or user allow rules,
@@ -145,7 +145,7 @@ import { resolveExecutiveBot } from "../../bot/executive.js";
145
145
  import { botsRoot } from "../../bot/paths.js";
146
146
  import { parseClaudeAuthStatus } from "../../bot/runtime/claude.js";
147
147
  import { SIGN_IN_CHECK_TIMEOUT_MS } from "../../bot/runtime-sign-in.js";
148
- import { CLAUDE_LOGGED_OUT_RE, CLAUDE_ISOLATION_ARGS, parseClaudeSignals } from "../../hot-channels/signals-pass.js";
148
+ import { CLAUDE_LOGGED_OUT_RE, CLAUDE_ISOLATION_ARGS, isUsageLimitSentence, parseClaudeSignals } from "../../hot-channels/signals-pass.js";
149
149
  import { assertAllowedPath, assertNoEscapingLinks, guardedRemove, guardedWrite, realRelPath } from "../write-guard.js";
150
150
  import { codexLockdownEnv, codexLockdownFilesystem, codexLockdownFlags, lockdownHomes, passwdHome, resolveCodexLockdownTarget, } from "../codex-lockdown.js";
151
151
  import { signalsCodexLogin } from "../codex-login.js";
@@ -173,6 +173,16 @@ export const WORKLIST_ITEM_TIMEOUT_MS = 10_000;
173
173
  export function worklistTimeoutMs(limit) {
174
174
  return SCRIPT_TIMEOUT_MS + Math.max(0, limit) * WORKLIST_ITEM_TIMEOUT_MS;
175
175
  }
176
+ /**
177
+ * The longest the step can go between two refreshes of the run lock, which it
178
+ * refreshes when a source starts and when it finishes: one channel's redo and
179
+ * listing calls before the first source, then one source's turn on the Fleet
180
+ * helper, its second turn on the claude CLI when the helper refuses it as too
181
+ * large, and its mark-done call. With the defaults: 60 s + 260 s + 600 s +
182
+ * 600 s + 60 s = 1,580 s, about 26 minutes. LOCK_STALE_MS (3 hours) is more
183
+ * than six times that.
184
+ */
185
+ export const MAX_SOURCE_GAP_MS = SCRIPT_TIMEOUT_MS + worklistTimeoutMs(DEFAULT_WORKLIST_LIMIT) + 2 * DEFAULT_TURN_TIMEOUT_MS + SCRIPT_TIMEOUT_MS;
176
186
  export const CODEX_PERMISSION_PROFILE = "hq_signals_extract";
177
187
  export const CANDIDATE_WRAPPER_NAME = "write-candidate.sh";
178
188
  /** The sandbox profile the step writes to <turn dir>/.grok/sandbox.toml for a grok turn. */
@@ -215,22 +225,19 @@ export function claudeAllowedTools(channelDir, wrapperPath) {
215
225
  return [`Read(/${channelDir}/**)`, `Bash(bash ${wrapperPath} *)`];
216
226
  }
217
227
  /**
218
- * What one source is charged against the run budget when the runtime reports
219
- * no cost for it. `codex exec` has no turn or budget option and its event
220
- * stream carries no cost, and a grok end event can omit total_cost_usd. Without
221
- * a charge the run's spend stays 0 and the budget stop never fires.
228
+ * What one source adds to the run's estimated spend when the runtime reports
229
+ * no cost for it. `codex exec` reports no cost in its event stream, and a grok
230
+ * end event can omit total_cost_usd. The figure is reported as information
231
+ * only: nothing stops a run on it.
222
232
  *
223
233
  * 0.10 USD (owner decision, 2026-11-16) is an assumption, not a measurement:
224
- * no priced codex or grok extract run exists to derive it from. With the
225
- * default 2.00 USD run budget it lets at most 20 such sources run. A codex turn
226
- * that fails or is refused is not charged. The run record marks the spend as
234
+ * no priced codex or grok extract run exists to derive it from. A codex turn
235
+ * that fails or is refused adds nothing. The run record marks the spend as
227
236
  * estimated.
228
237
  * Set `unpricedSourceEstimateUsd` in core/settings/signals.yaml to change it;
229
- * 0 turns the charge off.
238
+ * 0 turns the estimate off.
230
239
  */
231
240
  export const UNPRICED_SOURCE_ESTIMATE_USD = 0.1;
232
- /** Float tolerance for the run budget check, far below any real per-source cost. */
233
- const BUDGET_EPSILON_USD = 1e-9;
234
241
  /**
235
242
  * A citation marker in a signal body. The extract prompt asks for
236
243
  * (cite: "a quote") or (cite: 00:12:31). Near variants are also taken as a
@@ -243,8 +250,6 @@ const BUDGET_EPSILON_USD = 1e-9;
243
250
  * yet how often each runtime writes the marker.
244
251
  */
245
252
  const SIGNAL_CITATION_RE = /[([(]\s*cit(?:e|ed|ation)\s*[::]\s*[^\s)\])]/i;
246
- /** The result subtype claude prints when --max-budget-usd ends the turn. Only claude is given a budget. */
247
- const CLAUDE_BUDGET_STOP_SUBTYPE = "error_max_budget_usd";
248
253
  /** The Executive bot's runtime (lib/bot/executive.ts), or null when there is no personal bot. */
249
254
  export function defaultResolveBotRuntime(root = botsRoot()) {
250
255
  const main = resolveExecutiveBot({ root })?.config ?? null;
@@ -793,6 +798,38 @@ export function validateNewCandidates(files, expectedAudienceKey, scope, priorSi
793
798
  }
794
799
  return { kept, rejected, foreign, ...(priorSignals.length ? { updated, skipped: skipped + priorSignals.length - matchedPriorIds.size } : {}) };
795
800
  }
801
+ /**
802
+ * Whether a claude turn was refused for a provider limit, read from claude's
803
+ * own result event and nothing else. stderr and the turn's output are never
804
+ * read: they can carry the source's words, and a source that says "429" or
805
+ * "rate limit" must not stop a run.
806
+ *
807
+ * The event must be one claude marked as failed (`is_error`, or an `error*`
808
+ * subtype). Then:
809
+ * - `rate`: its `api_error_status` field is the number 429.
810
+ * - `usage`: its whole `result` is the provider's usage-limit sentence, by the
811
+ * rule the hot-channel signals pass uses (isUsageLimitSentence: short, opens
812
+ * as the sentence, no clause after it). claude gives a plan limit no code of
813
+ * its own, so this one field is read as text.
814
+ *
815
+ * codex and grok report no code for a limit, so a limit on those tools is not
816
+ * detected here: each remaining source fails and the run ends as it did before.
817
+ */
818
+ export function claudeProviderLimit(result) {
819
+ if (!result)
820
+ return null;
821
+ const errorSubtype = typeof result.subtype === "string" && result.subtype.startsWith("error");
822
+ if (result.is_error !== true && !errorSubtype)
823
+ return null;
824
+ if (result.api_error_status === 429)
825
+ return "rate";
826
+ if (typeof result.result === "string" && isUsageLimitSentence(result.result))
827
+ return "usage";
828
+ return null;
829
+ }
830
+ function providerLimitError(tool, kind) {
831
+ return `${tool} ${kind === "usage" ? "is out of usage" : "is rate limited"}; the run stopped and the remaining sources wait for the next run`;
832
+ }
796
833
  function classifyFailure(text, fallback) {
797
834
  if (CLAUDE_LOGGED_OUT_RE.test(text))
798
835
  return { error: "coding tool is not logged in", errorKind: "signed-out" };
@@ -1153,7 +1190,7 @@ function toolAvailability(ctx, bin, statusArgs, parse) {
1153
1190
  }
1154
1191
  return { installed: true, signedIn: parse({ code: res.status, signal: null, stdout: res.stdout, stderr: res.stderr }) };
1155
1192
  }
1156
- export function claudeTurnArgs(prompt, scope, maxTurns, budgetUsd) {
1193
+ export function claudeTurnArgs(prompt, scope, maxTurns) {
1157
1194
  return [
1158
1195
  "-p",
1159
1196
  prompt,
@@ -1174,8 +1211,6 @@ export function claudeTurnArgs(prompt, scope, maxTurns, budgetUsd) {
1174
1211
  "--no-session-persistence",
1175
1212
  "--max-turns",
1176
1213
  String(maxTurns),
1177
- "--max-budget-usd",
1178
- budgetUsd.toFixed(4),
1179
1214
  "--add-dir",
1180
1215
  scope.channelDir,
1181
1216
  "--allowedTools",
@@ -1271,10 +1306,10 @@ function stripFence(text) {
1271
1306
  const m = /^```(?:json)?\s*\n([\s\S]*?)\n```\s*$/.exec(text.trim());
1272
1307
  return m ? m[1] : text;
1273
1308
  }
1274
- function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
1309
+ function runTurn(ctx, runtime, prompt, scope, opts) {
1275
1310
  let cwd = scope.turnDir;
1276
1311
  let cmd = runtime === "claude" ? opts.claudeBin : runtime === "grok" ? opts.grokBin : opts.codexBin;
1277
- let args = runtime === "claude" ? claudeTurnArgs(prompt, scope, ctx.maxTurns, budgetUsd) : [];
1312
+ let args = runtime === "claude" ? claudeTurnArgs(prompt, scope, ctx.maxTurns) : [];
1278
1313
  let env = runtime === "claude" ? claudeSignalsEnv(process.env) : { ...process.env, HQ_ROOT: ctx.hqRoot };
1279
1314
  let grokHome;
1280
1315
  let codexRoot;
@@ -1347,15 +1382,15 @@ function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
1347
1382
  fs.rmSync(codexRoot, { recursive: true, force: true });
1348
1383
  }
1349
1384
  const parsed = parseTurnOutput(res.stdout);
1350
- // codex never reports a cost and grok may not. Charge the estimate so the
1351
- // run budget still stops the run. claude is capped by its own --max-budget-usd.
1352
- // A grok turn that started and then failed or timed out is charged too, since
1353
- // it may have used the model; only a runtime that could not start is free. A
1354
- // reported cost of 0 counts as reported and is not replaced by the estimate.
1385
+ // codex never reports a cost and grok may not. Count the estimate so the
1386
+ // run's estimated spend is not reported as 0. A grok turn that started and
1387
+ // then failed or timed out is counted too, since it may have used the model;
1388
+ // only a runtime that could not start counts nothing. A reported cost of 0
1389
+ // counts as reported and is not replaced by the estimate.
1355
1390
  const cost = runtime === "claude" || parsed.costReported ? { costUsd: parsed.costUsd } : { costUsd: opts.unpricedSourceEstimateUsd, costEstimated: true };
1356
- // A codex turn that fails, times out or is refused by the lockdown costs
1357
- // nothing against the run budget (owner decision, 2026-11-16): only a codex
1358
- // turn that finished and wrote its candidates is charged the estimate.
1391
+ // A codex turn that fails, times out or is refused by the lockdown adds
1392
+ // nothing to the estimated spend (owner decision, 2026-11-16): only a codex
1393
+ // turn that finished and wrote its candidates counts the estimate.
1359
1394
  const failCost = runtime === "codex" ? { costUsd: 0 } : cost;
1360
1395
  const all = `${res.stderr}\n${res.stdout}`;
1361
1396
  if (res.error) {
@@ -1364,12 +1399,11 @@ function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
1364
1399
  return { ok: false, error: `${runtime} timed out after ${opts.turnTimeoutMs}ms`, errorKind: "transient", turns: parsed.turns, ...failCost };
1365
1400
  return { ok: false, error: `${runtime} could not start: ${res.error.message}`.slice(0, 300), errorKind: "other", turns: 0, costUsd: 0 };
1366
1401
  }
1367
- // The runtime stopped the turn at its own budget cap (claude: result subtype
1368
- // error_max_budget_usd, with a non-zero exit). That is the run's budget stop,
1369
- // not a failed item.
1370
- if (runtime === "claude" && parsed.result?.subtype === CLAUDE_BUDGET_STOP_SUBTYPE) {
1371
- return { ok: false, error: "budget-exceeded", budgetExceeded: true, turns: parsed.turns, ...cost };
1372
- }
1402
+ // A provider limit, from claude's result event only (claudeProviderLimit). Checked before the exit code and
1403
+ // the error-result branch, because claude reports a refused turn either way.
1404
+ const limit = runtime === "claude" ? claudeProviderLimit(parsed.result) : null;
1405
+ if (limit)
1406
+ return { ok: false, error: providerLimitError("claude", limit), errorKind: "transient", providerLimit: true, turns: parsed.turns, ...failCost };
1373
1407
  if (res.status !== 0) {
1374
1408
  const c = classifyFailure(all, `${runtime} exited ${String(res.status)}: ${res.stderr.trim().slice(0, 200)}`);
1375
1409
  return { ok: false, ...c, turns: parsed.turns, ...failCost };
@@ -1481,7 +1515,9 @@ async function runFleetTurn(ctx, target, prompt, scope, opts) {
1481
1515
  if (result.kind === "error") {
1482
1516
  const { errorKind, reachedModel } = fleetExtractFailure(result.code);
1483
1517
  const detail = result.code === "timeout" ? ` after ${opts.turnTimeoutMs}ms` : "";
1484
- return { ok: false, error: fleetFailureMessage(target, result.code, detail), errorKind, turns: reachedModel ? 1 : 0, ...(reachedModel ? charged : { costUsd: 0 }) };
1518
+ // The helper's own codes for a provider limit.
1519
+ const providerLimit = result.code === "rate_limited" || result.code === "out_of_usage";
1520
+ return { ok: false, error: fleetFailureMessage(target, result.code, detail), errorKind, turns: reachedModel ? 1 : 0, ...(reachedModel ? charged : { costUsd: 0 }), ...(providerLimit ? { providerLimit } : {}) };
1485
1521
  }
1486
1522
  if (scope.wrapperBody === undefined) {
1487
1523
  return { ok: false, error: "pinned candidate writer is missing", errorKind: "other", turns: 1, ...charged };
@@ -1562,20 +1598,18 @@ export function codexHomeInstructions(codexHome) {
1562
1598
  return found;
1563
1599
  }
1564
1600
  export async function extractPartialDocument(ctx, doc, prior) {
1565
- if (ctx.maxBudgetUsd <= 0)
1566
- return { status: "partial", error: "budget-exceeded", itemsIn: 1, itemsOut: 0, modelTurns: 0, estimatedSpendUsd: 0 };
1567
1601
  const prompt = buildExtractPrompt({ documentOverride: doc, priorSignals: prior, skillText: "", company: ctx.company, channel: "", item: { file: "" }, itemPath: "", wrapperPath: "" });
1568
1602
  // Same no-tool JSON extractor as the hot-channel pass. Run in a blank cwd so
1569
1603
  // project instructions cannot change the response or grant filesystem access.
1570
1604
  const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "hq-incremental-"));
1571
1605
  let run;
1572
1606
  try {
1573
- run = ctx.spawn("claude", ["-p", ...CLAUDE_ISOLATION_ARGS, "--output-format", "json", "--max-turns", String(ctx.maxTurns), "--max-budget-usd", String(ctx.maxBudgetUsd)], { cwd, env: claudeSignalsEnv(process.env), timeoutMs: 120_000, input: prompt });
1607
+ run = ctx.spawn("claude", ["-p", ...CLAUDE_ISOLATION_ARGS, "--output-format", "json", "--max-turns", String(ctx.maxTurns)], { cwd, env: claudeSignalsEnv(process.env), timeoutMs: 120_000, input: prompt });
1574
1608
  }
1575
1609
  finally {
1576
1610
  fs.rmSync(cwd, { recursive: true, force: true });
1577
1611
  }
1578
- // One parse of the JSON envelope, used for the budget-stop check and the success path.
1612
+ // One parse of the JSON envelope, for the turn count and the reported cost.
1579
1613
  const envelope = (() => {
1580
1614
  if (run.error)
1581
1615
  return null;
@@ -1588,18 +1622,6 @@ export async function extractPartialDocument(ctx, doc, prior) {
1588
1622
  return null;
1589
1623
  }
1590
1624
  })();
1591
- // claude stopped the turn at --max-budget-usd. That is a budget stop, not a
1592
- // login problem; the caller leaves the cursor where it was.
1593
- if (envelope?.subtype === CLAUDE_BUDGET_STOP_SUBTYPE) {
1594
- return {
1595
- status: "partial",
1596
- error: "budget-exceeded",
1597
- itemsIn: 1,
1598
- itemsOut: 0,
1599
- modelTurns: typeof envelope.num_turns === "number" ? envelope.num_turns : 1,
1600
- estimatedSpendUsd: typeof envelope.total_cost_usd === "number" ? envelope.total_cost_usd : 0,
1601
- };
1602
- }
1603
1625
  if (run.error || run.status !== 0)
1604
1626
  throw new Error("Signal extraction failed; the cursor was not advanced. Check the coding-tool login and retry.");
1605
1627
  // parseClaudeSignals throws its own error for output that is not a usable envelope.
@@ -1703,23 +1725,12 @@ export function createExtractStep(options = {}) {
1703
1725
  let itemsOut = 0;
1704
1726
  let modelTurns = 0;
1705
1727
  let spent = 0;
1706
- let lastCost = 0;
1707
1728
  let rejected = 0;
1708
1729
  let updated = 0;
1709
1730
  let skipped = 0;
1710
1731
  let processedAny = false;
1711
- let budgetStop = false;
1712
1732
  /** Sources whose runtime reported no cost; their spend is the per-source estimate. */
1713
1733
  let unpricedSources = 0;
1714
- /** Sources a model turn ran for, and listed sources not started when the budget stopped the run. */
1715
- let sourcesRun = 0;
1716
- let sourcesLeft = 0;
1717
- /**
1718
- * The first source a budget stop left unfinished, which the next run takes first: the source whose
1719
- * turn the runtime stopped at its cap, or, when the run stops between sources, the next source it
1720
- * did not start. Named in the record so a source that never fits is findable.
1721
- */
1722
- let budgetStoppedAt;
1723
1734
  /** Signal candidates with no citation marker, and the sources they came from. Counted, not rejected. */
1724
1735
  let uncitedCandidates = 0;
1725
1736
  const uncitedSources = [];
@@ -1737,6 +1748,8 @@ export function createExtractStep(options = {}) {
1737
1748
  else if (unrunRedo.length > 0)
1738
1749
  errorKind = "other";
1739
1750
  const skippedItems = [];
1751
+ /** The source whose turn the provider refused for a usage or rate limit; the run stopped there. */
1752
+ let providerLimitStoppedAt;
1740
1753
  const sourcesReal = fs.realpathSync(path.join(ctx.hqRoot, "companies", ctx.company, "sources"));
1741
1754
  outer: for (const ch of channels) {
1742
1755
  const base = ["--company", ctx.company, "--channel", ch.channel, ...(ch.force ? ["--force"] : [])];
@@ -1816,17 +1829,8 @@ export function createExtractStep(options = {}) {
1816
1829
  errorKind = "other";
1817
1830
  continue;
1818
1831
  }
1819
- const remaining = ctx.maxBudgetUsd - spent;
1820
- // BUDGET_EPSILON_USD absorbs float drift: nineteen 0.10 charges sum to
1821
- // just over 1.90, which must not stop the twentieth source at 2.00.
1822
- if (spent > 0 && (spent >= ctx.maxBudgetUsd - BUDGET_EPSILON_USD || remaining < lastCost - BUDGET_EPSILON_USD)) {
1823
- // This source is not started and not marked done; the next run takes it first.
1824
- budgetStoppedAt = item.file;
1825
- budgetStop = true;
1826
- // This source and the ones listed after it in this channel. Later channels are not listed yet.
1827
- sourcesLeft = items.slice(items.indexOf(item)).filter((i) => !i.skip).length;
1828
- break outer;
1829
- }
1832
+ // A source starts: progress, so the run's lock is refreshed. The process blocks on each turn.
1833
+ ctx.heartbeat?.();
1830
1834
  let sourceRef = `${ch.channel}:${path.basename(item.file)}`;
1831
1835
  const sourceFile = fs.realpathSync(path.join(channelDir, path.basename(item.file)));
1832
1836
  if (path.dirname(sourceFile) !== channelDir)
@@ -1883,7 +1887,7 @@ export function createExtractStep(options = {}) {
1883
1887
  fleetTurn = fleetResult;
1884
1888
  }
1885
1889
  }
1886
- turn = fleetTurn ?? runTurn(ctx, runtime, promptFor(runtime), scope, Math.max(0, remaining), turnOpts);
1890
+ turn = fleetTurn ?? runTurn(ctx, runtime, promptFor(runtime), scope, turnOpts);
1887
1891
  if (tooLargeFor !== undefined && !turn.ok && turn.errorKind === "signed-out") {
1888
1892
  // The personal claude login is signed out, but the run is on the
1889
1893
  // bot's login, which still works: only this oversized item fails,
@@ -1894,9 +1898,10 @@ export function createExtractStep(options = {}) {
1894
1898
  finally {
1895
1899
  fs.rmSync(turnDir, { recursive: true, force: true });
1896
1900
  }
1901
+ // The source's turn finished, whatever its result: progress again.
1902
+ ctx.heartbeat?.();
1897
1903
  modelTurns += turn.turns;
1898
1904
  spent += turn.costUsd;
1899
- lastCost = turn.costUsd;
1900
1905
  if (turn.costEstimated)
1901
1906
  unpricedSources += 1;
1902
1907
  if (turn.droppedCandidates?.length) {
@@ -1904,18 +1909,12 @@ export function createExtractStep(options = {}) {
1904
1909
  droppedCandidates.push({ file: item.file, index: d.index, reason: d.reason });
1905
1910
  }
1906
1911
  }
1907
- sourcesRun += 1;
1908
1912
  const created = [...allCandidateFiles(ctx.hqRoot)].filter((f) => !before.has(f));
1909
- if (!turn.ok && (priorSignals.length || turn.budgetExceeded)) {
1913
+ if (!turn.ok && priorSignals.length) {
1910
1914
  // Failed model turns must not leave structured duplicates for garden.
1911
- // A budget-stopped source runs again next time and would write its
1912
- // candidates a second time, so the stopped turn's are removed too:
1913
- // its signal candidates and its entity candidates. A failed turn
1914
- // with prior signals keeps the scope it had, signal candidates only.
1915
- const stores = turn.budgetExceeded ? ["signals", "ontology"] : ["signals"];
1916
1915
  for (const file of created) {
1917
1916
  const rel = realRelPath(ctx.hqRoot, file);
1918
- if (!rel || !stores.some((store) => rel.startsWith(`companies/${ctx.company}/${store}/_candidates/`)))
1917
+ if (!rel || !rel.startsWith(`companies/${ctx.company}/signals/_candidates/`))
1919
1918
  continue;
1920
1919
  let text;
1921
1920
  try {
@@ -1948,18 +1947,13 @@ export function createExtractStep(options = {}) {
1948
1947
  failures.push({ file: item.file, error: `candidate written outside ${ctx.company} (deleted): ${v.foreign.join(", ")}`.slice(0, 300) });
1949
1948
  if (!errorKind)
1950
1949
  errorKind = "other";
1951
- if (turn.budgetExceeded) {
1952
- // The breach is recorded above; the runtime's budget stop still ends the run.
1953
- budgetStoppedAt = item.file;
1954
- budgetStop = true;
1955
- break outer;
1956
- }
1957
1950
  continue;
1958
1951
  }
1959
- if (!turn.ok && turn.budgetExceeded) {
1960
- // The item is not marked done, so the next run takes it again.
1961
- budgetStoppedAt = item.file;
1962
- budgetStop = true;
1952
+ if (!turn.ok && turn.providerLimit) {
1953
+ // Every later source would be refused too. This one stays queued and no other is started.
1954
+ failures.push({ file: item.file, error: turn.error ?? "provider limit" });
1955
+ errorKind = "transient";
1956
+ providerLimitStoppedAt = item.file;
1963
1957
  break outer;
1964
1958
  }
1965
1959
  if (!turn.ok) {
@@ -1988,30 +1982,13 @@ export function createExtractStep(options = {}) {
1988
1982
  ...(failures.length ? { failures } : {}),
1989
1983
  ...(skippedItems.length ? { skippedItems } : {}),
1990
1984
  ...(rejected ? { rejectedCandidates: rejected } : {}),
1991
- detail: { new: itemsOut, updated, skipped, runtime, ...(runtime === "claude" ? { login: fleet ? "fleet" : "claude-cli", ...(fleet ? { bot: fleet.botName } : {}) } : {}), ...(fleetFallback ? { loginFallback: fleetFallback } : {}), ...(fleetTooLarge.length ? { fleetTooLarge } : {}), ...(choice.fallback ? { fallback: choice.fallback } : {}), ...(budgetStoppedAt ? { budgetStoppedAt } : {}), ...(unpricedSources ? { spendEstimated: true, unpricedSources, unpricedSourceEstimateUsd: turnOpts.unpricedSourceEstimateUsd } : {}), ...(uncitedCandidates ? { uncitedCandidates, uncitedSources } : {}), ...(droppedCandidates.length ? { droppedCandidates } : {}), ...listingDetail },
1985
+ detail: { new: itemsOut, updated, skipped, runtime, ...(runtime === "claude" ? { login: fleet ? "fleet" : "claude-cli", ...(fleet ? { bot: fleet.botName } : {}) } : {}), ...(fleetFallback ? { loginFallback: fleetFallback } : {}), ...(fleetTooLarge.length ? { fleetTooLarge } : {}), ...(choice.fallback ? { fallback: choice.fallback } : {}), ...(unpricedSources ? { spendEstimated: true, unpricedSources, unpricedSourceEstimateUsd: turnOpts.unpricedSourceEstimateUsd } : {}), ...(uncitedCandidates ? { uncitedCandidates, uncitedSources } : {}), ...(droppedCandidates.length ? { droppedCandidates } : {}), ...(providerLimitStoppedAt ? { providerLimitStoppedAt } : {}), ...listingDetail },
1992
1986
  };
1993
- // Between-sources stop. An in-source stop sets budgetStoppedAt and leaves sourcesLeft at 0.
1994
- // Main names that next source in budgetStoppedAt; the estimate reason is recorded too.
1995
- if (budgetStop && unpricedSources > 0 && sourcesLeft > 0) {
1996
- // The stop came from estimated spend, not metered spend. Say so in the record.
1997
- result.detail = {
1998
- ...result.detail,
1999
- sourcesProcessed: sourcesRun,
2000
- sourcesLeft,
2001
- budgetStopReason: `Stopped at the spend cap of $${ctx.maxBudgetUsd.toFixed(2)} on estimated spend: ${runtime} does not report what a source costs, so each source is counted as $${turnOpts.unpricedSourceEstimateUsd.toFixed(2)}. ${sourcesRun} processed, at least ${sourcesLeft} left for the next run.`,
2002
- };
2003
- }
2004
- if (budgetStop) {
2005
- result.status = "partial";
2006
- result.error = "budget-exceeded";
2007
- }
2008
- else if (failures.length > 0) {
1987
+ if (failures.length > 0) {
2009
1988
  result.status = processedAny ? "partial" : "failed";
2010
1989
  result.error = failures[0].error;
2011
1990
  result.errorKind = errorKind ?? "other";
2012
1991
  }
2013
- if (budgetStop && failures.length > 0)
2014
- result.errorKind = errorKind ?? "other";
2015
1992
  return result;
2016
1993
  },
2017
1994
  };
@@ -57,8 +57,9 @@ export interface StepContext {
57
57
  trigger: string;
58
58
  catchUp: boolean;
59
59
  maxTurns: number;
60
- maxBudgetUsd: number;
61
- /** What a source counts as against the budget when the runtime reports no cost (core/settings/signals.yaml). */
60
+ /** Refreshes the run's company lock. A step calls it only on progress: when an item starts or finishes. Absent on a dry run. */
61
+ heartbeat?: () => void;
62
+ /** What a source adds to the estimated spend when the runtime reports no cost (core/settings/signals.yaml). */
62
63
  unpricedSourceEstimateUsd?: number;
63
64
  now: () => Date;
64
65
  spawn: SpawnSyncFn;
@@ -38,7 +38,8 @@ export interface SyncCoreReconcileDeps {
38
38
  removeStaleLegacyJournalFiles?: Parameters<typeof dropStaleLegacyJournalExport>[2];
39
39
  /** Only desktop and self-hosted machines set up a joined company. */
40
40
  machineType?: MachineType;
41
- ensureBinary: (release: string) => Promise<SyncCoreBinaryInstall>;
41
+ /** `revoked`: withdrawn releases from the server pin; an installed one is replaced even with an older release. */
42
+ ensureBinary: (release: string, revoked?: readonly string[]) => Promise<SyncCoreBinaryInstall>;
42
43
  /** A fixed release (tests). Otherwise readPin decides, then SYNC_CORE_RELEASE. */
43
44
  release?: string;
44
45
  platform?: NodeJS.Platform;
@@ -47,6 +48,11 @@ export interface SyncCoreReconcileDeps {
47
48
  readPin?: () => Promise<SyncCorePin>;
48
49
  now?: () => Date;
49
50
  log?: (line: string) => void;
51
+ /**
52
+ * Log a set of warnings identical to the last reconcile's as one pointer line. For the
53
+ * scheduled daemon run; a person running reconcile by hand sees every warning.
54
+ */
55
+ quietRepeatedWarnings?: boolean;
50
56
  }
51
57
  export interface SyncCoreReconcileResult {
52
58
  state: SyncCoreRolloutState;