@indigoai-us/hq-cli 5.345.269 → 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 (61) hide show
  1. package/CHANGELOG.md +81 -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 +4 -2
  25. package/dist/lib/hook-engine/reconcile.js +8 -0
  26. package/dist/lib/hook-engine/stable-heal.d.ts +17 -1
  27. package/dist/lib/hook-engine/stable-heal.js +42 -5
  28. package/dist/lib/hook-engine/stable-link.d.ts +70 -0
  29. package/dist/lib/hook-engine/stable-link.js +300 -0
  30. package/dist/lib/hot-channels/signals-pass.d.ts +10 -2
  31. package/dist/lib/hot-channels/signals-pass.js +13 -3
  32. package/dist/lib/install/hook-target.js +4 -1
  33. package/dist/lib/signals/engine.d.ts +0 -2
  34. package/dist/lib/signals/engine.js +12 -7
  35. package/dist/lib/signals/reply.js +35 -82
  36. package/dist/lib/signals/run-lock.d.ts +8 -0
  37. package/dist/lib/signals/run-lock.js +42 -7
  38. package/dist/lib/signals/run-record.js +2 -1
  39. package/dist/lib/signals/settings.d.ts +9 -4
  40. package/dist/lib/signals/settings.js +7 -5
  41. package/dist/lib/signals/steps/extract.d.ts +64 -17
  42. package/dist/lib/signals/steps/extract.js +175 -197
  43. package/dist/lib/signals/steps/types.d.ts +3 -2
  44. package/dist/lib/sync-core/reconcile.d.ts +7 -1
  45. package/dist/lib/sync-core/reconcile.js +105 -18
  46. package/dist/lib/sync-core/release.d.ts +52 -2
  47. package/dist/lib/sync-core/release.js +172 -11
  48. package/dist/lib/sync-core/rollout-state.d.ts +11 -0
  49. package/dist/lib/sync-core/rollout-state.js +16 -0
  50. package/dist/utils/client-health-contract.d.ts +32 -0
  51. package/dist/utils/client-health-contract.js +35 -0
  52. package/dist/utils/client-health.d.ts +43 -0
  53. package/dist/utils/client-health.js +106 -3
  54. package/dist/utils/hook-trust.js +7 -1
  55. package/dist/utils/host-registration.d.ts +12 -35
  56. package/dist/utils/host-registration.js +47 -177
  57. package/dist/utils/login-browser.d.ts +1 -0
  58. package/dist/utils/login-browser.js +31 -6
  59. package/dist/utils/spawn-detached-hidden.d.ts +66 -0
  60. package/dist/utils/spawn-detached-hidden.js +222 -0
  61. package/package.json +7 -7
