@indigoai-us/hq-cli 5.345.220 → 5.345.221

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 (138) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/dist/command-catalog.generated.d.ts +144 -2
  3. package/dist/command-catalog.generated.js +175 -2
  4. package/dist/commands/auth.js +4 -1
  5. package/dist/commands/bot-runtime.d.ts +18 -5
  6. package/dist/commands/bot-runtime.js +29 -12
  7. package/dist/commands/bot.d.ts +39 -2
  8. package/dist/commands/bot.js +140 -11
  9. package/dist/commands/core-stop-autosave.d.ts +21 -0
  10. package/dist/commands/core-stop-autosave.js +300 -0
  11. package/dist/commands/core.js +2 -0
  12. package/dist/commands/daemon.d.ts +5 -0
  13. package/dist/commands/daemon.js +31 -7
  14. package/dist/commands/doctor-usage.d.ts +5 -0
  15. package/dist/commands/doctor-usage.js +25 -0
  16. package/dist/commands/env.d.ts +49 -4
  17. package/dist/commands/env.js +355 -5
  18. package/dist/commands/lanes-shared.d.ts +3 -0
  19. package/dist/commands/lanes.d.ts +3 -0
  20. package/dist/commands/lanes.js +87 -3
  21. package/dist/commands/sources.js +3 -3
  22. package/dist/commands/sync-core.d.ts +1 -0
  23. package/dist/commands/sync-core.js +77 -3
  24. package/dist/commands/whoami.js +96 -80
  25. package/dist/lib/bot/config.d.ts +17 -0
  26. package/dist/lib/bot/config.js +13 -0
  27. package/dist/lib/bot/fleet-cron.js +24 -2
  28. package/dist/lib/bot/fleet-local.d.ts +30 -2
  29. package/dist/lib/bot/fleet-local.js +60 -1
  30. package/dist/lib/bot/grok-login-scope.d.ts +36 -0
  31. package/dist/lib/bot/grok-login-scope.js +93 -0
  32. package/dist/lib/bot/legacy-provider-login.d.ts +32 -9
  33. package/dist/lib/bot/legacy-provider-login.js +28 -22
  34. package/dist/lib/bot/runtime-sign-in-check.js +6 -1
  35. package/dist/lib/bot/runtime-sign-in.d.ts +2 -0
  36. package/dist/lib/core-utils/sentry-report.js +2 -0
  37. package/dist/lib/daemon/machine-checks.d.ts +22 -1
  38. package/dist/lib/daemon/machine-checks.js +54 -12
  39. package/dist/lib/daemon/run.js +66 -8
  40. package/dist/lib/daemon/stop-autosave-lock.d.ts +19 -0
  41. package/dist/lib/daemon/stop-autosave-lock.js +166 -0
  42. package/dist/lib/daemon/stop-autosave.d.ts +28 -0
  43. package/dist/lib/daemon/stop-autosave.js +111 -0
  44. package/dist/lib/daemon/stop-diagnostics.d.ts +11 -0
  45. package/dist/lib/daemon/stop-diagnostics.js +136 -0
  46. package/dist/lib/daemon/stop-job-executor.d.ts +19 -0
  47. package/dist/lib/daemon/stop-job-executor.js +126 -0
  48. package/dist/lib/daemon/stop-jobs.d.ts +93 -0
  49. package/dist/lib/daemon/stop-jobs.js +599 -0
  50. package/dist/lib/doctor/checks/fleet-hook-core.js +1 -1
  51. package/dist/lib/doctor/checks/host-core.js +1 -1
  52. package/dist/lib/environment/access-probes.d.ts +234 -0
  53. package/dist/lib/environment/access-probes.js +918 -0
  54. package/dist/lib/environment/profile.d.ts +15 -2
  55. package/dist/lib/environment/profile.js +55 -20
  56. package/dist/lib/environment/rfc3339.d.ts +8 -0
  57. package/dist/lib/environment/rfc3339.js +26 -0
  58. package/dist/lib/environment/work-requirements.d.ts +169 -0
  59. package/dist/lib/environment/work-requirements.js +389 -0
  60. package/dist/lib/hook-engine/coverage.d.ts +137 -7
  61. package/dist/lib/hook-engine/coverage.js +1424 -4
  62. package/dist/lib/hook-engine/fleet-registration.js +2 -2
  63. package/dist/lib/hook-engine/git-stop-config.json +513 -0
  64. package/dist/lib/hook-engine/native-stop-compatibility.json +311 -0
  65. package/dist/lib/hook-engine/reconcile.js +2 -2
  66. package/dist/lib/hot-channels/alert.d.ts +2 -2
  67. package/dist/lib/hot-channels/alert.js +8 -5
  68. package/dist/lib/hot-channels/signals-pass.d.ts +126 -17
  69. package/dist/lib/hot-channels/signals-pass.js +296 -17
  70. package/dist/lib/hot-channels/signals-runtime.d.ts +30 -0
  71. package/dist/lib/hot-channels/signals-runtime.js +82 -0
  72. package/dist/lib/install/hook-target.js +1 -1
  73. package/dist/lib/lanes/host-capacity.d.ts +26 -2
  74. package/dist/lib/lanes/host-capacity.js +17 -2
  75. package/dist/lib/lanes/host-compute.d.ts +90 -0
  76. package/dist/lib/lanes/host-compute.js +185 -0
  77. package/dist/lib/lanes/index.d.ts +2 -0
  78. package/dist/lib/lanes/index.js +1 -0
  79. package/dist/lib/lanes/reconcile.js +22 -1
  80. package/dist/lib/lanes/resource-usage.d.ts +155 -0
  81. package/dist/lib/lanes/resource-usage.js +589 -0
  82. package/dist/lib/lanes/run-size.d.ts +46 -0
  83. package/dist/lib/lanes/run-size.js +197 -0
  84. package/dist/lib/lanes/store.js +27 -0
  85. package/dist/lib/lanes/throttle.d.ts +36 -1
  86. package/dist/lib/lanes/throttle.js +47 -10
  87. package/dist/lib/lanes/types.d.ts +40 -0
  88. package/dist/lib/lanes/types.js +2 -2
  89. package/dist/lib/lanes/watcher.js +13 -4
  90. package/dist/lib/lanes/worker-process.d.ts +25 -2
  91. package/dist/lib/lanes/worker-process.js +71 -19
  92. package/dist/lib/placement/match.d.ts +192 -0
  93. package/dist/lib/placement/match.js +667 -0
  94. package/dist/lib/safe-store.d.ts +14 -0
  95. package/dist/lib/safe-store.js +77 -4
  96. package/dist/lib/search-index/index.d.ts +88 -4
  97. package/dist/lib/search-index/index.js +288 -24
  98. package/dist/lib/search-index/max-doc-bytes.d.ts +17 -6
  99. package/dist/lib/search-index/max-doc-bytes.js +48 -23
  100. package/dist/lib/signals/codex-lockdown.d.ts +79 -0
  101. package/dist/lib/signals/codex-lockdown.js +271 -0
  102. package/dist/lib/signals/codex-login.d.ts +37 -0
  103. package/dist/lib/signals/codex-login.js +83 -0
  104. package/dist/lib/signals/engine.d.ts +27 -0
  105. package/dist/lib/signals/engine.js +70 -0
  106. package/dist/lib/signals/reply.js +22 -1
  107. package/dist/lib/signals/run-record.js +6 -1
  108. package/dist/lib/signals/settings.d.ts +5 -0
  109. package/dist/lib/signals/settings.js +2 -0
  110. package/dist/lib/signals/steps/extract.d.ts +85 -9
  111. package/dist/lib/signals/steps/extract.js +317 -68
  112. package/dist/lib/signals/steps/types.d.ts +2 -0
  113. package/dist/lib/sync-core/engine-home.d.ts +35 -1
  114. package/dist/lib/sync-core/engine-home.js +119 -16
  115. package/dist/lib/sync-core/rollout-state.d.ts +2 -1
  116. package/dist/lib/sync-core/rollout-state.js +5 -2
  117. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  118. package/dist/lib/sync-core/vault-uid.js +4 -0
  119. package/dist/schemas/hq-work-requirements.v1.schema.json +145 -0
  120. package/dist/utils/auth-session-check.d.ts +16 -0
  121. package/dist/utils/auth-session-check.js +16 -0
  122. package/dist/utils/client-health-contract.d.ts +6 -0
  123. package/dist/utils/client-health-contract.js +13 -0
  124. package/dist/utils/client-health.d.ts +7 -0
  125. package/dist/utils/client-health.js +22 -1
  126. package/dist/utils/command-usage.d.ts +40 -0
  127. package/dist/utils/command-usage.js +61 -0
  128. package/dist/utils/duplicate-command-usage.d.ts +72 -0
  129. package/dist/utils/duplicate-command-usage.js +125 -0
  130. package/dist/utils/host-registration.js +2 -1
  131. package/dist/utils/resident-package-preload.js +4 -0
  132. package/dist/utils/sentry-fingerprint.js +9 -0
  133. package/dist/utils/windows-bash.d.ts +2 -0
  134. package/dist/utils/windows-bash.js +2 -1
  135. package/package.json +9 -8
  136. package/scripts/bench-core-compare.mjs +313 -0
  137. package/scripts/bench-core.mjs +399 -12
  138. package/scripts/check-function-manifest.mjs +116 -3
