@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
@@ -1815,6 +1815,11 @@ export function uncoveredHooks(root, host, event, covers, env = process.env) {
1815
1815
  if (hold)
1816
1816
  missing.push(`(native SessionStart compatibility: ${hold})`);
1817
1817
  }
1818
+ if (event === 'SessionStart' || event === 'UserPromptSubmit' || event === 'SessionEnd') {
1819
+ const hold = workMeshShimsHold(root, event, covered);
1820
+ if (hold)
1821
+ missing.push(`(native ${event} compatibility: ${hold})`);
1822
+ }
1818
1823
  if (host === 'fleet-local' && event === 'PreToolUse' && covered.includes('fleet-local-adapter:PreToolUse')) {
1819
1824
  const hold = fleetLocalPreToolUseHold(root);
1820
1825
  if (hold)
@@ -1921,7 +1926,7 @@ export const SESSION_START_PINS = [
1921
1926
  ['core/scripts/hqd-hook-flag-cache-lib.sh', ['061d264460408e9eaf43fdf0fdde662c906a9a7dacb4e7a591e684bca28c138a']],
1922
1927
  ['core/scripts/hq-session.sh', ['db701162f71b53fd2188974d2f46c58250593dde1252d65b36e6d02b9a765fe7', '02a37c5dbf4fb5af27cc64d0f271121e990758b757a479f60e9ce099f4d65ded', 'd4d4aef60ff8b095e3abcc817598f376d3c2de8d59758c3ed6dd40d4aa4b11fb']],
1923
1928
  ['core/scripts/lib/session-id.sh', ['2ebbc50893c7c601a111b9e8f9945afeac88f552d7caeec09c4096f4c27a833d', 'd6a04155571ec53edd853878cebaba5a5bab93801a73e356499440c1cd009c71']],
1924
- ['core/scripts/lib/session-scope-capability.sh', ['388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead', '498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38']],
1929
+ ['core/scripts/lib/session-scope-capability.sh', ['388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead', '498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38', 'cceddf40b3ec932cc4c83b31d72d9462f5a09be32246d57299591f4b75bdcd5a']],
1925
1930
  ['core/scripts/resolve-company.sh', ['00d6fa069f574a86087c77daa44887a2617446d4300d5daebecc9bfb5d81abe7']],
1926
1931
  ];
1927
1932
  /**
@@ -1947,6 +1952,94 @@ export function sessionStartHold(root) {
1947
1952
  }
1948
1953
  return null;
1949
1954
  }
1955
+ const WORK_MESH_REGISTER_BODY_PIN = {
1956
+ relative: 'core/hooks/work-mesh-register.sh',
1957
+ accepted: [
1958
+ 'e02a0f24da2bc094c0ee78ee68b8f35659e30f62e38bf386f2f833f94d580e57',
1959
+ '5cbc16337f2e8dbd0f2c5322edc2be654d8c24887ccb435ad4e22a538483d685',
1960
+ ],
1961
+ missing: 'allowed',
1962
+ };
1963
+ const WORK_MESH_CLOSE_BODY_PIN = {
1964
+ relative: 'core/hooks/work-mesh-close.sh',
1965
+ accepted: [
1966
+ '8203c5f18b296a392d843ba259e081de6b854932abb215e30cd068ed3c17c898',
1967
+ 'f8a3b57b0df638968a1750d1c98dccdb9f37106a7027dfd8aebf4ae5243e4456',
1968
+ ],
1969
+ missing: 'allowed',
1970
+ };
1971
+ const WORK_MESH_GROUND_BODY_PIN = {
1972
+ relative: 'core/hooks/work-mesh-ground.sh',
1973
+ accepted: [
1974
+ '22000e66f7f133f8ccda9556d53f61b6c861caf4169f78f142cd70d5e034eae0',
1975
+ 'eb4ab208156399da64d925564b87191d3685d3ede4925e6b7f4e41467fdcd645',
1976
+ ],
1977
+ missing: 'allowed',
1978
+ };
1979
+ export const WORK_MESH_SESSION_START_PINS = [
1980
+ {
1981
+ shim: {
1982
+ relative: 'core/hooks/SessionStart/35-work-mesh-register.sh',
1983
+ accepted: ['89f53b15099c7b01de6c5eeb35a7d40aa5075e8c4ac8cf9a6e511799cb3b57b9'],
1984
+ },
1985
+ body: WORK_MESH_REGISTER_BODY_PIN,
1986
+ },
1987
+ {
1988
+ shim: {
1989
+ relative: 'core/hooks/SessionStart/36-work-mesh-sweep.sh',
1990
+ accepted: ['870931f665f97cfa957806c2ba5466eb3ee2922a32c3c331a7c6fe447b60fc56'],
1991
+ },
1992
+ body: WORK_MESH_CLOSE_BODY_PIN,
1993
+ },
1994
+ ];
1995
+ export const WORK_MESH_USER_PROMPT_SUBMIT_PINS = [
1996
+ {
1997
+ shim: {
1998
+ relative: 'core/hooks/UserPromptSubmit/35-work-mesh-register.sh',
1999
+ accepted: ['89f53b15099c7b01de6c5eeb35a7d40aa5075e8c4ac8cf9a6e511799cb3b57b9'],
2000
+ },
2001
+ body: WORK_MESH_REGISTER_BODY_PIN,
2002
+ },
2003
+ {
2004
+ shim: {
2005
+ relative: 'core/hooks/UserPromptSubmit/70-work-mesh-ground.sh',
2006
+ accepted: ['d07328e4e5d8d3572e91321d209bf4c712317b1c6616ddd9084d3e544baa2e88'],
2007
+ },
2008
+ body: WORK_MESH_GROUND_BODY_PIN,
2009
+ },
2010
+ ];
2011
+ export const WORK_MESH_SESSION_END_PINS = [
2012
+ {
2013
+ shim: {
2014
+ relative: 'core/hooks/SessionEnd/35-work-mesh-close.sh',
2015
+ accepted: ['878d8e77bf67f3ad0cb9754ff625a001083213751ef2832c6071288e0b9f5bbe'],
2016
+ },
2017
+ body: WORK_MESH_CLOSE_BODY_PIN,
2018
+ },
2019
+ ];
2020
+ /**
2021
+ * Why `event` (`SessionStart`, `UserPromptSubmit`, or `SessionEnd`) must stay on the shell
2022
+ * registration for a present legacy Work Mesh shim in `root`: the shim file exists on disk, is
2023
+ * claimed in `covered`, and either the shim or its `core/hooks/work-mesh-*.sh` body is not a
2024
+ * pinned revision (`pinnedFilesHold`). Missing shims are not held.
2025
+ */
2026
+ export function workMeshShimsHold(root, event, covered) {
2027
+ const entries = event === 'SessionStart'
2028
+ ? WORK_MESH_SESSION_START_PINS
2029
+ : event === 'UserPromptSubmit'
2030
+ ? WORK_MESH_USER_PROMPT_SUBMIT_PINS
2031
+ : WORK_MESH_SESSION_END_PINS;
2032
+ for (const entry of entries) {
2033
+ if (!covered.includes(entry.shim.relative))
2034
+ continue;
2035
+ if (!regularFile(path.join(root, entry.shim.relative)))
2036
+ continue;
2037
+ const hold = pinnedFilesHold(root, event, [entry.shim, entry.body]);
2038
+ if (hold)
2039
+ return hold;
2040
+ }
2041
+ return null;
2042
+ }
1950
2043
  /**
1951
2044
  * The script revisions the native SessionStart `migrate-policy-triggers` port rebuilds
1952
2045
  * (`crates/hq-hook/src/session_start_ss1/migrate_triggers.rs`: `SCRIPT_SHA256`,
@@ -2023,7 +2116,7 @@ export const FLEET_LOCAL_PRE_TOOL_USE_PINS = [
2023
2116
  ],
2024
2117
  missing: 'allowed',
2025
2118
  },
2026
- { relative: 'core/scripts/lib/session-scope-capability.sh', accepted: ['388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead', '498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38'], missing: 'allowed' },
2119
+ { relative: 'core/scripts/lib/session-scope-capability.sh', accepted: ['388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead', '498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38', 'cceddf40b3ec932cc4c83b31d72d9462f5a09be32246d57299591f4b75bdcd5a'], missing: 'allowed' },
2027
2120
  ];
2028
2121
  /**
2029
2122
  * Why fleet-local PreToolUse must stay on the shell adapter in `root`: a present file of
@@ -2263,7 +2356,7 @@ export const PRE_TOOL_USE_DISPATCHER_PINS = [
2263
2356
  { relative: 'core/scripts/lib/epochrealtime.sh', accepted: ['4c9205520dba31533c95eea145f6068ba626885c342c2aa1f232a7237d046cdf'] },
2264
2357
  { relative: 'core/scripts/lib/perl-child-locale.sh', accepted: ['18e6b9d0e22874eea00ecc868b4dcfebbc3bb42434d8d0c81b20baec1194df2e'] },
2265
2358
  { relative: 'core/scripts/lib/session-id.sh', accepted: ['2ebbc50893c7c601a111b9e8f9945afeac88f552d7caeec09c4096f4c27a833d', 'd6a04155571ec53edd853878cebaba5a5bab93801a73e356499440c1cd009c71'] },
2266
- { relative: 'core/scripts/lib/session-scope-capability.sh', accepted: ['388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead', '498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38'] },
2359
+ { relative: 'core/scripts/lib/session-scope-capability.sh', accepted: ['388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead', '498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38', 'cceddf40b3ec932cc4c83b31d72d9462f5a09be32246d57299591f4b75bdcd5a'] },
2267
2360
  { relative: 'core/scripts/resolve-hq-root.sh', accepted: ['188e99c7c60bc9909290a666d6f3b93387ae6cf68f2eeb41fd24c2dea62a5240'] },
2268
2361
  ];
2269
2362
  /**
@@ -2684,7 +2777,7 @@ export const PROMPT_COMPANY_BIND_PINS = [
2684
2777
  },
2685
2778
  { relative: 'core/scripts/hq-session.sh', accepted: ['db701162f71b53fd2188974d2f46c58250593dde1252d65b36e6d02b9a765fe7', '02a37c5dbf4fb5af27cc64d0f271121e990758b757a479f60e9ce099f4d65ded', 'd4d4aef60ff8b095e3abcc817598f376d3c2de8d59758c3ed6dd40d4aa4b11fb'] },
2686
2779
  { relative: 'core/scripts/lib/session-id.sh', accepted: ['2ebbc50893c7c601a111b9e8f9945afeac88f552d7caeec09c4096f4c27a833d', 'd6a04155571ec53edd853878cebaba5a5bab93801a73e356499440c1cd009c71'] },
2687
- { relative: 'core/scripts/lib/session-scope-capability.sh', accepted: ['388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead', '498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38'] },
2780
+ { relative: 'core/scripts/lib/session-scope-capability.sh', accepted: ['388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead', '498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38', 'cceddf40b3ec932cc4c83b31d72d9462f5a09be32246d57299591f4b75bdcd5a'] },
2688
2781
  ];
2689
2782
  /**
2690
2783
  * Why UserPromptSubmit must stay on the shell registration in `root`: the native
@@ -2787,7 +2880,7 @@ export function postToolUseAdapterHold(root, host) {
2787
2880
  return null;
2788
2881
  }
2789
2882
  /** The session-scope-capability.sh master-hook's Task-agent pin is modelled on (crates/hq-hook/src/scope/session.rs `SUBAGENT_PIN_LIB_SHA256`). */
2790
- export const SUBAGENT_SCOPE_LIBRARY = { relative: 'core/scripts/lib/session-scope-capability.sh', accepted: ['388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead', '498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38'] };
2883
+ export const SUBAGENT_SCOPE_LIBRARY = { relative: 'core/scripts/lib/session-scope-capability.sh', accepted: ['388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead', '498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38', 'cceddf40b3ec932cc4c83b31d72d9462f5a09be32246d57299591f4b75bdcd5a'] };
2791
2884
  /**
2792
2885
  * Why SubagentStart or SubagentStop (`event`) must stay on the shell registration in `root`: the
2793
2886
  * native master work (crates/hq-hook/src/lifecycle_master.rs `begin`) refuses every such event that
@@ -310,6 +310,7 @@
310
310
  "3194d664e3840dcbf48a2d5681feb7cd299bd6f60d296337c70d8042d60886c2",
311
311
  "388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead",
312
312
  "498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38",
313
+ "cceddf40b3ec932cc4c83b31d72d9462f5a09be32246d57299591f4b75bdcd5a",
313
314
  "5d4c619a55db0de6ff210a3aa0e99aa92fb5795a3290dcfcafc141e3ad3894b6",
314
315
  "743d9438922f0bcc29f09b38f159b4fd686cc2ba15390602ef7b7f1d8db9ac26",
315
316
  "9ea044084200e5f2d1f47477ffeaf591a87b406e9bf48c8fd6e24c551c799fc1",
@@ -197,7 +197,8 @@
197
197
  ],
198
198
  "core/scripts/lib/session-scope-capability.sh": [
199
199
  "388ffef43cfe05810c38ce377245d0d86f415b4009b21a008bca8897be0c9ead",
200
- "498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38"
200
+ "498ffa6e4342c79eecb0c1fddec56ba03e169bb627b2da8f8ef2f09f55954b38",
201
+ "cceddf40b3ec932cc4c83b31d72d9462f5a09be32246d57299591f4b75bdcd5a"
201
202
  ],
202
203
  "core/scripts/lib/transcript-tail.sh": [
203
204
  "73eadafdd8e7c375bd12383947ac73c43e7dfe79b29e6553da1cb5b2746bb217"
@@ -133,8 +133,9 @@ export declare const WORKLIST_TIMEOUT_MS = 60000;
133
133
  * - Unusable replies: 40 documents x BAD_OUTPUT_ATTEMPTS (3) calls x 120 s =
134
134
  * 4 hours (2 hours at the old cap of 20). That is longer than the 3 hours
135
135
  * after which the engine's company run lock can be taken over (LOCK_STALE_MS
136
- * in src/lib/signals/run-lock.ts, counted from the lock's start, with no
137
- * heartbeat).
136
+ * in src/lib/signals/run-lock.ts). The engine refreshes that lock when a
137
+ * step starts or finishes, so the 3 hours count from the start of the
138
+ * adapters step; this pass does not refresh it per document.
138
139
  * - Once a timed-out document is skipped instead of sent again (PR 3438, not
139
140
  * merged when this was written): 40 x 120 s = 80 minutes (40 minutes at the
140
141
  * old cap). That is longer than the 60 minutes after which the bot releases
@@ -156,6 +157,13 @@ export declare const BAD_OUTPUT_STOP_AFTER = 3;
156
157
  export declare const TIMEOUT_STOP_AFTER = 3;
157
158
  /** Payload bytes sent to claude per document (200 KB). A longer payload is cut with a marker. */
158
159
  export declare const MAX_PAYLOAD_BYTES: number;
160
+ /** A reply that opens as a provider's limit sentence and has no clause after it. */
161
+ /**
162
+ * True when the whole text is a provider's usage-limit sentence: short, opening
163
+ * as the sentence, with no clause after it. Prose that mentions a limit, or a
164
+ * longer text that contains the sentence, is not one.
165
+ */
166
+ export declare function isUsageLimitSentence(text: string): boolean;
159
167
  export interface BoundedRun {
160
168
  code: number | null;
161
169
  stdout: string;
@@ -307,8 +307,9 @@ export const WORKLIST_TIMEOUT_MS = 60_000;
307
307
  * - Unusable replies: 40 documents x BAD_OUTPUT_ATTEMPTS (3) calls x 120 s =
308
308
  * 4 hours (2 hours at the old cap of 20). That is longer than the 3 hours
309
309
  * after which the engine's company run lock can be taken over (LOCK_STALE_MS
310
- * in src/lib/signals/run-lock.ts, counted from the lock's start, with no
311
- * heartbeat).
310
+ * in src/lib/signals/run-lock.ts). The engine refreshes that lock when a
311
+ * step starts or finishes, so the 3 hours count from the start of the
312
+ * adapters step; this pass does not refresh it per document.
312
313
  * - Once a timed-out document is skipped instead of sent again (PR 3438, not
313
314
  * merged when this was written): 40 x 120 s = 80 minutes (40 minutes at the
314
315
  * old cap). That is longer than the 60 minutes after which the bot releases