@@ -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;
@@ -411,8 +416,8 @@ export function buildExtractPrompt(input) {
411
416
  // A fleet turn (hq-fleet-local complete) has no tools, like codex: the host
412
417
  // puts the item in the prompt.
413
418
  const hostRead = input.runtime === "codex" || input.runtime === "fleet";
414
- // The no-shell runtimes return commands as JSON data for the host to run.
415
- const jsonCommands = input.runtime === "grok" || hostRead;
419
+ // The no-shell runtimes return structured candidates as JSON data for the host to write.
420
+ const jsonCandidates = input.runtime === "grok" || hostRead;
416
421
  const tool = hostRead ? "terminal or any other tool" : "terminal tool";
417
422
  return [
418
423
  "You are running the ontology worker's process-source skill unattended for ONE source item.",
@@ -431,23 +436,29 @@ export function buildExtractPrompt(input) {
431
436
  : input.runtime === "grok"
432
437
  ? "- Read the item with the read_file tool. Only files in the item's channel folder are readable."
433
438
  : "- Read the item with the Read tool. Only files in the item's channel folder are readable.",
434
- `- Write candidates ONLY with: bash ${input.wrapperPath} --kind signal|entity --type <type> --body "<text>"`,
435
- "- That command already fixes the company, audience and source ref for this item. Do not pass --company, --audience, --source-ref or --body-file; it refuses them.",
436
- ...(jsonCommands
437
- ? [`- You have no ${tool}. Return JSON only: {"commands":["bash ..."]}. HQ executes validated commands after your turn. At most 8 commands; use an empty array for no candidates.`, "- Use exactly the flags above in that order; quote the body as a literal. No pipes, no &&, no ;, no substitutions, redirections or other commands outside quoted text."]
438
- : []),
439
+ ...(jsonCandidates
440
+ ? [
441
+ `- You have no ${tool}. Return JSON only: {"candidates":[{"kind":"signal"|"entity","type":"<type>","body":"<text>"}]}. HQ writes validated candidates after your turn. At most ${MAX_CANDIDATES_PER_ITEM} candidates; use an empty array for no candidates.`,
442
+ "- Do not return shell commands or flags; put the literal candidate text in \"body\". Company, audience and source ref are fixed by HQ.",
443
+ ]
444
+ : [
445
+ `- Write candidates ONLY with: bash ${input.wrapperPath} --kind signal|entity --type <type> --body "<text>"`,
446
+ "- That command already fixes the company, audience and source ref for this item. Do not pass --company, --audience, --source-ref or --body-file; it refuses them.",
447
+ ]),
439
448
  `- Signal types (exactly these): ${EXTRACT_SIGNAL_TYPES.join(", ")}.`,
440
449
  `- Entity types: ${ENTITY_TYPES.join(", ")}.`,
441
450
  "- Every signal body must end with a citation: a one-sentence quote from the item or its timestamp, for example: (cite: \"we ship Friday\") or (cite: 00:12:31).",
442
451
  "- No other command can run, and no other file can be written.",
443
- jsonCommands
444
- ? '- Return only the JSON commands object, without markdown fences. This overrides the skill instructions about executing commands.'
452
+ jsonCandidates
453
+ ? '- Return only the JSON candidates object, without markdown fences. This overrides the skill instructions about executing commands.'
445
454
  : "- When finished, reply with one line: the number of candidates written.",
446
455
  "",
447
456
  ...(input.priorSignals?.length ? [
448
457
  "Already extracted for this source; do not repeat; return `update: <id>` to amend one",
449
458
  JSON.stringify(input.priorSignals),
450
- 'For signals only, pass --body a JSON object {"title":"short title","body":"text with citation","update":"prior id (omit for new)"}. Entity bodies stay plain text.',
459
+ jsonCandidates
460
+ ? 'For signals only, pass "body" as a JSON string {"title":"short title","body":"text with citation","update":"prior id (omit for new)"}. Entity bodies stay plain text.'
461
+ : 'For signals only, pass --body a JSON object {"title":"short title","body":"text with citation","update":"prior id (omit for new)"}. Entity bodies stay plain text.',
451
462
  ] : []),
452
463
  "--- process-source skill ---",
453
464
  input.skillText.trim(),
@@ -787,6 +798,38 @@ export function validateNewCandidates(files, expectedAudienceKey, scope, priorSi
787
798
  }
788
799
  return { kept, rejected, foreign, ...(priorSignals.length ? { updated, skipped: skipped + priorSignals.length - matchedPriorIds.size } : {}) };
789
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
+ }
790
833
  function classifyFailure(text, fallback) {
791
834
  if (CLAUDE_LOGGED_OUT_RE.test(text))
792
835
  return { error: "coding tool is not logged in", errorKind: "signed-out" };
@@ -897,57 +940,33 @@ export function grokSandboxProfile(scope, envPath) {
897
940
  export function grokAllowRules(channelDir) {
898
941
  return [`Read(${channelDir}/**)`];
899
942
  }
900
- /** Parse literal arguments only. No shell ever interprets model output. */
901
- export function grokCandidateArgv(command, wrapperPath) {
902
- const words = [];
903
- let i = 0;
904
- while (i < command.length) {
905
- while (command[i] === " " || command[i] === "\t")
906
- i++;
907
- if (i === command.length)
908
- break;
909
- let word = "";
910
- while (i < command.length && command[i] !== " " && command[i] !== "\t") {
911
- const ch = command[i++];
912
- if (ch === "'" || ch === '"') {
913
- const quote = ch;
914
- let closed = false;
915
- while (i < command.length) {
916
- const c = command[i++];
917
- if (c === quote) {
918
- closed = true;
919
- break;
920
- }
921
- if (quote === '"' && (c === "$" || c === "`"))
922
- return null;
923
- if (quote === '"' && c === "\\") {
924
- const next = command[i++];
925
- if (next !== '"' && next !== "\\")
926
- return null;
927
- word += next;
928
- }
929
- else
930
- word += c;
931
- }
932
- if (!closed)
933
- return null;
934
- }
935
- else if (ch === "\\" && command[i] === "'") {
936
- word += command[i++];
937
- }
938
- else if (/^[a-zA-Z0-9_./:-]$/.test(ch))
939
- word += ch;
940
- else
941
- return null;
942
- }
943
- words.push(word);
943
+ const SIGNAL_TYPE_SET = new Set(EXTRACT_SIGNAL_TYPES);
944
+ const ENTITY_TYPE_SET = new Set(ENTITY_TYPES);
945
+ const MAX_CANDIDATES_PER_ITEM = 8;
946
+ /**
947
+ * Validate one structured candidate object and build the fixed 7-element argv
948
+ * for the pinned candidate wrapper. No shell ever interprets model output, and
949
+ * the model can never change the executable, wrapper path, or flag shape.
950
+ */
951
+ export function structuredCandidateArgv(candidate, wrapperPath) {
952
+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) {
953
+ return { ok: false, reason: "candidate must be a JSON object" };
944
954
  }
945
- if (words.length !== 8 || words[0] !== "bash" || words[1] !== wrapperPath ||
946
- words[2] !== "--kind" || !["signal", "entity"].includes(words[3]) ||
947
- words[4] !== "--type" || !/^[a-z][a-z0-9_-]*$/.test(words[5]) ||
948
- words[6] !== "--body" || !words[7] || words.some((w) => w.includes("\0")))
949
- return null;
950
- return words.slice(1);
955
+ const obj = candidate;
956
+ const kind = obj.kind;
957
+ if (kind !== "signal" && kind !== "entity") {
958
+ return { ok: false, reason: 'invalid kind: must be "signal" or "entity"' };
959
+ }
960
+ const type = obj.type;
961
+ const allowedTypes = kind === "signal" ? SIGNAL_TYPE_SET : ENTITY_TYPE_SET;
962
+ if (typeof type !== "string" || !allowedTypes.has(type)) {
963
+ return { ok: false, reason: `invalid ${kind} type` };
964
+ }
965
+ const body = obj.body;
966
+ if (typeof body !== "string" || body.length === 0 || body.includes("\0")) {
967
+ return { ok: false, reason: "body must be a non-empty string without NUL bytes" };
968
+ }
969
+ return { ok: true, argv: [wrapperPath, "--kind", kind, "--type", type, "--body", body] };
951
970
  }
952
971
  /** True when the writer on disk is still the script this turn generated. */
953
972
  function wrapperMatchesGenerated(wrapperPath, expected) {
@@ -959,10 +978,11 @@ function wrapperMatchesGenerated(wrapperPath, expected) {
959
978
  }
960
979
  }
961
980
  /**
962
- * Validate the whole batch before writing. Only the host executes the pinned
963
- * writer. When `expectedWrapper` is set, the file is compared to that text
964
- * immediately before each exec. Strict can write the turn directory, so a
965
- * writer that no longer matches is not run.
981
+ * Validate structured candidates and execute each valid one through the pinned
982
+ * wrapper using a fixed argv array (never a shell command string). A malformed
983
+ * or invalid candidate drops only itself, records why, and keeps the rest of
984
+ * the item's valid candidates. When `expectedWrapper` is set, the file on disk
985
+ * is compared to that text immediately before each exec.
966
986
  */
967
987
  export function executeGrokCandidates(text, wrapperPath, spawn, opts, expectedWrapper, runtime = "grok") {
968
988
  let data;
@@ -970,27 +990,33 @@ export function executeGrokCandidates(text, wrapperPath, spawn, opts, expectedWr
970
990
  data = JSON.parse(text);
971
991
  }
972
992
  catch {
973
- return `${runtime} must return a JSON commands array`;
993
+ return { error: `${runtime} must return a JSON candidates object`, dropped: [] };
994
+ }
995
+ if (!data || typeof data !== "object" || Array.isArray(data) || !("candidates" in data) || !Array.isArray(data.candidates)) {
996
+ return { error: `${runtime} must return a JSON candidates array`, dropped: [] };
974
997
  }
975
- if (!data || typeof data !== "object" || !("commands" in data) || !Array.isArray(data.commands) || data.commands.length > 8) {
976
- return `${runtime} must return at most 8 candidate commands`;
998
+ if (data.candidates.length > MAX_CANDIDATES_PER_ITEM) {
999
+ return { error: `${runtime} must return at most ${MAX_CANDIDATES_PER_ITEM} candidates`, dropped: [] };
977
1000
  }
978
1001
  const batch = [];
979
- for (const command of data.commands) {
980
- const argv = typeof command === "string" ? grokCandidateArgv(command, wrapperPath) : null;
981
- if (!argv)
982
- return "refused: command is not the pinned candidate wrapper";
983
- batch.push(argv);
1002
+ const dropped = [];
1003
+ for (let index = 0; index < data.candidates.length; index++) {
1004
+ const parsed = structuredCandidateArgv(data.candidates[index], wrapperPath);
1005
+ if (!parsed.ok) {
1006
+ dropped.push({ index, reason: parsed.reason });
1007
+ continue;
1008
+ }
1009
+ batch.push(parsed.argv);
984
1010
  }
985
1011
  for (const argv of batch) {
986
1012
  if (expectedWrapper !== undefined && !wrapperMatchesGenerated(wrapperPath, expectedWrapper)) {
987
- return "pinned candidate writer does not match the generated script";
1013
+ return { error: "pinned candidate writer does not match the generated script", dropped };
988
1014
  }
989
1015
  const result = spawn("/bin/bash", argv, opts);
990
1016
  if (result.error || result.status !== 0)
991
- return "pinned candidate writer failed";
1017
+ return { error: "pinned candidate writer failed", dropped };
992
1018
  }
993
- return undefined;
1019
+ return { dropped };
994
1020
  }
995
1021
  /**
996
1022
  * Read denies for the grok login. Grok matches a `~` tool path literally and
@@ -1164,7 +1190,7 @@ function toolAvailability(ctx, bin, statusArgs, parse) {
1164
1190
  }
1165
1191
  return { installed: true, signedIn: parse({ code: res.status, signal: null, stdout: res.stdout, stderr: res.stderr }) };
1166
1192
  }
1167
- export function claudeTurnArgs(prompt, scope, maxTurns, budgetUsd) {
1193
+ export function claudeTurnArgs(prompt, scope, maxTurns) {
1168
1194
  return [
1169
1195
  "-p",
1170
1196
  prompt,
@@ -1185,8 +1211,6 @@ export function claudeTurnArgs(prompt, scope, maxTurns, budgetUsd) {
1185
1211
  "--no-session-persistence",
1186
1212
  "--max-turns",
1187
1213
  String(maxTurns),
1188
- "--max-budget-usd",
1189
- budgetUsd.toFixed(4),
1190
1214
  "--add-dir",
1191
1215
  scope.channelDir,
1192
1216
  "--allowedTools",
@@ -1282,10 +1306,10 @@ function stripFence(text) {
1282
1306
  const m = /^```(?:json)?\s*\n([\s\S]*?)\n```\s*$/.exec(text.trim());
1283
1307
  return m ? m[1] : text;
1284
1308
  }
1285
- function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
1309
+ function runTurn(ctx, runtime, prompt, scope, opts) {
1286
1310
  let cwd = scope.turnDir;
1287
1311
  let cmd = runtime === "claude" ? opts.claudeBin : runtime === "grok" ? opts.grokBin : opts.codexBin;
1288
- let args = runtime === "claude" ? claudeTurnArgs(prompt, scope, ctx.maxTurns, budgetUsd) : [];
1312
+ let args = runtime === "claude" ? claudeTurnArgs(prompt, scope, ctx.maxTurns) : [];
1289
1313
  let env = runtime === "claude" ? claudeSignalsEnv(process.env) : { ...process.env, HQ_ROOT: ctx.hqRoot };
1290
1314
  let grokHome;
1291
1315
  let codexRoot;
@@ -1358,15 +1382,15 @@ function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
1358
1382
  fs.rmSync(codexRoot, { recursive: true, force: true });
1359
1383
  }
1360
1384
  const parsed = parseTurnOutput(res.stdout);
1361
- // codex never reports a cost and grok may not. Charge the estimate so the
1362
- // run budget still stops the run. claude is capped by its own --max-budget-usd.
1363
- // A grok turn that started and then failed or timed out is charged too, since
1364
- // it may have used the model; only a runtime that could not start is free. A
1365
- // 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.
1366
1390
  const cost = runtime === "claude" || parsed.costReported ? { costUsd: parsed.costUsd } : { costUsd: opts.unpricedSourceEstimateUsd, costEstimated: true };
1367
- // A codex turn that fails, times out or is refused by the lockdown costs
1368
- // nothing against the run budget (owner decision, 2026-11-16): only a codex
1369
- // 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.
1370
1394
  const failCost = runtime === "codex" ? { costUsd: 0 } : cost;
1371
1395
  const all = `${res.stderr}\n${res.stdout}`;
1372
1396
  if (res.error) {
@@ -1375,12 +1399,11 @@ function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
1375
1399
  return { ok: false, error: `${runtime} timed out after ${opts.turnTimeoutMs}ms`, errorKind: "transient", turns: parsed.turns, ...failCost };
1376
1400
  return { ok: false, error: `${runtime} could not start: ${res.error.message}`.slice(0, 300), errorKind: "other", turns: 0, costUsd: 0 };
1377
1401
  }
1378
- // The runtime stopped the turn at its own budget cap (claude: result subtype
1379
- // error_max_budget_usd, with a non-zero exit). That is the run's budget stop,
1380
- // not a failed item.
1381
- if (runtime === "claude" && parsed.result?.subtype === CLAUDE_BUDGET_STOP_SUBTYPE) {
1382
- return { ok: false, error: "budget-exceeded", budgetExceeded: true, turns: parsed.turns, ...cost };
1383
- }
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 };
1384
1407
  if (res.status !== 0) {
1385
1408
  const c = classifyFailure(all, `${runtime} exited ${String(res.status)}: ${res.stderr.trim().slice(0, 200)}`);
1386
1409
  return { ok: false, ...c, turns: parsed.turns, ...failCost };
@@ -1395,15 +1418,18 @@ function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
1395
1418
  const c = classifyFailure(detail, `${runtime} turn failed: ${detail.slice(0, 300) || "error result"}`);
1396
1419
  return { ok: false, ...c, turns: parsed.turns, ...failCost };
1397
1420
  }
1421
+ let droppedCandidates;
1398
1422
  if (runtime === "grok") {
1399
1423
  if (scope.wrapperBody === undefined) {
1400
1424
  return { ok: false, error: "pinned candidate writer is missing", errorKind: "other", turns: parsed.turns, ...failCost };
1401
1425
  }
1402
- const error = executeGrokCandidates(String(parsed.result.result ?? ""), scope.wrapperPath, ctx.spawn, {
1426
+ const exec = executeGrokCandidates(stripFence(String(parsed.result.result ?? "")), scope.wrapperPath, ctx.spawn, {
1403
1427
  cwd, env: grokTurnEnv({ ...process.env, HQ_ROOT: ctx.hqRoot }), timeoutMs: SCRIPT_TIMEOUT_MS,
1404
1428
  }, scope.wrapperBody);
1405
- if (error)
1406
- return { ok: false, error, errorKind: "other", turns: parsed.turns, ...failCost };
1429
+ if (exec.dropped.length)
1430
+ droppedCandidates = exec.dropped;
1431
+ if (exec.error)
1432
+ return { ok: false, error: exec.error, errorKind: "other", turns: parsed.turns, ...(droppedCandidates ? { droppedCandidates } : {}), ...failCost };
1407
1433
  }
1408
1434
  if (runtime === "codex") {
1409
1435
  const used = codexToolItem(res.stdout);
@@ -1414,13 +1440,15 @@ function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
1414
1440
  }
1415
1441
  if (codexReplyText === null)
1416
1442
  return { ok: false, error: "codex printed no reply", errorKind: "other", turns: parsed.turns, ...failCost };
1417
- const error = executeGrokCandidates(stripFence(codexReplyText), scope.wrapperPath, ctx.spawn, {
1443
+ const exec = executeGrokCandidates(stripFence(codexReplyText), scope.wrapperPath, ctx.spawn, {
1418
1444
  cwd: scope.turnDir, env: grokTurnEnv({ ...process.env, HQ_ROOT: ctx.hqRoot }), timeoutMs: SCRIPT_TIMEOUT_MS,
1419
1445
  }, scope.wrapperBody, "codex");
1420
- if (error)
1421
- return { ok: false, error, errorKind: "other", turns: parsed.turns, ...failCost };
1446
+ if (exec.dropped.length)
1447
+ droppedCandidates = exec.dropped;
1448
+ if (exec.error)
1449
+ return { ok: false, error: exec.error, errorKind: "other", turns: parsed.turns, ...(droppedCandidates ? { droppedCandidates } : {}), ...failCost };
1422
1450
  }
1423
- return { ok: true, turns: parsed.turns, ...cost };
1451
+ return { ok: true, turns: parsed.turns, ...(droppedCandidates ? { droppedCandidates } : {}), ...cost };
1424
1452
  }
1425
1453
  /** Spawn error codes that mean the hq-fleet-local helper never started. */
1426
1454
  const FLEET_HELPER_NOT_STARTED = new Set(["ENOENT", "EACCES", "ENOTDIR", "EPERM", "ENOEXEC"]);
@@ -1487,17 +1515,20 @@ async function runFleetTurn(ctx, target, prompt, scope, opts) {
1487
1515
  if (result.kind === "error") {
1488
1516
  const { errorKind, reachedModel } = fleetExtractFailure(result.code);
1489
1517
  const detail = result.code === "timeout" ? ` after ${opts.turnTimeoutMs}ms` : "";
1490
- 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 } : {}) };
1491
1521
  }
1492
1522
  if (scope.wrapperBody === undefined) {
1493
1523
  return { ok: false, error: "pinned candidate writer is missing", errorKind: "other", turns: 1, ...charged };
1494
1524
  }
1495
- const error = executeGrokCandidates(stripFence(result.text), scope.wrapperPath, ctx.spawn, {
1525
+ const exec = executeGrokCandidates(stripFence(result.text), scope.wrapperPath, ctx.spawn, {
1496
1526
  cwd: scope.turnDir, env: grokTurnEnv({ ...process.env, HQ_ROOT: ctx.hqRoot }), timeoutMs: SCRIPT_TIMEOUT_MS,
1497
1527
  }, scope.wrapperBody, "claude");
1498
- if (error)
1499
- return { ok: false, error, errorKind: "other", turns: 1, ...charged };
1500
- return { ok: true, turns: 1, ...charged };
1528
+ const dropped = exec.dropped.length ? { droppedCandidates: exec.dropped } : {};
1529
+ if (exec.error)
1530
+ return { ok: false, error: exec.error, errorKind: "other", turns: 1, ...dropped, ...charged };
1531
+ return { ok: true, turns: 1, ...dropped, ...charged };
1501
1532
  }
1502
1533
  /**
1503
1534
  * The Executive bot's HQ Fleet target (fleetCompleteTarget, the resolution
@@ -1567,20 +1598,18 @@ export function codexHomeInstructions(codexHome) {
1567
1598
  return found;
1568
1599
  }
1569
1600
  export async function extractPartialDocument(ctx, doc, prior) {
1570
- if (ctx.maxBudgetUsd <= 0)
1571
- return { status: "partial", error: "budget-exceeded", itemsIn: 1, itemsOut: 0, modelTurns: 0, estimatedSpendUsd: 0 };
1572
1601
  const prompt = buildExtractPrompt({ documentOverride: doc, priorSignals: prior, skillText: "", company: ctx.company, channel: "", item: { file: "" }, itemPath: "", wrapperPath: "" });
1573
1602
  // Same no-tool JSON extractor as the hot-channel pass. Run in a blank cwd so
1574
1603
  // project instructions cannot change the response or grant filesystem access.
1575
1604
  const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "hq-incremental-"));
1576
1605
  let run;
1577
1606
  try {
1578
- 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 });
1579
1608
  }
1580
1609
  finally {
1581
1610
  fs.rmSync(cwd, { recursive: true, force: true });
1582
1611
  }
1583
- // 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.
1584
1613
  const envelope = (() => {
1585
1614
  if (run.error)
1586
1615
  return null;
@@ -1593,18 +1622,6 @@ export async function extractPartialDocument(ctx, doc, prior) {
1593
1622
  return null;
1594
1623
  }
1595
1624
  })();
1596
- // claude stopped the turn at --max-budget-usd. That is a budget stop, not a
1597
- // login problem; the caller leaves the cursor where it was.
1598
- if (envelope?.subtype === CLAUDE_BUDGET_STOP_SUBTYPE) {
1599
- return {
1600
- status: "partial",
1601
- error: "budget-exceeded",
1602
- itemsIn: 1,
1603
- itemsOut: 0,
1604
- modelTurns: typeof envelope.num_turns === "number" ? envelope.num_turns : 1,
1605
- estimatedSpendUsd: typeof envelope.total_cost_usd === "number" ? envelope.total_cost_usd : 0,
1606
- };
1607
- }
1608
1625
  if (run.error || run.status !== 0)
1609
1626
  throw new Error("Signal extraction failed; the cursor was not advanced. Check the coding-tool login and retry.");
1610
1627
  // parseClaudeSignals throws its own error for output that is not a usable envelope.
@@ -1708,26 +1725,16 @@ export function createExtractStep(options = {}) {
1708
1725
  let itemsOut = 0;
1709
1726
  let modelTurns = 0;
1710
1727
  let spent = 0;
1711
- let lastCost = 0;
1712
1728
  let rejected = 0;
1713
1729
  let updated = 0;
1714
1730
  let skipped = 0;
1715
1731
  let processedAny = false;
1716
- let budgetStop = false;
1717
1732
  /** Sources whose runtime reported no cost; their spend is the per-source estimate. */
1718
1733
  let unpricedSources = 0;
1719
- /** Sources a model turn ran for, and listed sources not started when the budget stopped the run. */
1720
- let sourcesRun = 0;
1721
- let sourcesLeft = 0;
1722
- /**
1723
- * The first source a budget stop left unfinished, which the next run takes first: the source whose
1724
- * turn the runtime stopped at its cap, or, when the run stops between sources, the next source it
1725
- * did not start. Named in the record so a source that never fits is findable.
1726
- */
1727
- let budgetStoppedAt;
1728
1734
  /** Signal candidates with no citation marker, and the sources they came from. Counted, not rejected. */
1729
1735
  let uncitedCandidates = 0;
1730
1736
  const uncitedSources = [];
1737
+ const droppedCandidates = [];
1731
1738
  let errorKind;
1732
1739
  const failures = [
1733
1740
  ...unreadable,
@@ -1741,6 +1748,8 @@ export function createExtractStep(options = {}) {
1741
1748
  else if (unrunRedo.length > 0)
1742
1749
  errorKind = "other";
1743
1750
  const skippedItems = [];
1751
+ /** The source whose turn the provider refused for a usage or rate limit; the run stopped there. */
1752
+ let providerLimitStoppedAt;
1744
1753
  const sourcesReal = fs.realpathSync(path.join(ctx.hqRoot, "companies", ctx.company, "sources"));
1745
1754
  outer: for (const ch of channels) {
1746
1755
  const base = ["--company", ctx.company, "--channel", ch.channel, ...(ch.force ? ["--force"] : [])];
@@ -1820,17 +1829,8 @@ export function createExtractStep(options = {}) {
1820
1829
  errorKind = "other";
1821
1830
  continue;
1822
1831
  }
1823
- const remaining = ctx.maxBudgetUsd - spent;
1824
- // BUDGET_EPSILON_USD absorbs float drift: nineteen 0.10 charges sum to
1825
- // just over 1.90, which must not stop the twentieth source at 2.00.
1826
- if (spent > 0 && (spent >= ctx.maxBudgetUsd - BUDGET_EPSILON_USD || remaining < lastCost - BUDGET_EPSILON_USD)) {
1827
- // This source is not started and not marked done; the next run takes it first.
1828
- budgetStoppedAt = item.file;
1829
- budgetStop = true;
1830
- // This source and the ones listed after it in this channel. Later channels are not listed yet.
1831
- sourcesLeft = items.slice(items.indexOf(item)).filter((i) => !i.skip).length;
1832
- break outer;
1833
- }
1832
+ // A source starts: progress, so the run's lock is refreshed. The process blocks on each turn.
1833
+ ctx.heartbeat?.();
1834
1834
  let sourceRef = `${ch.channel}:${path.basename(item.file)}`;
1835
1835
  const sourceFile = fs.realpathSync(path.join(channelDir, path.basename(item.file)));
1836
1836
  if (path.dirname(sourceFile) !== channelDir)
@@ -1887,7 +1887,7 @@ export function createExtractStep(options = {}) {
1887
1887
  fleetTurn = fleetResult;
1888
1888
  }
1889
1889
  }
1890
- turn = fleetTurn ?? runTurn(ctx, runtime, promptFor(runtime), scope, Math.max(0, remaining), turnOpts);
1890
+ turn = fleetTurn ?? runTurn(ctx, runtime, promptFor(runtime), scope, turnOpts);
1891
1891
  if (tooLargeFor !== undefined && !turn.ok && turn.errorKind === "signed-out") {
1892
1892
  // The personal claude login is signed out, but the run is on the
1893
1893
  // bot's login, which still works: only this oversized item fails,
@@ -1898,23 +1898,23 @@ export function createExtractStep(options = {}) {
1898
1898
  finally {
1899
1899
  fs.rmSync(turnDir, { recursive: true, force: true });
1900
1900
  }
1901
+ // The source's turn finished, whatever its result: progress again.
1902
+ ctx.heartbeat?.();
1901
1903
  modelTurns += turn.turns;
1902
1904
  spent += turn.costUsd;
1903
- lastCost = turn.costUsd;
1904
1905
  if (turn.costEstimated)
1905
1906
  unpricedSources += 1;
1906
- sourcesRun += 1;
1907
+ if (turn.droppedCandidates?.length) {
1908
+ for (const d of turn.droppedCandidates) {
1909
+ droppedCandidates.push({ file: item.file, index: d.index, reason: d.reason });
1910
+ }
1911
+ }
1907
1912
  const created = [...allCandidateFiles(ctx.hqRoot)].filter((f) => !before.has(f));
1908
- if (!turn.ok && (priorSignals.length || turn.budgetExceeded)) {
1913
+ if (!turn.ok && priorSignals.length) {
1909
1914
  // Failed model turns must not leave structured duplicates for garden.
1910
- // A budget-stopped source runs again next time and would write its
1911
- // candidates a second time, so the stopped turn's are removed too:
1912
- // its signal candidates and its entity candidates. A failed turn
1913
- // with prior signals keeps the scope it had, signal candidates only.
1914
- const stores = turn.budgetExceeded ? ["signals", "ontology"] : ["signals"];
1915
1915
  for (const file of created) {
1916
1916
  const rel = realRelPath(ctx.hqRoot, file);
1917
- if (!rel || !stores.some((store) => rel.startsWith(`companies/${ctx.company}/${store}/_candidates/`)))
1917
+ if (!rel || !rel.startsWith(`companies/${ctx.company}/signals/_candidates/`))
1918
1918
  continue;
1919
1919
  let text;
1920
1920
  try {
@@ -1947,18 +1947,13 @@ export function createExtractStep(options = {}) {
1947
1947
  failures.push({ file: item.file, error: `candidate written outside ${ctx.company} (deleted): ${v.foreign.join(", ")}`.slice(0, 300) });
1948
1948
  if (!errorKind)
1949
1949
  errorKind = "other";
1950
- if (turn.budgetExceeded) {
1951
- // The breach is recorded above; the runtime's budget stop still ends the run.
1952
- budgetStoppedAt = item.file;
1953
- budgetStop = true;
1954
- break outer;
1955
- }
1956
1950
  continue;
1957
1951
  }
1958
- if (!turn.ok && turn.budgetExceeded) {
1959
- // The item is not marked done, so the next run takes it again.
1960
- budgetStoppedAt = item.file;
1961
- 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;
1962
1957
  break outer;
1963
1958
  }
1964
1959
  if (!turn.ok) {
@@ -1987,30 +1982,13 @@ export function createExtractStep(options = {}) {
1987
1982
  ...(failures.length ? { failures } : {}),
1988
1983
  ...(skippedItems.length ? { skippedItems } : {}),
1989
1984
  ...(rejected ? { rejectedCandidates: rejected } : {}),
1990
- 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 } : {}), ...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 },
1991
1986
  };
1992
- // Between-sources stop. An in-source stop sets budgetStoppedAt and leaves sourcesLeft at 0.
1993
- // Main names that next source in budgetStoppedAt; the estimate reason is recorded too.
1994
- if (budgetStop && unpricedSources > 0 && sourcesLeft > 0) {
1995
- // The stop came from estimated spend, not metered spend. Say so in the record.
1996
- result.detail = {
1997
- ...result.detail,
1998
- sourcesProcessed: sourcesRun,
1999
- sourcesLeft,
2000
- 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.`,
2001
- };
2002
- }
2003
- if (budgetStop) {
2004
- result.status = "partial";
2005
- result.error = "budget-exceeded";
2006
- }
2007
- else if (failures.length > 0) {
1987
+ if (failures.length > 0) {
2008
1988
  result.status = processedAny ? "partial" : "failed";
2009
1989
  result.error = failures[0].error;
2010
1990
  result.errorKind = errorKind ?? "other";
2011
1991
  }
2012
- if (budgetStop && failures.length > 0)
2013
- result.errorKind = errorKind ?? "other";
2014
1992
  return result;
2015
1993
  },
2016
1994
  };