@@ -0,0 +1,589 @@
1
+ /**
2
+ * Resource use of one lane worker run (PS-011).
3
+ *
4
+ * The lane worker wrapper (worker-process.ts) samples every process in the
5
+ * worker's tree while it runs and writes one `resource_usage` block into
6
+ * logs/worker-exit.json when the worker exits. The watcher adds that block to
7
+ * the lane record's `run_size` (run-size.ts).
8
+ *
9
+ * What each value means, and how exact it is:
10
+ *
11
+ * - active_seconds: wall time from the wrapper starting the worker to the
12
+ * worker exiting. A lane that is blocked or waiting on a question has no
13
+ * worker process, so that time is never in a run. (A Remote Control lane's
14
+ * worker stays up while it waits for the user; run-size.ts marks those.)
15
+ * - peak_rss_mb: the largest sum of resident memory over the processes in the
16
+ * tree at one sample. Sampled (default every 5 s), so a peak shorter than the
17
+ * interval can be missed, and pages shared between processes are counted
18
+ * once per process. Linux reads the page size from `getconf PAGESIZE`, else
19
+ * from /proc/self/smaps.
20
+ * - cpu_seconds: user + system CPU, the larger of two lower bounds that never
21
+ * double count: (a) each process's own CPU at its last sample, summed over
22
+ * every process seen; (b) at one sample, each live process's own CPU plus
23
+ * the CPU of the children it has already waited for (Linux cutime/cstime;
24
+ * macOS ri_child_user/system_time from proc_pid_rusage), summed. (b) counts
25
+ * short tool calls that start and end between samples. On Linux the wrapper
26
+ * also reads its own reaped-children CPU from /proc/self/stat after the
27
+ * worker exits, which covers every descendant that was waited for. macOS
28
+ * child CPU covers direct children only (a grandchild started through a
29
+ * shell was not included when measured), so macOS stays a lower bound.
30
+ * - disk_written_mb: bytes the tree caused to be written to storage. Linux:
31
+ * /proc/<pid>/io write_bytes, which already includes waited-for children;
32
+ * the largest per-sample sum over live processes, and the wrapper's own
33
+ * /proc/self/io after the worker exits, whichever is larger. macOS:
34
+ * ri_diskio_byteswritten from proc_pid_rusage per live process, read
35
+ * through the Command Line Tools python3 (macOS ships no command that
36
+ * prints per-process disk bytes); summed per process over the run. macOS
37
+ * keeps no disk count for exited children, so a process that exits between
38
+ * samples loses what it wrote since its last sample. Null when that python3
39
+ * is not installed.
40
+ *
41
+ * Processes are the wrapper's descendants (by parent pid) plus, when the
42
+ * wrapper leads its process group (lanes spawn it detached), every process in
43
+ * that group. The sampler's own ps and python3 are left out. A descendant
44
+ * that starts its own session after its parent exited is not seen.
45
+ */
46
+ import * as childProcess from "node:child_process";
47
+ import * as fs from "node:fs";
48
+ export const RESOURCE_SAMPLE_INTERVAL_MS_DEFAULT = 5_000;
49
+ export const RESOURCE_SAMPLE_INTERVAL_ENV = "HQ_LANE_RESOURCE_SAMPLE_MS";
50
+ /** The longest stop() waits for a sample that is still running before it gives up on it. */
51
+ export const RESOURCE_STOP_WAIT_MS = 250;
52
+ const SAMPLE_TIMEOUT_MS = 4_000;
53
+ /** Linux USER_HZ: 100 on every architecture Node supports. */
54
+ const LINUX_CLOCK_TICKS = 100;
55
+ const MB = 1024 * 1024;
56
+ /** The Command Line Tools / Xcode python3. /usr/bin/python3 is a stub that can open an install dialog. */
57
+ export const DARWIN_PYTHON_CANDIDATES = [
58
+ "/Library/Developer/CommandLineTools/usr/bin/python3",
59
+ "/Applications/Xcode.app/Contents/Developer/usr/bin/python3",
60
+ ];
61
+ function defaultExecFile(cmd, args, timeoutMs, signal) {
62
+ return new Promise((resolve, reject) => {
63
+ childProcess.execFile(cmd, args, { timeout: timeoutMs, maxBuffer: 8 * MB, encoding: "utf8", signal, killSignal: "SIGKILL" }, (error, stdout) => {
64
+ if (error)
65
+ reject(error);
66
+ else
67
+ resolve(stdout);
68
+ });
69
+ });
70
+ }
71
+ /** `KernelPageSize: 4 kB` from /proc/self/smaps, in bytes. */
72
+ export function parseSmapsPageSize(text) {
73
+ const m = /^KernelPageSize:\s*(\d+)\s*kB\s*$/m.exec(text);
74
+ const bytes = m ? Number(m[1]) * 1024 : NaN;
75
+ return Number.isSafeInteger(bytes) && bytes > 0 ? bytes : null;
76
+ }
77
+ let cachedLinuxPageSize;
78
+ /** Linux page size: `getconf PAGESIZE` once, else /proc/self/smaps, cached for the process. */
79
+ export function linuxPageSize(run = () => childProcess.execFileSync("getconf", ["PAGESIZE"], { encoding: "utf8", timeout: 2_000 }), readSmaps = () => fs.readFileSync("/proc/self/smaps", "utf8")) {
80
+ if (cachedLinuxPageSize !== undefined)
81
+ return cachedLinuxPageSize;
82
+ let size = null;
83
+ try {
84
+ const n = Number(run().trim());
85
+ if (Number.isSafeInteger(n) && n > 0)
86
+ size = n;
87
+ }
88
+ catch {
89
+ size = null;
90
+ }
91
+ if (size === null) {
92
+ try {
93
+ size = parseSmapsPageSize(readSmaps());
94
+ }
95
+ catch {
96
+ size = null;
97
+ }
98
+ }
99
+ cachedLinuxPageSize = size;
100
+ return size;
101
+ }
102
+ /** Test hook: forget the cached page size. */
103
+ export function _resetLinuxPageSizeForTests() {
104
+ cachedLinuxPageSize = undefined;
105
+ }
106
+ /** `[[DD-]HH:]MM:SS[.cc]` (ps `time` on macOS and Linux) to seconds; null when unreadable. */
107
+ export function parsePsCpuTime(value) {
108
+ const text = value.trim();
109
+ const match = /^(?:(\d+)-)?([\d:.]+)$/.exec(text);
110
+ if (!match)
111
+ return null;
112
+ const days = match[1] ? Number(match[1]) : 0;
113
+ const parts = match[2].split(":");
114
+ if (parts.length < 1 || parts.length > 3 || parts.some((p) => p === "" || !/^\d+(\.\d+)?$/.test(p)))
115
+ return null;
116
+ let seconds = 0;
117
+ for (const part of parts)
118
+ seconds = seconds * 60 + Number(part);
119
+ return days * 86_400 + seconds;
120
+ }
121
+ /** Parses `ps -A -o pid=,ppid=,pgid=,rss=,time=` output (rss in KiB). */
122
+ export function parsePsSnapshot(text) {
123
+ const out = [];
124
+ for (const line of text.split(/\r?\n/)) {
125
+ const fields = line.trim().split(/\s+/);
126
+ if (fields.length < 5)
127
+ continue;
128
+ const [pid, ppid, pgid, rss] = fields.slice(0, 4).map(Number);
129
+ const cpu = parsePsCpuTime(fields[4]);
130
+ if (![pid, ppid, pgid, rss].every((n) => Number.isSafeInteger(n) && n >= 0) || cpu === null)
131
+ continue;
132
+ out.push({ pid: pid, ppid: ppid, pgid: pgid, rssBytes: rss * 1024, cpuSeconds: cpu, diskWrittenBytes: null });
133
+ }
134
+ return out;
135
+ }
136
+ /** Parses /proc/<pid>/stat: fields after the parenthesised comm. */
137
+ export function parseProcStat(text, pageSize) {
138
+ const close = text.lastIndexOf(")");
139
+ const open = text.indexOf("(");
140
+ if (open < 0 || close < open)
141
+ return null;
142
+ const pid = Number(text.slice(0, open).trim());
143
+ const rest = text.slice(close + 2).trim().split(/\s+/);
144
+ // rest[0] is field 3 (state); field N is rest[N - 3].
145
+ const at = (field) => Number(rest[field - 3]);
146
+ const values = { ppid: at(4), pgid: at(5), utime: at(14), stime: at(15), cutime: at(16), cstime: at(17), starttime: at(22), rss: at(24) };
147
+ if (!Number.isSafeInteger(pid) || Object.values(values).some((n) => !Number.isFinite(n)))
148
+ return null;
149
+ return {
150
+ pid,
151
+ ppid: values.ppid,
152
+ pgid: values.pgid,
153
+ rssBytes: pageSize === null ? 0 : Math.max(0, values.rss) * pageSize,
154
+ rssKnown: pageSize !== null,
155
+ cpuSeconds: (values.utime + values.stime) / LINUX_CLOCK_TICKS,
156
+ childCpuSeconds: (values.cutime + values.cstime) / LINUX_CLOCK_TICKS,
157
+ starttime: values.starttime,
158
+ };
159
+ }
160
+ /** write_bytes from /proc/<pid>/io, or null. */
161
+ export function parseProcIoWriteBytes(text) {
162
+ const match = /^write_bytes:\s*(\d+)\s*$/m.exec(text);
163
+ return match ? Number(match[1]) : null;
164
+ }
165
+ /**
166
+ * The worker's processes: descendants of the wrapper (`rootPid`) plus the
167
+ * members of its process group, without the wrapper itself. When the worker's
168
+ * pid is known, the wrapper's other children (the sampler's own ps and
169
+ * python3) and their descendants are left out.
170
+ */
171
+ export function selectTree(all, rootPid, rootPgid, workerPid = null) {
172
+ const children = new Map();
173
+ for (const p of all) {
174
+ const list = children.get(p.ppid) ?? [];
175
+ list.push(p);
176
+ children.set(p.ppid, list);
177
+ }
178
+ const descendants = (start) => {
179
+ const seen = new Set();
180
+ const stack = [start];
181
+ while (stack.length > 0) {
182
+ const pid = stack.pop();
183
+ for (const child of children.get(pid) ?? []) {
184
+ if (seen.has(child.pid) || child.pid === rootPid)
185
+ continue;
186
+ seen.add(child.pid);
187
+ stack.push(child.pid);
188
+ }
189
+ }
190
+ return seen;
191
+ };
192
+ const excluded = new Set([rootPid]);
193
+ if (workerPid !== null) {
194
+ for (const helper of children.get(rootPid) ?? []) {
195
+ if (helper.pid === workerPid)
196
+ continue;
197
+ excluded.add(helper.pid);
198
+ for (const pid of descendants(helper.pid))
199
+ excluded.add(pid);
200
+ }
201
+ }
202
+ const wanted = descendants(rootPid);
203
+ // The group counts only when the wrapper leads it (spawned detached, as
204
+ // lanes do). Otherwise the group is the caller's, with unrelated processes.
205
+ if (rootPgid !== null && rootPgid === rootPid) {
206
+ for (const p of all)
207
+ if (p.pgid === rootPgid)
208
+ wanted.add(p.pid);
209
+ }
210
+ return all.filter((p) => wanted.has(p.pid) && !excluded.has(p.pid));
211
+ }
212
+ /**
213
+ * proc_pid_rusage per pid: prints `pid disk_bytes own_cpu_s child_cpu_s`.
214
+ * CPU times are mach absolute time units, converted with mach_timebase_info.
215
+ */
216
+ export const DARWIN_RUSAGE_SCRIPT = [
217
+ "import ctypes, sys",
218
+ "lib = ctypes.CDLL('/usr/lib/libproc.dylib')",
219
+ "sysl = ctypes.CDLL('/usr/lib/libSystem.dylib')",
220
+ "class R(ctypes.Structure):",
221
+ " _fields_ = [('uuid', ctypes.c_uint8 * 16)] + [(n, ctypes.c_uint64) for n in ('u','s','pi','iw','pg','wired','res','phys','ps','pe','cu','cs','cpi','ciw','cpg','ce','dr','dw')]",
222
+ "class TB(ctypes.Structure):",
223
+ " _fields_ = [('numer', ctypes.c_uint32), ('denom', ctypes.c_uint32)]",
224
+ "tb = TB()",
225
+ "sysl.mach_timebase_info(ctypes.byref(tb))",
226
+ "f = tb.numer / tb.denom / 1e9",
227
+ "for a in sys.argv[1:]:",
228
+ " r = R()",
229
+ " if lib.proc_pid_rusage(int(a), 2, ctypes.byref(r)) == 0:",
230
+ " print(a, r.dw, '%.6f' % ((r.u + r.s) * f), '%.6f' % ((r.cu + r.cs) * f))",
231
+ ].join("\n");
232
+ /** Parses `pid disk own child` lines from the macOS rusage helper. */
233
+ export function parseDarwinRusage(text) {
234
+ const out = new Map();
235
+ for (const line of text.split(/\r?\n/)) {
236
+ const m = /^(\d+)\s+(\d+)\s+(\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)$/.exec(line.trim());
237
+ if (m)
238
+ out.set(Number(m[1]), { diskBytes: Number(m[2]), cpuSeconds: Number(m[3]), childCpuSeconds: Number(m[4]) });
239
+ }
240
+ return out;
241
+ }
242
+ /**
243
+ * Accumulates samples of one worker tree. Feed it with `record`; read the
244
+ * totals with `totals`. Kept separate from the I/O so it can be tested with
245
+ * plain arrays.
246
+ */
247
+ export class ResourceAccumulator {
248
+ live = new Map();
249
+ retiredCpu = 0;
250
+ retiredDisk = 0;
251
+ sawExclusiveDisk = false;
252
+ /** Largest per-sample sum of own + reaped-children CPU over live processes. */
253
+ inclusiveCpu = null;
254
+ /** Largest per-sample sum of disk counters that already include reaped children. */
255
+ inclusiveDisk = null;
256
+ peakRssBytes = 0;
257
+ samples = 0;
258
+ record(tree) {
259
+ this.samples += 1;
260
+ let rss = 0;
261
+ let inclusiveCpu = 0;
262
+ let sawChildCpu = false;
263
+ let inclusiveDisk = 0;
264
+ let sawInclusiveDisk = false;
265
+ for (const p of tree) {
266
+ rss += p.rssBytes;
267
+ if (p.inclusiveExcluded) {
268
+ // Possibly already inside its parent's reaped-children counters.
269
+ }
270
+ else if (typeof p.childCpuSeconds === "number") {
271
+ sawChildCpu = true;
272
+ inclusiveCpu += p.cpuSeconds + p.childCpuSeconds;
273
+ }
274
+ else {
275
+ inclusiveCpu += p.cpuSeconds;
276
+ }
277
+ if (p.diskWrittenBytes !== null && p.diskIncludesChildren && !p.inclusiveExcluded) {
278
+ sawInclusiveDisk = true;
279
+ inclusiveDisk += p.diskWrittenBytes;
280
+ }
281
+ const exclusiveDisk = p.diskIncludesChildren ? null : p.diskWrittenBytes;
282
+ if (exclusiveDisk !== null)
283
+ this.sawExclusiveDisk = true;
284
+ const prev = this.live.get(p.pid);
285
+ if (prev && p.cpuSeconds + 0.5 < prev.cpu) {
286
+ // The pid was reused by a new process: keep what the old one used.
287
+ this.retiredCpu += prev.cpu;
288
+ this.retiredDisk += prev.disk ?? 0;
289
+ this.live.set(p.pid, { cpu: p.cpuSeconds, disk: exclusiveDisk });
290
+ continue;
291
+ }
292
+ this.live.set(p.pid, {
293
+ cpu: Math.max(prev?.cpu ?? 0, p.cpuSeconds),
294
+ disk: exclusiveDisk === null ? prev?.disk ?? null : Math.max(prev?.disk ?? 0, exclusiveDisk),
295
+ });
296
+ }
297
+ this.peakRssBytes = Math.max(this.peakRssBytes, rss);
298
+ if (sawChildCpu)
299
+ this.inclusiveCpu = Math.max(this.inclusiveCpu ?? 0, inclusiveCpu);
300
+ if (sawInclusiveDisk)
301
+ this.inclusiveDisk = Math.max(this.inclusiveDisk ?? 0, inclusiveDisk);
302
+ }
303
+ totals() {
304
+ let cpu = this.retiredCpu;
305
+ let disk = this.retiredDisk;
306
+ for (const t of this.live.values()) {
307
+ cpu += t.cpu;
308
+ disk += t.disk ?? 0;
309
+ }
310
+ const usedChildCpu = this.inclusiveCpu !== null && this.inclusiveCpu > cpu;
311
+ if (usedChildCpu)
312
+ cpu = this.inclusiveCpu;
313
+ let diskTotal = this.sawExclusiveDisk ? disk : null;
314
+ if (this.inclusiveDisk !== null)
315
+ diskTotal = Math.max(diskTotal ?? 0, this.inclusiveDisk);
316
+ return { peakRssBytes: this.peakRssBytes, cpuSeconds: cpu, diskWrittenBytes: diskTotal, usedChildCpu };
317
+ }
318
+ }
319
+ const round = (n, places) => {
320
+ const f = 10 ** places;
321
+ return Math.round(n * f) / f;
322
+ };
323
+ /**
324
+ * Samples the process tree under `rootPid` until `stop()` is called, then
325
+ * returns the run's `WorkerResourceUsage`. Sampling never throws: a failed
326
+ * sample is skipped, and a run with no successful sample reports null values.
327
+ */
328
+ export class WorkerResourceSampler {
329
+ rootPid;
330
+ startedAt;
331
+ intervalMs;
332
+ stopWaitMs;
333
+ deps;
334
+ acc = new ResourceAccumulator();
335
+ abort = new AbortController();
336
+ timer = null;
337
+ inFlight = null;
338
+ stopped = false;
339
+ rootPgid = null;
340
+ workerPid = null;
341
+ pythonPath;
342
+ rssMethod = "none";
343
+ cpuMethod = "none";
344
+ diskMethod = "none";
345
+ constructor(rootPid, startedAt, intervalMs, deps = {}, stopWaitMs = RESOURCE_STOP_WAIT_MS) {
346
+ this.rootPid = rootPid;
347
+ this.startedAt = startedAt;
348
+ this.intervalMs = intervalMs;
349
+ this.stopWaitMs = stopWaitMs;
350
+ this.deps = {
351
+ platform: deps.platform ?? process.platform,
352
+ readFile: deps.readFile ?? ((p) => fs.readFileSync(p, "utf8")),
353
+ readdir: deps.readdir ?? ((p) => fs.readdirSync(p)),
354
+ existsSync: deps.existsSync ?? ((p) => fs.existsSync(p)),
355
+ execFile: deps.execFile ?? defaultExecFile,
356
+ pageSize: deps.pageSize ?? (() => linuxPageSize()),
357
+ };
358
+ }
359
+ /** The worker process the wrapper started; the wrapper's other children are the sampler's own tools. */
360
+ setWorkerPid(pid) {
361
+ this.workerPid = typeof pid === "number" && pid > 0 ? pid : null;
362
+ }
363
+ start() {
364
+ if (this.timer || this.stopped)
365
+ return;
366
+ this.timer = setInterval(() => void this.tick(), this.intervalMs);
367
+ this.timer.unref?.();
368
+ void this.tick();
369
+ }
370
+ /** One sample, skipped while the previous one is still running. */
371
+ tick() {
372
+ if (this.stopped)
373
+ return Promise.resolve();
374
+ if (this.inFlight)
375
+ return this.inFlight;
376
+ this.inFlight = this.sample()
377
+ .then((tree) => {
378
+ // A sample that finishes after stop() is dropped: totals are already out.
379
+ if (tree && !this.stopped)
380
+ this.acc.record(tree);
381
+ })
382
+ .catch(() => undefined)
383
+ .finally(() => {
384
+ this.inFlight = null;
385
+ });
386
+ return this.inFlight;
387
+ }
388
+ async sample() {
389
+ if (this.deps.platform === "linux")
390
+ return this.sampleLinux();
391
+ if (this.deps.platform === "win32")
392
+ return null;
393
+ return this.samplePs();
394
+ }
395
+ sampleLinux() {
396
+ const all = [];
397
+ let names;
398
+ try {
399
+ names = this.deps.readdir("/proc");
400
+ }
401
+ catch {
402
+ return null;
403
+ }
404
+ const pageSize = this.deps.pageSize();
405
+ const starttimes = new Map();
406
+ for (const name of names) {
407
+ if (!/^\d+$/.test(name))
408
+ continue;
409
+ try {
410
+ const stat = parseProcStat(this.deps.readFile(`/proc/${name}/stat`), pageSize);
411
+ if (!stat)
412
+ continue;
413
+ starttimes.set(stat.pid, stat.starttime);
414
+ all.push({
415
+ pid: stat.pid,
416
+ ppid: stat.ppid,
417
+ pgid: stat.pgid,
418
+ rssBytes: stat.rssBytes,
419
+ cpuSeconds: stat.cpuSeconds,
420
+ childCpuSeconds: stat.childCpuSeconds,
421
+ diskWrittenBytes: null,
422
+ diskIncludesChildren: true,
423
+ });
424
+ }
425
+ catch {
426
+ // the process exited while it was read
427
+ }
428
+ }
429
+ const self = all.find((p) => p.pid === this.rootPid);
430
+ if (self)
431
+ this.rootPgid = self.pgid;
432
+ const tree = selectTree(all, this.rootPid, this.rootPgid, this.workerPid);
433
+ for (const p of tree) {
434
+ try {
435
+ p.diskWrittenBytes = parseProcIoWriteBytes(this.deps.readFile(`/proc/${p.pid}/io`));
436
+ }
437
+ catch {
438
+ p.diskWrittenBytes = null;
439
+ }
440
+ }
441
+ // The stats and io files were read one process at a time. A process that
442
+ // exited and was waited for during the pass may already be counted in its
443
+ // parent's cutime/cstime and write_bytes; one whose pid was reused is a
444
+ // different process. Either way it no longer reads back with the same
445
+ // start time, and it is left out of this sample's inclusive totals.
446
+ for (const p of tree) {
447
+ let same = false;
448
+ try {
449
+ same = parseProcStat(this.deps.readFile(`/proc/${p.pid}/stat`), null)?.starttime === starttimes.get(p.pid);
450
+ }
451
+ catch {
452
+ same = false;
453
+ }
454
+ if (!same)
455
+ p.inclusiveExcluded = true;
456
+ }
457
+ this.rssMethod = pageSize === null ? "none" : "proc";
458
+ this.cpuMethod = "proc";
459
+ if (tree.some((p) => p.diskWrittenBytes !== null))
460
+ this.diskMethod = "proc";
461
+ return tree;
462
+ }
463
+ async samplePs() {
464
+ const text = await this.deps.execFile("ps", ["-A", "-o", "pid=,ppid=,pgid=,rss=,time="], SAMPLE_TIMEOUT_MS, this.abort.signal);
465
+ const all = parsePsSnapshot(text);
466
+ const self = all.find((p) => p.pid === this.rootPid);
467
+ if (self)
468
+ this.rootPgid = self.pgid;
469
+ const tree = selectTree(all, this.rootPid, this.rootPgid, this.workerPid);
470
+ this.rssMethod = "ps";
471
+ if (this.cpuMethod === "none")
472
+ this.cpuMethod = "ps";
473
+ if (this.deps.platform === "darwin" && tree.length > 0 && !this.stopped) {
474
+ const python = this.darwinPython();
475
+ if (python) {
476
+ try {
477
+ const rusage = parseDarwinRusage(await this.deps.execFile(python, ["-I", "-c", DARWIN_RUSAGE_SCRIPT, ...tree.map((p) => String(p.pid))], SAMPLE_TIMEOUT_MS, this.abort.signal));
478
+ for (const p of tree) {
479
+ const r = rusage.get(p.pid);
480
+ if (!r) {
481
+ // Gone by the time python3 ran: it may have been waited for
482
+ // after ps saw it, so its parent's child CPU may hold it.
483
+ p.inclusiveExcluded = true;
484
+ continue;
485
+ }
486
+ p.diskWrittenBytes = r.diskBytes;
487
+ p.cpuSeconds = Math.max(p.cpuSeconds, r.cpuSeconds);
488
+ p.childCpuSeconds = r.childCpuSeconds;
489
+ }
490
+ if (rusage.size > 0) {
491
+ this.diskMethod = "libproc";
492
+ this.cpuMethod = "ps+libproc";
493
+ }
494
+ }
495
+ catch {
496
+ // disk and child CPU stay unknown for this sample
497
+ }
498
+ }
499
+ }
500
+ return tree;
501
+ }
502
+ darwinPython() {
503
+ if (this.pythonPath === undefined) {
504
+ this.pythonPath = DARWIN_PYTHON_CANDIDATES.find((p) => this.deps.existsSync(p)) ?? null;
505
+ }
506
+ return this.pythonPath;
507
+ }
508
+ /** Linux only: CPU and disk of the wrapper's waited-for descendants, read from its own /proc entry. */
509
+ linuxReapedChildren() {
510
+ if (this.deps.platform !== "linux")
511
+ return { cpu: null, diskBytes: null };
512
+ let cpu;
513
+ let diskBytes;
514
+ try {
515
+ cpu = parseProcStat(this.deps.readFile(`/proc/${this.rootPid}/stat`), null)?.childCpuSeconds ?? null;
516
+ }
517
+ catch {
518
+ cpu = null;
519
+ }
520
+ try {
521
+ diskBytes = parseProcIoWriteBytes(this.deps.readFile(`/proc/${this.rootPid}/io`));
522
+ }
523
+ catch {
524
+ diskBytes = null;
525
+ }
526
+ return { cpu, diskBytes };
527
+ }
528
+ /**
529
+ * Stops sampling and returns the run's usage. Waits at most stopWaitMs for
530
+ * a sample already running; past that the sample's ps or python3 is killed
531
+ * and the totals so far are used.
532
+ */
533
+ async stop(endedAt) {
534
+ if (this.timer)
535
+ clearInterval(this.timer);
536
+ this.timer = null;
537
+ const pending = this.inFlight;
538
+ if (pending) {
539
+ let timeout;
540
+ const timedOut = await Promise.race([
541
+ pending.then(() => false),
542
+ new Promise((resolve) => {
543
+ // Not unref'd: the wrapper must stay alive until stop() returns.
544
+ timeout = setTimeout(() => resolve(true), this.stopWaitMs);
545
+ }),
546
+ ]);
547
+ if (timeout)
548
+ clearTimeout(timeout);
549
+ if (timedOut)
550
+ this.abort.abort();
551
+ }
552
+ this.stopped = true;
553
+ this.abort.abort();
554
+ const totals = this.acc.totals();
555
+ const reaped = this.linuxReapedChildren();
556
+ const sampled = this.acc.samples > 0;
557
+ let cpu = sampled ? totals.cpuSeconds : null;
558
+ let cpuMethod = sampled ? this.cpuMethod : "none";
559
+ if (reaped.cpu !== null && (cpu === null || reaped.cpu > cpu)) {
560
+ cpu = reaped.cpu;
561
+ cpuMethod = "proc+children";
562
+ }
563
+ let disk = totals.diskWrittenBytes;
564
+ let diskMethod = disk === null ? "none" : this.diskMethod;
565
+ if (reaped.diskBytes !== null && (disk === null || reaped.diskBytes > disk)) {
566
+ disk = reaped.diskBytes;
567
+ diskMethod = "proc+children";
568
+ }
569
+ const rssKnown = sampled && this.rssMethod !== "none";
570
+ return {
571
+ started_at: this.startedAt.toISOString(),
572
+ ended_at: endedAt.toISOString(),
573
+ active_seconds: round(Math.max(0, endedAt.getTime() - this.startedAt.getTime()) / 1000, 1),
574
+ peak_rss_mb: rssKnown ? round(totals.peakRssBytes / MB, 1) : null,
575
+ cpu_seconds: cpu === null ? null : round(cpu, 2),
576
+ disk_written_mb: disk === null ? null : round(disk / MB, 2),
577
+ samples: this.acc.samples,
578
+ sample_interval_ms: this.intervalMs,
579
+ method: { rss: rssKnown ? this.rssMethod : "none", cpu: cpuMethod, disk: diskMethod },
580
+ };
581
+ }
582
+ }
583
+ export function resourceSampleIntervalMs(env) {
584
+ const raw = Number(env[RESOURCE_SAMPLE_INTERVAL_ENV]);
585
+ if (!Number.isFinite(raw) || raw <= 0)
586
+ return RESOURCE_SAMPLE_INTERVAL_MS_DEFAULT;
587
+ return Math.min(60_000, Math.max(100, Math.floor(raw)));
588
+ }
589
+ //# sourceMappingURL=resource-usage.js.map
@@ -0,0 +1,46 @@
1
+ import { resolveAdmissionHost } from "./admission-host.js";
2
+ import type { LaneRecord, LaneRunSize } from "./types.js";
3
+ import type { WorkerResourceUsage } from "./resource-usage.js";
4
+ export type { ActiveSecondsBasis, LaneRunSize } from "./types.js";
5
+ /** A worker-exit.json `resource_usage` block, or null when absent or malformed. */
6
+ export declare function parseWorkerResourceUsage(raw: unknown): WorkerResourceUsage | null;
7
+ /** Reads the last run's resource use from the lane's run dir. */
8
+ export declare function readWorkerResourceUsage(runDir: string): WorkerResourceUsage | null;
9
+ /**
10
+ * A stored run_size, or undefined when it is malformed. Read leniently: a
11
+ * bad size must never make the lane unreadable.
12
+ */
13
+ export declare function parseLaneRunSize(raw: unknown): LaneRunSize | undefined;
14
+ /** The canonical id of the machine this process runs on (PS-003). */
15
+ export declare function canonicalHostIdHere(deps?: Parameters<typeof resolveAdmissionHost>[0]): string | null;
16
+ /** The repo the lane works in, from its work requirements. */
17
+ export declare function laneRepo(lane: Pick<LaneRecord, "work_requirements">): string | null;
18
+ /**
19
+ * The lane's run_size with one more run added, or null when the run was
20
+ * already added (same started_at) or carries no usage.
21
+ */
22
+ export declare function addRunToSize(lane: Pick<LaneRecord, "run_size" | "provider" | "account" | "work_requirements" | "remote_control">, usage: WorkerResourceUsage | null, input: {
23
+ hostId: string | null;
24
+ at: string;
25
+ }): LaneRunSize | null;
26
+ /** The watcher's patch for a run that just ended: `{ run_size }` or nothing. */
27
+ export declare function runSizeFields(runDir: string, lane: Pick<LaneRecord, "run_size" | "provider" | "account" | "work_requirements" | "remote_control">, at: string, hostId?: () => string | null): Pick<LaneRecord, "run_size"> | Record<string, never>;
28
+ export declare function median(values: readonly number[]): number | null;
29
+ export interface RepoRunSizeMedian {
30
+ repo: string;
31
+ lanes: number;
32
+ active_seconds_median: number | null;
33
+ /** Remote Control lanes in this repo left out because their active_seconds is wall time. */
34
+ wall_clock_lanes_excluded: number;
35
+ peak_rss_mb_median: number | null;
36
+ }
37
+ /** Key used for lanes whose repo is not known. */
38
+ export declare const UNKNOWN_REPO = "(unknown)";
39
+ /**
40
+ * Per-repo medians of active_seconds and peak_rss_mb over lanes that carry a
41
+ * run_size. Lanes without one (older records, runs not yet measured) are left
42
+ * out, and so are lanes whose active_seconds is wall time (Remote Control),
43
+ * which are counted in wall_clock_lanes_excluded. Sorted by repo.
44
+ */
45
+ export declare function runSizeMediansByRepo(lanes: readonly Pick<LaneRecord, "run_size" | "work_requirements">[]): RepoRunSizeMedian[];
46
+ //# sourceMappingURL=run-size.d.ts.map