@@ -341,6 +342,15 @@ const MAX_REASON_CHARS = 300;
341
342
  /** A reply longer than this is not a provider's limit sentence. */
342
343
  const MAX_LIMIT_SENTENCE_CHARS = 500;
343
344
  /** A reply that opens as a provider's limit sentence and has no clause after it. */
345
+ /**
346
+ * True when the whole text is a provider's usage-limit sentence: short, opening
347
+ * as the sentence, with no clause after it. Prose that mentions a limit, or a
348
+ * longer text that contains the sentence, is not one.
349
+ */
350
+ export function isUsageLimitSentence(text) {
351
+ const t = text.trim();
352
+ return t.length <= MAX_LIMIT_SENTENCE_CHARS && LIMIT_SENTENCE_REPLY.test(t) && isRuntimeUsageLimit(t);
353
+ }
344
354
  const LIMIT_SENTENCE_REPLY = /^(?:you(?:['’]?ve| have) (?:hit|reached) your |you['’]?re out of |(?:claude ai )?usage limit )[^,;\n]*(?:$|[|·.])/i;
345
355
  /**
346
356
  * Run a command with a hard timeout. The child leads its own process group;
@@ -786,7 +796,7 @@ export function parseSignalsReply(reply, runtime) {
786
796
  // A limit sentence can arrive as a plain successful reply. The whole reply
787
797
  // must be that sentence, so prose about a limit stays bad output, and the
788
798
  // reply is not quoted because it is stdout.
789
- if (text.length <= MAX_LIMIT_SENTENCE_CHARS && LIMIT_SENTENCE_REPLY.test(text) && isRuntimeUsageLimit(text)) {
799
+ if (isUsageLimitSentence(text)) {
790
800
  throw new SignalsPassError(`${runtime}-usage-limit`, `${runtime} is out of usage: its whole reply was a limit sentence`);
791
801
  }
792
802
  throw new SignalsPassError(`${runtime}-bad-output`, `${runtime} result is not JSON`);
@@ -67,7 +67,6 @@ export interface RunRecord {
67
67
  skippedReason?: string;
68
68
  currentStep: StepName | null;
69
69
  steps: StepRecord[];
70
- maxBudgetUsd: number;
71
70
  maxTurns: number;
72
71
  /** Set when a job run finishes complete or partial; carried forward by every later run that day. */
73
72
  jobRanAt: string | null;
@@ -202,7 +201,6 @@ export interface RunSignalsOptions {
202
201
  force?: boolean;
203
202
  catchUp?: boolean;
204
203
  maxTurns?: number;
205
- maxBudgetUsd?: number;
206
204
  now?: () => Date;
207
205
  spawn?: SpawnSyncFn;
208
206
  hotChannelSync?: HotChannelSyncFn;
@@ -23,7 +23,7 @@ import { loadSignalsSettings, loadIncrementalSettings } from "./settings.js";
23
23
  import { createIncrementalStep } from "./incremental.js";
24
24
  import { localDate } from "./local-date.js";
25
25
  import { guardedWrite, WriteGuardError } from "./write-guard.js";
26
- import { LOCK_STALE_MS, acquireCompanyLock, companyLockRel, defaultIsPidAlive, withSummaryLock, } from "./run-lock.js";
26
+ import { LOCK_STALE_MS, acquireCompanyLock, isLockExpired, companyLockRel, defaultIsPidAlive, withSummaryLock, } from "./run-lock.js";
27
27
  import { gardenStep } from "./steps/garden.js";
28
28
  import { adaptersStep } from "./steps/adapters.js";
29
29
  import { extractStep, redoItemChannel } from "./steps/extract.js";
@@ -563,9 +563,8 @@ export async function runSignals(opts) {
563
563
  }
564
564
  const limits = opts.incremental ? loadIncrementalSettings(hqRoot) : settings;
565
565
  const maxTurns = opts.maxTurns ?? limits.maxTurns;
566
- const maxBudgetUsd = opts.maxBudgetUsd ?? limits.maxBudgetUsd;
567
- if (!Number.isInteger(maxTurns) || maxTurns < 1 || !Number.isFinite(maxBudgetUsd) || maxBudgetUsd < 0)
568
- throw new SignalsUsageError("invalid model cost limits");
566
+ if (!Number.isInteger(maxTurns) || maxTurns < 1)
567
+ throw new SignalsUsageError("invalid model turn limit");
569
568
  const stepImpls = { ...DEFAULT_STEPS, ...(opts.steps ?? {}) };
570
569
  if (opts.incremental)
571
570
  stepImpls.extract = createIncrementalStep(opts.source, opts.incrementalOptions);
@@ -610,6 +609,7 @@ export async function runSignals(opts) {
610
609
  const write = (r, data) => guardedWrite(hqRoot, r, data, { company });
611
610
  // 1. Take the company lock (a dry run writes nothing, so it takes none).
612
611
  let release = null;
612
+ let heartbeat = null;
613
613
  let takeover = null;
614
614
  if (!dryRun) {
615
615
  const got = acquireCompanyLock({ hqRoot, date, company, trigger, now, ...(opts.isPidAlive ? { isPidAlive: opts.isPidAlive } : {}) });
@@ -618,6 +618,11 @@ export async function runSignals(opts) {
618
618
  locked.push({ company, status: "running", startedAt: got.holder.startedAt, trigger: got.holder.trigger });
619
619
  continue;
620
620
  }
621
+ // The lock is refreshed on progress only: here when a step starts or
622
+ // finishes, and by the extract step when a source starts or finishes.
623
+ // No timer refreshes it, so a run that stops making progress loses the
624
+ // lock after LOCK_STALE_MS even while its process is alive.
625
+ heartbeat = got.heartbeat;
621
626
  release = got.release;
622
627
  takeover = got.takeover;
623
628
  }
@@ -634,7 +639,6 @@ export async function runSignals(opts) {
634
639
  skipReason: null,
635
640
  currentStep: null,
636
641
  steps: [],
637
- maxBudgetUsd,
638
642
  maxTurns,
639
643
  jobRanAt: null,
640
644
  nextRetryAt: null,
@@ -767,6 +771,7 @@ export async function runSignals(opts) {
767
771
  for (const name of plan) {
768
772
  record.currentStep = name;
769
773
  persist();
774
+ heartbeat?.();
770
775
  const t0 = now().getTime();
771
776
  const ctx = {
772
777
  hqRoot,
@@ -775,7 +780,7 @@ export async function runSignals(opts) {
775
780
  trigger,
776
781
  catchUp: record.catchUp,
777
782
  maxTurns,
778
- maxBudgetUsd,
783
+ ...(heartbeat ? { heartbeat } : {}),
779
784
  unpricedSourceEstimateUsd: settings.unpricedSourceEstimateUsd,
780
785
  now,
781
786
  spawn,
@@ -923,7 +928,7 @@ function stoppedRunReason(hqRoot, record, date, nowMs, isPidAlive) {
923
928
  return `${lead}: it holds no run lock.`;
924
929
  if (!isPidAlive(holder.pid))
925
930
  return `${lead}: its process (pid ${holder.pid}) is gone.`;
926
- if (nowMs - Date.parse(holder.startedAt) > LOCK_STALE_MS) {
931
+ if (isLockExpired({ startedAt: holder.startedAt, ...(typeof holder.heartbeatAt === "string" ? { heartbeatAt: holder.heartbeatAt } : {}) }, nowMs)) {
927
932
  return `${lead}: it has held the run lock for more than ${LOCK_STALE_MS / 3_600_000} hours.`;
928
933
  }
929
934
  return null;
@@ -169,33 +169,17 @@ export function runCountItems(record, summary, opts) {
169
169
  function spendUsd(record) {
170
170
  return record.steps.reduce((n, s) => n + (s.estimatedSpendUsd ?? 0), 0);
171
171
  }
172
- function spendBlock(record) {
173
- if (!(record.maxBudgetUsd > 0))
174
- return null;
175
- const spend = spendUsd(record);
176
- const value = Math.max(0, Math.min(100, Math.round((spend / record.maxBudgetUsd) * 100)));
177
- // Some coding tools report no cost; the step then counts a flat amount per source. Say it is an estimate.
178
- const estimated = record.steps.some((s) => s.detail?.spendEstimated === true);
179
- return {
180
- kind: "progress",
181
- value,
182
- label: `${estimated ? "Estimated spend" : "Spend"} $${spend.toFixed(2)} of the $${record.maxBudgetUsd.toFixed(2)} cap`,
183
- tone: "neutral",
184
- };
185
- }
186
172
  /**
187
- * A run that stopped at the spend cap on estimated spend, in plain words:
188
- * how many sources were processed, how many are left, and what controls it.
189
- * Null for any other outcome.
173
+ * The run's estimated spend as one key/value row, or null when nothing was
174
+ * spent. It is information only: there is no cap to compare it with.
190
175
  */
191
- function estimatedBudgetStop(record) {
192
- const step = record.steps.find((s) => s.error === "budget-exceeded" && s.detail?.spendEstimated === true && typeof s.detail.sourcesProcessed === "number");
193
- const d = step?.detail;
194
- if (!d)
176
+ function spendItem(record) {
177
+ const spend = spendUsd(record);
178
+ if (!(spend > 0))
195
179
  return null;
196
- const each = typeof d.unpricedSourceEstimateUsd === "number" ? `$${d.unpricedSourceEstimateUsd.toFixed(2)}` : "a set amount";
197
- const left = typeof d.sourcesLeft === "number" && d.sourcesLeft > 0 ? `, with at least ${plural(d.sourcesLeft, "source")} left for the next run` : "";
198
- return `Signals stopped at the $${record.maxBudgetUsd.toFixed(2)} spend cap after ${plural(d.sourcesProcessed, "source")}${left}. The spend is an estimate: this coding tool does not report its cost, so each source counts as ${each}. To process more in one run, raise the cap with --max-budget-usd.`;
180
+ // Some coding tools report no cost; the step then counts a flat amount per source. Say it is an estimate.
181
+ const estimated = record.steps.some((s) => s.detail?.spendEstimated === true);
182
+ return { key: estimated ? "Estimated spend" : "Spend", value: `$${spend.toFixed(2)}` };
199
183
  }
200
184
  /**
201
185
  * The non-desktop brief decision. It says the brief builds next only when a
@@ -231,48 +215,22 @@ function listInWords(parts) {
231
215
  function capitalize(text) {
232
216
  return text ? text[0].toUpperCase() + text.slice(1) : text;
233
217
  }
234
- /** The extract step that stopped because the run reached its spend cap, if any. */
235
- function budgetStopStep(record) {
218
+ /**
219
+ * Run records written while runs had a spend cap can hold an extract step that
220
+ * stopped with error "budget-exceeded". No run stops that way now. The reply
221
+ * for such a record says only that the run stopped early.
222
+ */
223
+ function legacyEarlyStopStep(record) {
236
224
  return record.steps.find((s) => s.name === "extract" && (s.status === "partial" || s.status === "failed") && s.error === "budget-exceeded");
237
225
  }
238
- /** "$2.00", or null when the record carries no usable cap. */
239
- function capInWords(record) {
240
- return Number.isFinite(record.maxBudgetUsd) && record.maxBudgetUsd >= 0 ? `$${record.maxBudgetUsd.toFixed(2)}` : null;
241
- }
226
+ const LEGACY_EARLY_STOP_TITLE = "Finding signals stopped early.";
227
+ const LEGACY_EARLY_STOP_MAIN = "Finding signals stopped before it read every source. The sources it did not reach wait for the next run.";
228
+ const LEGACY_EARLY_STOP_NOTE = "Finding signals also stopped early, so some sources wait for the next run.";
242
229
  /** The run's first problem, picked the way finalizeRecord picks the step behind failureReason. */
243
230
  function firstProblem(record) {
244
231
  const problems = record.steps.filter((s) => s.status === "failed" || s.status === "partial");
245
232
  return problems.find((s) => s.status === "failed") ?? problems[0];
246
233
  }
247
- /**
248
- * The per-run way to raise the cap. Only the flag is named: the default lives
249
- * in core/settings/signals.yaml, which is release-owned and replaced on
250
- * update, so a member edit there would be lost. The flag also sets the cap of
251
- * an --incremental run.
252
- */
253
- function raiseCapLine(record) {
254
- return `To raise the cap for one run, use hq signals run --company ${record.company} --max-budget-usd <amount>.`;
255
- }
256
- /**
257
- * A budget stop in words: the source it stopped at (detail.budgetStoppedAt),
258
- * that the rest waits for the next run, and how to raise the cap for a run.
259
- */
260
- function budgetGuidance(record, stopped) {
261
- // Estimated spend has its own sentence (counts and the per-source amount).
262
- // A metered stop still names the source it stopped at.
263
- const estimated = estimatedBudgetStop(record);
264
- if (estimated)
265
- return estimated;
266
- const raw = stopped.detail?.budgetStoppedAt;
267
- const at = typeof raw === "string" && raw.trim() ? raw.trim() : null;
268
- const cap = capInWords(record);
269
- const reached = cap ? `its spend cap of ${cap}` : "its spend cap";
270
- return [
271
- at ? `Finding signals stopped at ${at} because the run reached ${reached}.` : `Finding signals stopped because the run reached ${reached}.`,
272
- at ? "That source and any after it wait for the next run." : "The sources it did not reach wait for the next run.",
273
- raiseCapLine(record),
274
- ].join(" ");
275
- }
276
234
  /**
277
235
  * The extract step's signed-out kind is the coding tool's login, never HQ's:
278
236
  * the Fleet bot's own login when extract ran on it (detail.login "fleet"),
@@ -296,17 +254,16 @@ function codingToolSignedOut(step) {
296
254
  * (reconnect, signed-out) is on the failing step; the record carries only the
297
255
  * coarse v2 kind (auth, config, transient).
298
256
  *
299
- * `main` answers the run's first problem. A budget stop that is not the first
300
- * problem is added as a short `note` after it, so neither problem goes unsaid.
257
+ * `main` answers the run's first problem. An early stop on an older record
258
+ * (legacyEarlyStopStep) that is not the first problem is added as a short
259
+ * `note` after it, so neither problem goes unsaid.
301
260
  */
302
261
  function failureGuidance(record, failed, company) {
303
- const stopped = budgetStopStep(record);
304
- const budgetFirst = stopped !== undefined && firstProblem(record) === stopped;
305
- const cap = capInWords(record);
306
- const shortNote = `Finding signals also reached ${cap ? `its ${cap} spend cap` : "its spend cap"}, so some sources wait for the next run. ${raiseCapLine(record)}`;
262
+ const stopped = legacyEarlyStopStep(record);
263
+ const stoppedFirst = stopped !== undefined && firstProblem(record) === stopped;
307
264
  const kindStep = failed?.errorKind ? failed : record.steps.find((s) => s.status === "failed" || s.status === "partial");
308
265
  const stepKind = kindStep?.errorKind;
309
- // Sign-in and setup problems come first; a budget stop is then added after them.
266
+ // Sign-in and setup problems come first; an older record's early stop is then added after them.
310
267
  const urgent = stepKind === "reconnect" ? `A connection for ${company} needs reconnecting.`
311
268
  : stepKind === "signed-out" && kindStep?.name === "extract" ? codingToolSignedOut(kindStep)
312
269
  : stepKind === "signed-out" ? "You are signed out of HQ. Sign in again with hq login."
@@ -314,13 +271,13 @@ function failureGuidance(record, failed, company) {
314
271
  : record.errorKind === "config" ? `Something in the signals setup for ${company} needs fixing first.`
315
272
  : null;
316
273
  if (urgent)
317
- return { main: urgent, note: stopped ? (budgetFirst ? budgetGuidance(record, stopped) : shortNote) : null };
318
- if (budgetFirst)
319
- return { main: budgetGuidance(record, stopped), note: null };
274
+ return { main: urgent, note: stopped ? (stoppedFirst ? LEGACY_EARLY_STOP_MAIN : LEGACY_EARLY_STOP_NOTE) : null };
275
+ if (stoppedFirst)
276
+ return { main: LEGACY_EARLY_STOP_MAIN, note: null };
320
277
  const main = record.errorKind === "transient" ? "This looks temporary."
321
278
  : failed ? `${STEP_DOING[failed.name]} for ${company} failed.`
322
279
  : `Signals for ${company} failed.`;
323
- return { main, note: stopped ? shortNote : null };
280
+ return { main, note: stopped ? LEGACY_EARLY_STOP_NOTE : null };
324
281
  }
325
282
  /** First sentence of an error, trimmed to one plain line. */
326
283
  function oneSentence(text) {
@@ -432,12 +389,9 @@ export function formatRunReply(record, summary, opts) {
432
389
  const stoppedProse = `${job} stopped at ${finished}.`;
433
390
  return build(opts.desktopLinks ? `${stoppedProse}\n\n${briefLinkLine(opts)}` : stoppedProse, blocks, "failed");
434
391
  }
435
- const counts = runCountItems(record, summary, opts);
436
- const spend = spendBlock(record);
437
- const tail = [
438
- ...(counts.length ? [{ kind: "keyValue", items: counts }] : []),
439
- ...(spend ? [spend] : []),
440
- ];
392
+ const spend = spendItem(record);
393
+ const counts = [...runCountItems(record, summary, opts), ...(spend ? [spend] : [])];
394
+ const tail = counts.length ? [{ kind: "keyValue", items: counts }] : [];
441
395
  const due = timeInWords(opts.scheduledFor, tz);
442
396
  const catchUpBadge = { kind: "badge", label: "Catch-up", tone: "warning", icon: "clock" };
443
397
  const partialReason = record.partialReason ?? record.partial ?? null;
@@ -450,12 +404,11 @@ export function formatRunReply(record, summary, opts) {
450
404
  ], "late-start");
451
405
  }
452
406
  if (record.status === "partial") {
453
- // The budget title only when the budget stop is the run's first problem
454
- // (the step finalizeRecord builds failureReason from).
407
+ // An older record's early stop gets its own title only when it is the
408
+ // run's first problem (the step finalizeRecord builds failureReason from).
455
409
  const first = firstProblem(record);
456
- const budgetCap = first && first === budgetStopStep(record) ? capInWords(record) : null;
457
- const title = budgetCap
458
- ? `Finding signals reached the ${budgetCap} spend cap.`
410
+ const title = first && first === legacyEarlyStopStep(record)
411
+ ? LEGACY_EARLY_STOP_TITLE
459
412
  : record.failureReason
460
413
  ? oneSentence(record.failureReason)
461
414
  : partialReason
@@ -464,7 +417,7 @@ export function formatRunReply(record, summary, opts) {
464
417
  const guidance = failureGuidance(record, failedStep, company);
465
418
  // A signals pass that was blocked or failed: the owner's plain notice and
466
419
  // its one fix lead, never the pass's error code. The run's own guidance
467
- // (a reconnect step, the spend cap) stays after it. A run reply is always
420
+ // (a reconnect step) stays after it. A run reply is always
468
421
  // a bot's, so a signed-out pass names the bot's own sign-in, never a
469
422
  // Claude Code sign-in.
470
423
  const notice = signalsNoticeProblem(record);
@@ -3,7 +3,13 @@ export interface LockHolder {
3
3
  pid: number;
4
4
  startedAt: string;
5
5
  trigger: string;
6
+ /** When the holder last refreshed the lock. Absent until the first refresh. */
7
+ heartbeatAt?: string;
6
8
  }
9
+ /** The lock's last sign of life in epoch ms: its heartbeat, else its start. NaN when neither parses. */
10
+ export declare function lockLastAliveMs(holder: Pick<LockHolder, "startedAt" | "heartbeatAt">): number;
11
+ /** True when the lock's last sign of life is more than LOCK_STALE_MS before `nowMs`. */
12
+ export declare function isLockExpired(holder: Pick<LockHolder, "startedAt" | "heartbeatAt">, nowMs: number): boolean;
7
13
  export interface LockTakeover extends LockHolder {
8
14
  takenOverAt: string;
9
15
  reason: "pid-dead" | "expired" | "unreadable";
@@ -11,6 +17,8 @@ export interface LockTakeover extends LockHolder {
11
17
  export type AcquireResult = {
12
18
  ok: true;
13
19
  takeover: LockTakeover | null;
20
+ /** Refresh the lock's heartbeatAt. A no-op when the lock no longer names this holder. Never throws. */
21
+ heartbeat: () => void;
14
22
  release: () => void;
15
23
  } | {
16
24
  ok: false;
@@ -3,10 +3,23 @@
3
3
  * (run record contract v2).
4
4
  *
5
5
  * Lock file: workspace/signals/runs/{date}/{company}.lock, created with
6
- * O_EXCL ("wx") and holding JSON { pid, startedAt, trigger }. A lock is stale
7
- * when its pid is not alive or its startedAt is older than 3 hours; a stale
8
- * lock is removed and taken over, and the caller logs the takeover in the
9
- * run record.
6
+ * O_EXCL ("wx") and holding JSON { pid, startedAt, trigger, heartbeatAt }. A
7
+ * lock is stale when its pid is not alive, or when its last sign of life is
8
+ * older than 3 hours; a stale lock is removed and taken over, and the caller
9
+ * logs the takeover in the run record.
10
+ *
11
+ * The last sign of life is heartbeatAt, or startedAt for a lock that has no
12
+ * heartbeat yet (and for a lock written by an older hq-cli). The holder
13
+ * refreshes heartbeatAt only when it makes progress (`heartbeat` on the
14
+ * acquire result): the engine when a step starts or finishes, and the extract
15
+ * step when a source starts or finishes. There is no timer, so a refresh is
16
+ * evidence of work, not of a live process. A run that keeps making progress
17
+ * keeps its lock however long it takes. A run that makes no progress for 3
18
+ * hours loses it, even when its process is alive (an awaited step that never
19
+ * settles, for example).
20
+ *
21
+ * 3 hours is far above the longest gap between two refreshes in the extract
22
+ * step, MAX_SOURCE_GAP_MS in steps/extract.ts (about 26 minutes).
10
23
  */
11
24
  import * as fs from "node:fs";
12
25
  import * as path from "node:path";
@@ -14,6 +27,15 @@ import { assertAllowedPath } from "./write-guard.js";
14
27
  export const LOCK_STALE_MS = 3 * 60 * 60 * 1000;
15
28
  /** An unreadable lock younger than this is treated as being written right now. */
16
29
  const UNREADABLE_GRACE_MS = 60 * 1000;
30
+ /** The lock's last sign of life in epoch ms: its heartbeat, else its start. NaN when neither parses. */
31
+ export function lockLastAliveMs(holder) {
32
+ const beat = typeof holder.heartbeatAt === "string" ? Date.parse(holder.heartbeatAt) : Number.NaN;
33
+ return Number.isNaN(beat) ? Date.parse(holder.startedAt) : beat;
34
+ }
35
+ /** True when the lock's last sign of life is more than LOCK_STALE_MS before `nowMs`. */
36
+ export function isLockExpired(holder, nowMs) {
37
+ return nowMs - lockLastAliveMs(holder) > LOCK_STALE_MS;
38
+ }
17
39
  export function companyLockRel(date, company) {
18
40
  return `workspace/signals/runs/${date}/${company}.lock`;
19
41
  }
@@ -33,7 +55,7 @@ function readHolder(abs) {
33
55
  try {
34
56
  const v = JSON.parse(fs.readFileSync(abs, "utf8"));
35
57
  if (typeof v.pid === "number" && typeof v.startedAt === "string" && typeof v.trigger === "string") {
36
- return { pid: v.pid, startedAt: v.startedAt, trigger: v.trigger };
58
+ return { pid: v.pid, startedAt: v.startedAt, trigger: v.trigger, ...(typeof v.heartbeatAt === "string" ? { heartbeatAt: v.heartbeatAt } : {}) };
37
59
  }
38
60
  }
39
61
  catch {
@@ -73,7 +95,20 @@ export function acquireCompanyLock(input) {
73
95
  fs.rmSync(abs, { force: true });
74
96
  }
75
97
  };
76
- return { ok: true, takeover, release };
98
+ const heartbeat = () => {
99
+ try {
100
+ const current = readHolder(abs);
101
+ if (!current || current.pid !== mine.pid || current.startedAt !== mine.startedAt)
102
+ return;
103
+ const tmp = `${abs}.hb-${process.pid}`;
104
+ fs.writeFileSync(tmp, JSON.stringify({ ...mine, heartbeatAt: input.now().toISOString() }));
105
+ fs.renameSync(tmp, abs);
106
+ }
107
+ catch {
108
+ // A missed refresh is not an error: the next one writes again.
109
+ }
110
+ };
111
+ return { ok: true, takeover, heartbeat, release };
77
112
  }
78
113
  const holder = readHolder(abs);
79
114
  const nowMs = input.now().getTime();
@@ -94,7 +129,7 @@ export function acquireCompanyLock(input) {
94
129
  else if (!isAlive(holder.pid)) {
95
130
  reason = "pid-dead";
96
131
  }
97
- else if (nowMs - Date.parse(holder.startedAt) > LOCK_STALE_MS) {
132
+ else if (isLockExpired(holder, nowMs)) {
98
133
  reason = "expired";
99
134
  }
100
135
  if (reason === null && holder)
@@ -58,7 +58,8 @@ export function isRunRecord(v) {
58
58
  (v.currentStep === null || oneOf(STEP_NAMES, v.currentStep)) &&
59
59
  Array.isArray(v.steps) &&
60
60
  v.steps.every(isStepRecord) &&
61
- isNum(v.maxBudgetUsd) &&
61
+ // `maxBudgetUsd` is on records written while runs had a spend cap. It is
62
+ // not read and not checked, so those records still load.
62
63
  isNum(v.maxTurns) &&
63
64
  strOrNull(v.jobRanAt) &&
64
65
  strOrNull(v.nextRetryAt) &&