@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
@@ -0,0 +1,300 @@
1
+ /**
2
+ * The release-stable link `<home>/.hq/bin/hq-hook/stable`, which every
3
+ * core.next registration runs the engine through.
4
+ *
5
+ * Kept apart from host-registration.ts so the start-up heal
6
+ * (stable-heal.ts) can move the link without loading the registration switch,
7
+ * the canary gate and their imports. host-registration.ts re-exports what it
8
+ * always exported from here.
9
+ *
10
+ * The link never moves to a lower engine version than the one it names unless
11
+ * the caller is a repair or downgrade the person asked for and passes
12
+ * `allowDowngrade: true` (no command does yet). There is deliberately no
13
+ * environment switch: a lane or an old install script could set one. The
14
+ * refusal applies only while the newer engine the link names is still there
15
+ * and runnable. An older hq-cli run with the real home once moved it from
16
+ * 5.345.268 back to 5.345.238; the older engine did not know the installed gate
17
+ * and refused every PreToolUse call until a heal finished. This guard only
18
+ * binds CLIs that carry it; stable-heal.ts undoes a roll-back made by an older
19
+ * CLI when the pinned engine was canary-accepted on this machine.
20
+ */
21
+ import * as fs from 'node:fs';
22
+ import * as path from 'node:path';
23
+ /** Name of the release-stable link next to the pinned engine versions. */
24
+ export const STABLE_LINK_NAME = 'stable';
25
+ /** Record of canary-accepted hook engines committed to `stable`, under the home folder. */
26
+ export const ACCEPTED_HOOK_ENGINE_RECORD = path.join('.hq', 'bin', 'hq-hook', 'accepted-engine.json');
27
+ /** Schema of [`ACCEPTED_HOOK_ENGINE_RECORD`]. */
28
+ export const ACCEPTED_HOOK_ENGINE_SCHEMA = 'hq.accepted-hook-engine.v1';
29
+ /**
30
+ * Read `<home>/.hq/bin/hq-hook/accepted-engine.json`; null when absent,
31
+ * unreadable, invalid, or writable by another user.
32
+ */
33
+ export function readAcceptedHookEngineRecord(home, platform = process.platform) {
34
+ const file = path.join(home, ACCEPTED_HOOK_ENGINE_RECORD);
35
+ let text;
36
+ try {
37
+ checkOwnedEntry(file, 'file', platform);
38
+ text = fs.readFileSync(file, 'utf8');
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ let doc;
44
+ try {
45
+ doc = JSON.parse(text);
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ const rec = doc;
51
+ if (!rec || rec.schema !== ACCEPTED_HOOK_ENGINE_SCHEMA || !rec.engines || typeof rec.engines !== 'object' || Array.isArray(rec.engines)) {
52
+ return null;
53
+ }
54
+ const engines = {};
55
+ for (const [key, raw] of Object.entries(rec.engines)) {
56
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
57
+ continue;
58
+ const entry = raw;
59
+ if (typeof entry.engineVersion !== 'string' || !entry.engineVersion)
60
+ continue;
61
+ if (typeof entry.pinnedEngine !== 'string' || !entry.pinnedEngine)
62
+ continue;
63
+ if (!Array.isArray(entry.hosts))
64
+ continue;
65
+ const hosts = entry.hosts.filter((h) => typeof h === 'string');
66
+ if (hosts.length === 0)
67
+ continue;
68
+ engines[key] = {
69
+ engineVersion: entry.engineVersion,
70
+ pinnedEngine: entry.pinnedEngine,
71
+ acceptedAt: typeof entry.acceptedAt === 'string' ? entry.acceptedAt : '',
72
+ hosts,
73
+ };
74
+ }
75
+ return { schema: ACCEPTED_HOOK_ENGINE_SCHEMA, engines };
76
+ }
77
+ /** True when `pinned` resolves to an engine recorded in the accepted-engine record (it passed the host canary gate here). */
78
+ export function isAcceptedHookEngine(home, pinned, platform = process.platform) {
79
+ let resolved;
80
+ try {
81
+ resolved = fs.realpathSync(pinned);
82
+ }
83
+ catch {
84
+ return false;
85
+ }
86
+ const entry = readAcceptedHookEngineRecord(home, platform)?.engines[resolved];
87
+ return !!entry && entry.hosts.length > 0;
88
+ }
89
+ /** Thrown when `stable` names a newer, runnable engine and the caller did not ask for a downgrade. */
90
+ export class StableDowngradeRefused extends Error {
91
+ constructor(message) {
92
+ super(message);
93
+ this.name = 'StableDowngradeRefused';
94
+ }
95
+ }
96
+ export function hookEngineDir(home) {
97
+ return path.join(home, '.hq', 'bin', 'hq-hook');
98
+ }
99
+ /** The stable path that stands for a pinned engine path. */
100
+ export function stableEnginePath(pinned, home) {
101
+ const relative = path.relative(hookEngineDir(home), pinned);
102
+ const [, ...rest] = relative.split(/[\\/]/);
103
+ if (relative.startsWith('..') || path.isAbsolute(relative) || rest.length === 0) {
104
+ throw new Error(`hook engine ${pinned} is not under ${hookEngineDir(home)}`);
105
+ }
106
+ return path.join(hookEngineDir(home), STABLE_LINK_NAME, ...rest);
107
+ }
108
+ function parseVersion(version) {
109
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(version);
110
+ if (!match)
111
+ return null;
112
+ return { core: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] ? match[4].split('.') : [] };
113
+ }
114
+ /**
115
+ * Semver precedence of two engine version folder names: negative when `a` is
116
+ * older, positive when newer, 0 when equal. Null when either is not a version
117
+ * folder name, so the caller cannot tell which is older.
118
+ */
119
+ export function compareEngineVersions(a, b) {
120
+ const left = parseVersion(a);
121
+ const right = parseVersion(b);
122
+ if (!left || !right)
123
+ return null;
124
+ for (let i = 0; i < 3; i += 1) {
125
+ if (left.core[i] !== right.core[i])
126
+ return left.core[i] - right.core[i];
127
+ }
128
+ if (!left.pre.length || !right.pre.length)
129
+ return right.pre.length - left.pre.length;
130
+ for (let i = 0; i < Math.max(left.pre.length, right.pre.length); i += 1) {
131
+ const x = left.pre[i];
132
+ const y = right.pre[i];
133
+ if (x === undefined)
134
+ return -1;
135
+ if (y === undefined)
136
+ return 1;
137
+ if (x === y)
138
+ continue;
139
+ const xn = /^\d+$/.test(x);
140
+ const yn = /^\d+$/.test(y);
141
+ if (xn && yn)
142
+ return Number(x) - Number(y);
143
+ if (xn !== yn)
144
+ return xn ? -1 : 1;
145
+ return x < y ? -1 : 1;
146
+ }
147
+ return 0;
148
+ }
149
+ /** The version folder an engine path under `<home>/.hq/bin/hq-hook` sits in; null when it is not under it. */
150
+ export function engineVersionOf(pinned, home) {
151
+ const relative = path.relative(hookEngineDir(home), pinned);
152
+ if (relative.startsWith('..') || path.isAbsolute(relative))
153
+ return null;
154
+ const version = relative.split(/[\\/]/)[0];
155
+ return version && version !== STABLE_LINK_NAME ? version : null;
156
+ }
157
+ /** The version folder name `stable` names (even when that folder is gone); null when it is not a link. */
158
+ export function stableLinkVersion(home) {
159
+ try {
160
+ const target = fs.readlinkSync(path.join(hookEngineDir(home), STABLE_LINK_NAME));
161
+ return target.split(/[\\/]/).filter(Boolean).pop() ?? null;
162
+ }
163
+ catch {
164
+ return null;
165
+ }
166
+ }
167
+ /** True when `file` resolves to a regular file that this platform can run. */
168
+ function isRunnableFile(file, platform) {
169
+ try {
170
+ const stat = fs.statSync(fs.realpathSync(file));
171
+ return stat.isFile() && (platform === 'win32' || (stat.mode & 0o111) !== 0);
172
+ }
173
+ catch {
174
+ return false;
175
+ }
176
+ }
177
+ /** Append one line to `<home>/.hq/logs/stable-heal.log`; best effort. */
178
+ export function appendStableHealLog(home, line, now = Date.now()) {
179
+ try {
180
+ const logDir = path.join(home, '.hq', 'logs');
181
+ fs.mkdirSync(logDir, { recursive: true });
182
+ fs.appendFileSync(path.join(logDir, 'stable-heal.log'), `${new Date(now).toISOString()} ${line}\n`);
183
+ }
184
+ catch {
185
+ // Nowhere left to record it; the caller still gets the error.
186
+ }
187
+ }
188
+ /**
189
+ * Point `<home>/.hq/bin/hq-hook/stable` at the pinned engine's version folder
190
+ * and return the stable engine path. The link is replaced by rename, so a
191
+ * planted file at the temporary name or the link itself is never followed. A
192
+ * `stable` that is a real folder (not a link) is someone else's and is left
193
+ * alone: the call fails and the caller keeps the current registrations.
194
+ *
195
+ * A link that names a newer engine than `pinned`, which is still there and
196
+ * runnable, stays where it is: the call records the refusal in stable-heal.log
197
+ * and throws [`StableDowngradeRefused`], unless the person asked for the
198
+ * downgrade ([`LinkStableEngineOptions.allowDowngrade`]).
199
+ */
200
+ export function linkStableEngine(pinned, home, platform = process.platform, options = {}) {
201
+ const root = hookEngineDir(home);
202
+ const relative = path.relative(root, pinned).split(/[\\/]/);
203
+ const version = relative[0];
204
+ if (!version || version === '..' || version === STABLE_LINK_NAME || path.isAbsolute(path.relative(root, pinned))) {
205
+ throw new Error(`hook engine ${pinned} is not under ${root}`);
206
+ }
207
+ const stable = path.join(root, STABLE_LINK_NAME);
208
+ // Store rule v2: every path component this follows or creates under the home
209
+ // folder is a real folder of this user that group and others cannot write:
210
+ // .hq, .hq/bin, .hq/bin/hq-hook, the version folder and any folder below it
211
+ // up to the engine, and the engine file itself.
212
+ const components = [path.join(home, '.hq'), path.join(home, '.hq', 'bin'), root];
213
+ for (let i = 0; i < relative.length - 1; i += 1)
214
+ components.push(path.join(root, ...relative.slice(0, i + 1)));
215
+ for (const component of components)
216
+ checkOwnedEntry(component, 'folder', platform);
217
+ checkOwnedEntry(pinned, 'file', platform);
218
+ // Windows creates a junction, which needs an absolute target; elsewhere the
219
+ // link is relative so it names the version folder beside it.
220
+ const target = platform === 'win32' ? path.join(root, version) : version;
221
+ let current;
222
+ try {
223
+ current = fs.lstatSync(stable);
224
+ }
225
+ catch (error) {
226
+ if (error.code !== 'ENOENT')
227
+ throw error;
228
+ }
229
+ if (current && !current.isSymbolicLink())
230
+ throw new Error(`${stable} exists and is not a link; leaving it in place`);
231
+ if (current && pointsAt(stable, path.join(root, version)))
232
+ return stableEnginePath(pinned, home);
233
+ if (current && options.allowDowngrade !== true) {
234
+ const linked = stableLinkVersion(home);
235
+ const order = linked ? compareEngineVersions(version, linked) : null;
236
+ // Only a newer engine that still runs holds the link: a dangling or broken
237
+ // target is relinked to the engine installed now.
238
+ const linkedEngine = path.join(stable, ...relative.slice(1));
239
+ if (order !== null && order < 0 && pointsAt(stable, path.join(root, linked)) && isRunnableFile(linkedEngine, platform)) {
240
+ const message = `refused to move ${stable} from ${linked} back to the older engine ${version} (${pinned}); only an explicit repair or downgrade may move it back`;
241
+ appendStableHealLog(home, message, (options.now ?? Date.now)());
242
+ throw new StableDowngradeRefused(message);
243
+ }
244
+ }
245
+ if (platform === 'win32') {
246
+ // A junction cannot be renamed over another. A running engine keeps its
247
+ // own image open, which the junction does not hold.
248
+ if (current) {
249
+ try {
250
+ fs.unlinkSync(stable);
251
+ }
252
+ catch {
253
+ fs.rmdirSync(stable);
254
+ }
255
+ }
256
+ fs.symlinkSync(target, stable, 'junction');
257
+ }
258
+ else {
259
+ const staged = path.join(root, `.${STABLE_LINK_NAME}.${process.pid}.tmp`);
260
+ try {
261
+ fs.unlinkSync(staged);
262
+ }
263
+ catch (error) {
264
+ if (error.code !== 'ENOENT')
265
+ throw error;
266
+ }
267
+ fs.symlinkSync(target, staged);
268
+ try {
269
+ fs.renameSync(staged, stable);
270
+ }
271
+ catch (error) {
272
+ try {
273
+ fs.unlinkSync(staged);
274
+ }
275
+ catch { /* already gone */ }
276
+ throw error;
277
+ }
278
+ }
279
+ return stableEnginePath(pinned, home);
280
+ }
281
+ /** A real folder or file (not a link) of this user that group and others cannot write. */
282
+ export function checkOwnedEntry(entry, kind, platform) {
283
+ const stat = fs.lstatSync(entry);
284
+ if (stat.isSymbolicLink() || (kind === 'folder' ? !stat.isDirectory() : !stat.isFile()))
285
+ throw new Error(`${entry} is not a ${kind}`);
286
+ if (typeof process.getuid === 'function' && stat.uid !== process.getuid())
287
+ throw new Error(`${entry} is not owned by this user`);
288
+ if (platform !== 'win32' && (stat.mode & 0o022) !== 0)
289
+ throw new Error(`${entry} is writable by group or others`);
290
+ }
291
+ /** True when the link resolves to `folder` (Windows reports junction targets in its own spelling). */
292
+ export function pointsAt(link, folder) {
293
+ try {
294
+ return fs.realpathSync(link) === fs.realpathSync(folder);
295
+ }
296
+ catch {
297
+ return false;
298
+ }
299
+ }
300
+ //# sourceMappingURL=stable-link.js.map
@@ -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`);
@@ -83,7 +83,10 @@ export function resolveInstallHookTarget(hqRoot, home, daemonInstalled, env = pr
83
83
  }
84
84
  const coreNext = forHost(rawCoreNext, hqRoot, host, env);
85
85
  if (coreNext) {
86
- candidate?.commitStable?.([host]);
86
+ if (candidate?.commitStable)
87
+ candidate.commitStable([host]);
88
+ else
89
+ candidate?.recordAccepted?.([host]);
87
90
  return { target: { ...coreNext, fallback } };
88
91
  }
89
92
  const existingHosts = nativeOnly ? detectMachineHookHosts(hqRoot, home, env) : [];
@@ -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);