@nredd/pi-resource-sampler 0.1.1 → 0.2.0

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.
package/README.md CHANGED
@@ -4,6 +4,9 @@ Pi-independent, dependency-free ESM library for passive host resource dashboards
4
4
  `@nredd/pi-resource-sampler` is not a Pi extension. No tools, timers, hooks, output or policy are
5
5
  registered. Runs on Node >=22.14 and Bun.
6
6
 
7
+ Unreleased source (planned `0.2.0`): native Darwin interval CPU/footprint and host used/swap metrics.
8
+ Published `0.1.1` still lacks them; release and consumer-pin steps remain owner-gated.
9
+
7
10
  Upgrade from `0.1.0`, which is unsafe: on Darwin it reported `ps -c -o comm`, the basename of argv[0],
8
11
  so a launcher-chosen argv[0] or Node `process.title` (e.g. `npm exec <package> mcp`) leaked into
9
12
  `processes[].name`. On Bun, host `cpu` read lazily populated `os.cpus()` objects, so the second sample
@@ -29,7 +32,7 @@ Semantics:
29
32
  - `cpu`: aggregate host CPU counter delta, 0..100. Core count/model changes, individual counter
30
33
  rollback, initial samples, invalid intervals and counters that have not advanced are `warming`,
31
34
  never fabricated zero. Uses Node's native `os.cpus()` counters, not load average.
32
- - `processes[].cpu`: Linux user+system counter delta divided by monotonic elapsed milliseconds.
35
+ - `processes[].cpu`: cumulative user+system counter delta divided by monotonic elapsed milliseconds.
33
36
  100 means one logical core, multi-threaded processes can exceed 100. Linux `CLK_TCK` is read
34
37
  once with fixed `/usr/bin/getconf CLK_TCK`; no assumed tick rate or RSS page size.
35
38
  - Linux identity includes the exact `/proc/PID/stat` start tick string. Read stat/exe/status/stat and
@@ -37,20 +40,44 @@ Semantics:
37
40
  invalidate their old baselines. New/reused PIDs and counter resets warm rather than showing zero.
38
41
  - `cpu` copies every `os.cpus()` counter when sampled. Bun returns lazy placeholders that read native
39
42
  counters on first property access; an unread stored baseline would describe a later instant.
40
- - Darwin uses only `/bin/ps -A -o pid=,ppid=,lstart=,time=,rss=,ucomm=` with `LC_ALL=C`.
41
- Actual macOS observation: `time` prints hundredths (e.g. `185:32.40`), but `lstart` prints only
42
- seconds (`Sat Oct 3 01:49:05 2026`). That cannot rule out PID reuse within one second, so Darwin
43
- process interval CPU is explicitly `unavailable`. No decaying `%cpu` is relabelled as an interval.
44
- RSS/name/parent PID remain useful. No native helper until this limitation justifies one separately.
43
+ - Darwin enumerates metadata with fixed `/bin/ps -A -o pid=,ppid=,lstart=,time=,rss=,ucomm=`
44
+ and `LC_ALL=C`. Builtin FFI (Node >=26.1, Bun; toolchain pin in root `.bun-version`) then reads fixed symbols
45
+ `proc_pidinfo`, `proc_pid_rusage` and `mach_timebase_info` from `/usr/lib/libproc.dylib`, without
46
+ root, a compiler, addon or new binary/package dependency. Import/construction does not load FFI.
47
+ Node emits its builtin experimental-FFI warning on first use; Bun does not. Node 22-25 keeps
48
+ metadata/RSS but explicitly unavailable CPU/footprint. ABI access is restricted to Darwin arm64/x64.
49
+ - Native Darwin identity includes PID, kernel process-start absolute ticks, microsecond start time,
50
+ PPID and exact `p_comm` bytes. Rusage reads bracket metadata; changed start/exit state or counter
51
+ rollback rejects the native read. Same-second PID reuse cannot authenticate an old baseline even
52
+ with identical parent/name and nondecreasing CPU. Each observation has its own monotonic timestamp.
53
+ Identity/parent/name changes, negative deltas, nonpositive/nonfinite intervals and native intervals
54
+ over 60s warm instead of fabricating CPU. Native CPU counters are Mach ticks converted using the
55
+ kernel timebase (125/3 ns per tick on this Apple Silicon Mac), NOT assumed nanoseconds.
56
+ - `processes[].footprint` is an optional Darwin metric from `ri_phys_footprint`, including compressed
57
+ memory. Native `rssBytes` comes from `ri_resident_size`. Inaccessible/exited/reused PIDs or exhausted
58
+ native budgets retain the enumerated metadata/RSS row with unavailable CPU/footprint; unsupported
59
+ runtimes do the same. No failed footprint is encoded as zero. `ps` fallback identity has only
60
+ whole-second precision, so it NEVER supplies interval CPU. No decaying `%cpu` is relabelled.
45
61
  - `wallTimeMs` labels the start; `monotonicTimeMs` controls intervals. Per-process reads have their own
46
62
  monotonic timestamps internally; the scan is not atomic. `durationMs` includes collection.
47
- - `memory.freeBytes` means free, NOT available or pressure. `loadAverage` is load, NOT percent.
63
+ - `memory.freeBytes` means free, NOT available or pressure. Darwin adds optional v1 `memory.usage`
64
+ and `memory.swap` metrics. `usage.value.usedBytes` estimates resident App + Wired + Compressed RAM:
65
+ `(Anonymous pages - Pages purgeable + Pages wired down + Pages occupied by compressor) * page size`
66
+ from fixed `/usr/bin/vm_stat` output. The page size comes from its header, never an assumed 4KiB.
67
+ `availableBytes` is total minus that estimate (reclaimable cache included), NOT a pressure score or
68
+ an allocation guarantee. Compressor occupancy is physical RAM, not `Pages stored in compressor`.
69
+ Swap used/allocated bytes come from fixed `/usr/sbin/sysctl vm.swapusage` (binary MiB).
70
+ Invalid/missing/over-budget counters are `unavailable`, never zero or a silent total-free fallback.
71
+ Older producers and non-Darwin platforms omit these additive fields. Linux's existing free-page/PSI
72
+ semantics are unchanged; this library did not expose Linux MemAvailable.
73
+ Both helpers share the existing scan budget, fixed environment, output bound and awaited reaping.
74
+ `loadAverage` is load, NOT percent.
48
75
  Linux memory PSI preserves native `some`/optional `full`, avg10/60/300 percentages and cumulative
49
76
  stall microseconds. Missing/invalid PSI is unavailable. Other platforms explicitly have no PSI.
50
77
  - `processes[].name` is an executable basename from kernel metadata. It excludes argv, environment,
51
78
  process title and Linux comm, but it is still untrusted metadata that the process or its launcher can
52
79
  choose (see the last item). `""` means unavailable, not a process called nothing:
53
- - Darwin: `ucomm`, which `ps` prints from kinfo `p_comm`. XNU writes it only at exec, from the
80
+ - Darwin: native `proc_bsdinfo.pbi_comm`, or `ps ucomm` from kinfo `p_comm`. XNU writes it at exec, from the
54
81
  looked-up executable file name, truncated to 16 bytes (`Google Chrome He`). `ps -c -o comm` is
55
82
  argv[0] and is NOT used.
56
83
  - Linux: basename of `readlink /proc/PID/exe` (` (deleted)` marker removed), read between the two
@@ -68,13 +95,21 @@ Bounds:
68
95
 
69
96
  - Default scan budget 250ms, 2048 PIDs, 2MiB captured bytes; options allow at most 5s, 16384 PIDs,
70
97
  16MiB. Linux proc files read sequentially (concurrency one), at most 8KiB each. Directory iteration
71
- stops at the budget; Darwin output stops at the PID/output budget and reaps the fixed helper.
98
+ stops at the budget; Darwin output stops at the PID/output budget and reaps the fixed helper. Native reads charge
99
+ 8 bytes for the timebase and 328 bytes per admitted PID (two 96-byte rusage buffers and one 136-byte
100
+ metadata buffer), including failed calls, to that SAME byte budget. Only `pbi_comm` and numeric
101
+ fields are inspected; `pbi_name`, arguments and environment are never decoded or exported. Native
102
+ syscalls are synchronous/non-preemptible like `os.cpus()`; admission is checked between reads.
72
103
  - `/proc/PID/exe` is a `readlink`, which Node and Bun cannot cap: each call copies up to PATH_MAX
73
104
  (4096) bytes into a fixed runtime buffer before the length is known. That fixed per-call syscall
74
105
  copy can exceed the remaining budget; the logical budget cannot. A target longer than the remainder
75
- is charged the remainder and its name dropped (`""`, `byte-limit`), so `bytesRead <= maxBytes`. A
76
- target filling the 4096-byte buffer may be truncated: Node returns it silently and the name is
77
- dropped too (`file-byte-limit`); Bun refuses it with `ENAMETOOLONG`, so the name is `""`.
106
+ is charged the remainder, so `bytesRead <= maxBytes`, and the budget is then exhausted: that
107
+ process's `status` read is refused, so the whole process is skipped
108
+ (`process-unreadable-or-changed`, `byte-limit`), not kept with an empty name, and the scan stops.
109
+ A target filling the 4096-byte buffer may be truncated: Node returns it silently, the name is
110
+ dropped (`""`, `file-byte-limit`) and the process is kept. Bun's readlink source refuses such a
111
+ target with `ENAMETOOLONG`, which would take the unreadable-link path (`""`, no reason); that Bun
112
+ path was read in source only, never executed here.
78
113
  - `coverage.complete`, `enumerated`, `sampled`, `skipped`, `bytesRead` and reasons describe partial
79
114
  coverage explicitly. `enumerated` is encountered rows, not total processes when partial. Truncation
80
115
  is not a host-wide top-process ranking. OS enumeration order may favor the same subset each time.
@@ -84,6 +119,11 @@ Bounds:
84
119
  immediate SIGKILL on abort/deadline/cap, and resolve only on close. No persistent children or workers.
85
120
  - Unsupported platforms keep native host metrics but report process coverage unavailable.
86
121
 
122
+ macOS measurement/definition comparison, native ABI evidence and future publication checklist:
123
+ [here](../../docs/mon-accuracy.md). Process `rssBytes` still excludes compressed pages; it is not
124
+ Activity Monitor's physical footprint; use the separate `footprint` metric for that comparison.
125
+ Names remain executable names, so Pi commonly appears as `node`.
126
+
87
127
  Local overhead observation (2026-10-22, Darwin arm64, Node 26.12.0, 10 logical CPUs, 16GiB RAM,
88
128
  load about 6, not a quiet-runner benchmark): ten scans of 557 processes took 17.5-24.9ms each,
89
129
  about 41.3KB captured, all complete. The Node collector consumed 25.7ms CPU total across ten
@@ -93,11 +133,27 @@ scans (2.6ms/sample, excludes helper CPU); a separate fixed `ps` invocation meas
93
133
  real-input gate and reports its snapshot duration/coverage.
94
134
 
95
135
  Development: `npm run check --workspace @nredd/pi-resource-sampler` (single-worker tests, including
96
- actual host samples and child cleanup). `test/runtime.test.ts` runs under both Vitest (Node) and
97
- `bun test`: it starts a child whose argv[0], argv, environment, process title and (Linux) comm hold a
98
- random secret, proves the 0.1.0 source exposes it, then requires no 12-character fragment in the
99
- snapshot, plus three real CPU samples. `make check-resource-sampler-contract` builds and exercises
100
- an isolated installed tarball, with no Pi or siblings. Both run on existing macOS/Linux CI jobs.
136
+ actual host samples and child cleanup). The full suite runs through Vitest on Node and pinned Bun.
137
+ Native failure tests inject fixed bindings through the same lazy loader seam used by production,
138
+ not a Node-shaped global builtin mock; they do not require the runtime's real FFI to exist.
139
+ `test/runtime.test.ts` runs under both engines: it starts a child whose argv[0], argv, environment, process title and (Linux) comm hold a
140
+ random secret, proves the 0.1.0 source exposes it, then requires the child in the snapshot and no
141
+ 12-character fragment of the secret, plus three real CPU samples. Everything after spawn, readiness
142
+ included, is followed by SIGTERM, then SIGKILL, with a bounded wait for the runtime's exit status
143
+ of that exact child (never a PID probe); a cleanup failure is reported alongside the original error
144
+ (`AggregateError`), never instead of it. Regressions make readiness and the negative control fail
145
+ and require the child reaped, including a child that ignores SIGTERM and needs SIGKILL, and inject a
146
+ cleanup failure to require both errors. This cleanup is in-process only: if the test worker itself
147
+ is SIGKILLed, no JavaScript runs and the child outlives it. The packed contract probe below instead
148
+ runs in its own process group, which the gate kills on its Python timeout or `KeyboardInterrupt`
149
+ while the leader is unreaped; an already reaped leader, or an unhandled SIGTERM/SIGHUP or SIGKILL of
150
+ the gate, skips that cleanup and may leave members behind. The privacy
151
+ check samples with the library maxima (5s, 16384 PIDs, 16MiB) and never accepts a missing child as
152
+ a pass: on a host whose processes exceed those bounds, or whose enumeration reaches the child only
153
+ after them, it fails with the snapshot's coverage in the error. On Linux each process costs two
154
+ `stat` reads, the `/proc/PID/exe` target bytes and `status`, so the byte bound can bind before the
155
+ PID bound. `make check-resource-sampler-contract` builds and exercises an isolated installed
156
+ tarball, with no Pi or siblings. Both run on existing macOS/Linux CI jobs.
101
157
  `dist` contains compiled ESM and declarations; the exact packed payload is contract-pinned. No install
102
- scripts or runtime dependencies. New npm-name ownership bootstrap requires the owner's interactive
103
- 2FA/staged publication and trusted-publisher setup; nothing is published automatically by this PR.
158
+ scripts or runtime dependencies. Releases publish through `publish.yml` with npm provenance; see
159
+ [releases](../../docs/releases.md).
package/dist/collect.d.ts CHANGED
@@ -10,10 +10,23 @@ export declare class Budget {
10
10
  enumerated: number;
11
11
  skipped: number;
12
12
  readonly reasons: Set<string>;
13
+ /**
14
+ * Initialize one scan's limits.
15
+ * @param deadline Absolute monotonic deadline in milliseconds.
16
+ * @param maxBytes Maximum captured/charged bytes.
17
+ * @param maxPids Maximum enumerated PIDs.
18
+ * @param signal Caller-owned cancellation signal.
19
+ */
13
20
  constructor(deadline: number, maxBytes: number, maxPids: number, signal: AbortSignal);
21
+ /** @returns Remaining admission milliseconds; throws when cancelled. */
14
22
  remaining(): number;
23
+ /** @returns Whether time/bytes remain, recording exhausted limits; throws when cancelled. */
15
24
  ready(): boolean;
16
- /** Fixed-size proc read: no unbounded readFile allocation, and always await handle closure. */
25
+ /**
26
+ * Read a fixed-size proc file and always await handle closure.
27
+ * @param path Fixed proc file path for an admitted PID or pressure source.
28
+ * @returns Complete UTF-8 contents; rejects on exhaustion/truncation/read failure/abort.
29
+ */
17
30
  read(path: string): Promise<string>;
18
31
  /**
19
32
  * Linux executable basename, or "" when the exe link is unreadable (other users' processes without
@@ -21,20 +34,48 @@ export declare class Budget {
21
34
  * outward. Node and Bun cannot cap readlink below their fixed PATH_MAX buffer, so the length is only
22
35
  * known after the syscall: a target beyond the remaining budget is charged the remainder and dropped,
23
36
  * keeping `bytesRead <= maxBytes`. Node returns a full buffer silently truncated, so that is dropped too.
37
+ * @param path Admitted PID's /proc/PID/exe link path.
38
+ * @returns Safe basename, or empty string when unavailable; aborts propagate.
24
39
  */
25
40
  executable(path: string): Promise<string>;
26
41
  }
27
- /** Fixed executable/argv only. Bound capture, kill on cancellation/deadline, await close/reaping. */
42
+ /**
43
+ * Run a fixed helper with bounded capture, kill on cancellation/deadline and await close/reaping.
44
+ * @param executable Fixed absolute OS helper path.
45
+ * @param args Fixed helper arguments, never target process arguments.
46
+ * @param budget Shared admission and capture accounting.
47
+ * @param maxLines Maximum complete stdout rows to admit.
48
+ * @returns Captured text and whether the command completed without truncation/failure.
49
+ */
28
50
  export declare function command(executable: string, args: string[], budget: Budget, maxLines?: number): Promise<{
29
51
  text: string;
30
52
  complete: boolean;
31
53
  }>;
32
- /** Linux scan is sequential and closes the directory even on cancellation. */
54
+ /**
55
+ * Scan Linux sequentially and close the directory even on cancellation.
56
+ * @param budget Shared scan limits and cancellation.
57
+ * @param hz Host CLK_TCK rate in ticks per second.
58
+ * @returns Validated identity-bracketed process counters; aborts propagate.
59
+ */
33
60
  export declare function linuxProcesses(budget: Budget, hz: number): Promise<ProcessCounter[]>;
34
61
  /**
35
62
  * Fixed metadata-only ps format. `ucomm` prints kinfo `p_comm`, never `comm`: `ps -c -o comm` shows the
36
63
  * basename of argv[0], which any launcher picks and Node's `process.title` rewrites in place.
64
+ * @param budget Shared helper/native scan limits and cancellation.
65
+ * @returns Bounded fallback rows enriched with accessible native metrics; aborts propagate.
37
66
  */
38
67
  export declare function darwinProcesses(budget: Budget): Promise<ProcessCounter[]>;
39
- /** PSI is optional and platform-specific; absence is not zero pressure. */
68
+ /**
69
+ * Run fixed metadata-only helpers sharing the process deadline, cap and awaited reaping.
70
+ * @param budget Shared helper capture budget and cancellation.
71
+ * @param total Host physical RAM in bytes.
72
+ * @returns Explicit available/unavailable host usage and swap metrics.
73
+ */
74
+ export declare function darwinHostMemory(budget: Budget, total: number): Promise<Pick<ResourceSnapshot["memory"], "usage" | "swap">>;
75
+ /**
76
+ * Collect optional platform-specific PSI; absence is not zero pressure.
77
+ * @param budget Shared file-read budget and cancellation.
78
+ * @param platform Host platform identifier.
79
+ * @returns Linux PSI availability or explicit unsupported state; aborts propagate.
80
+ */
40
81
  export declare function pressure(budget: Budget, platform: string): Promise<ResourceSnapshot["pressure"]>;
package/dist/collect.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { open, opendir, readlink } from "node:fs/promises";
3
3
  import { performance } from "node:perf_hooks";
4
- import { darwinProcess, executableName, linuxRss, linuxStat, psi } from "./counters.js";
4
+ import { darwinMemory, darwinProcess, darwinSwap, executableName, linuxRss, linuxStat, psi, } from "./counters.js";
5
+ import { darwinNativeProcesses } from "./darwin.js";
5
6
  /** Linux PATH_MAX: Node (libuv `pathconf`) and Bun (`PathBuffer`) readlink buffer size on Linux. */
6
7
  const LINK_BUFFER_BYTES = 4096;
7
8
  /** Per-scan mutable budget, never shared between sampler instances. */
@@ -14,16 +15,25 @@ export class Budget {
14
15
  enumerated = 0;
15
16
  skipped = 0;
16
17
  reasons = new Set();
18
+ /**
19
+ * Initialize one scan's limits.
20
+ * @param deadline Absolute monotonic deadline in milliseconds.
21
+ * @param maxBytes Maximum captured/charged bytes.
22
+ * @param maxPids Maximum enumerated PIDs.
23
+ * @param signal Caller-owned cancellation signal.
24
+ */
17
25
  constructor(deadline, maxBytes, maxPids, signal) {
18
26
  this.deadline = deadline;
19
27
  this.maxBytes = maxBytes;
20
28
  this.maxPids = maxPids;
21
29
  this.signal = signal;
22
30
  }
31
+ /** @returns Remaining admission milliseconds; throws when cancelled. */
23
32
  remaining() {
24
33
  this.signal.throwIfAborted();
25
34
  return Math.max(0, this.deadline - performance.now());
26
35
  }
36
+ /** @returns Whether time/bytes remain, recording exhausted limits; throws when cancelled. */
27
37
  ready() {
28
38
  if (this.remaining() <= 0)
29
39
  this.reasons.add("deadline");
@@ -31,7 +41,11 @@ export class Budget {
31
41
  this.reasons.add("byte-limit");
32
42
  return this.remaining() > 0 && this.bytesRead < this.maxBytes;
33
43
  }
34
- /** Fixed-size proc read: no unbounded readFile allocation, and always await handle closure. */
44
+ /**
45
+ * Read a fixed-size proc file and always await handle closure.
46
+ * @param path Fixed proc file path for an admitted PID or pressure source.
47
+ * @returns Complete UTF-8 contents; rejects on exhaustion/truncation/read failure/abort.
48
+ */
35
49
  async read(path) {
36
50
  if (!this.ready())
37
51
  throw new Error("budget exhausted");
@@ -60,6 +74,8 @@ export class Budget {
60
74
  * outward. Node and Bun cannot cap readlink below their fixed PATH_MAX buffer, so the length is only
61
75
  * known after the syscall: a target beyond the remaining budget is charged the remainder and dropped,
62
76
  * keeping `bytesRead <= maxBytes`. Node returns a full buffer silently truncated, so that is dropped too.
77
+ * @param path Admitted PID's /proc/PID/exe link path.
78
+ * @returns Safe basename, or empty string when unavailable; aborts propagate.
63
79
  */
64
80
  async executable(path) {
65
81
  if (!this.ready())
@@ -87,7 +103,14 @@ export class Budget {
87
103
  return executableName(target.toString("utf8"));
88
104
  }
89
105
  }
90
- /** Fixed executable/argv only. Bound capture, kill on cancellation/deadline, await close/reaping. */
106
+ /**
107
+ * Run a fixed helper with bounded capture, kill on cancellation/deadline and await close/reaping.
108
+ * @param executable Fixed absolute OS helper path.
109
+ * @param args Fixed helper arguments, never target process arguments.
110
+ * @param budget Shared admission and capture accounting.
111
+ * @param maxLines Maximum complete stdout rows to admit.
112
+ * @returns Captured text and whether the command completed without truncation/failure.
113
+ */
91
114
  export async function command(executable, args, budget, maxLines = Number.POSITIVE_INFINITY) {
92
115
  if (!budget.ready())
93
116
  return { text: "", complete: false };
@@ -99,11 +122,17 @@ export async function command(executable, args, budget, maxLines = Number.POSITI
99
122
  const buffers = [];
100
123
  let complete = true;
101
124
  let lines = 0;
125
+ /**
126
+ * Terminate the helper and mark capture incomplete.
127
+ * @param reason Coverage reason to record.
128
+ * @returns Nothing; completion still waits for close.
129
+ */
102
130
  const stop = (reason) => {
103
131
  complete = false;
104
132
  budget.reasons.add(reason);
105
133
  child.kill("SIGKILL");
106
134
  };
135
+ /** @returns Nothing; terminate the helper after shared cancellation. */
107
136
  const abort = () => stop("cancelled");
108
137
  const timer = setTimeout(() => stop("deadline"), budget.remaining());
109
138
  budget.signal.addEventListener("abort", abort, { once: true });
@@ -152,7 +181,12 @@ export async function command(executable, args, budget, maxLines = Number.POSITI
152
181
  });
153
182
  });
154
183
  }
155
- /** Linux scan is sequential and closes the directory even on cancellation. */
184
+ /**
185
+ * Scan Linux sequentially and close the directory even on cancellation.
186
+ * @param budget Shared scan limits and cancellation.
187
+ * @param hz Host CLK_TCK rate in ticks per second.
188
+ * @returns Validated identity-bracketed process counters; aborts propagate.
189
+ */
156
190
  export async function linuxProcesses(budget, hz) {
157
191
  const result = [];
158
192
  const directory = await opendir("/proc");
@@ -190,6 +224,8 @@ export async function linuxProcesses(budget, hz) {
190
224
  /**
191
225
  * Fixed metadata-only ps format. `ucomm` prints kinfo `p_comm`, never `comm`: `ps -c -o comm` shows the
192
226
  * basename of argv[0], which any launcher picks and Node's `process.title` rewrites in place.
227
+ * @param budget Shared helper/native scan limits and cancellation.
228
+ * @returns Bounded fallback rows enriched with accessible native metrics; aborts propagate.
193
229
  */
194
230
  export async function darwinProcesses(budget) {
195
231
  const { text } = await command("/bin/ps", ["-A", "-o", "pid=,ppid=,lstart=,time=,rss=,ucomm="], budget, budget.maxPids);
@@ -210,9 +246,34 @@ export async function darwinProcesses(budget) {
210
246
  budget.reasons.add("malformed-process-row");
211
247
  }
212
248
  }
213
- return result;
249
+ return darwinNativeProcesses(result, budget);
250
+ }
251
+ /**
252
+ * Run fixed metadata-only helpers sharing the process deadline, cap and awaited reaping.
253
+ * @param budget Shared helper capture budget and cancellation.
254
+ * @param total Host physical RAM in bytes.
255
+ * @returns Explicit available/unavailable host usage and swap metrics.
256
+ */
257
+ export async function darwinHostMemory(budget, total) {
258
+ const vm = await command("/usr/bin/vm_stat", [], budget);
259
+ const usage = vm.complete ? darwinMemory(vm.text, total) : null;
260
+ const swap = await command("/usr/sbin/sysctl", ["vm.swapusage"], budget);
261
+ const parsedSwap = swap.complete ? darwinSwap(swap.text) : null;
262
+ return {
263
+ usage: usage
264
+ ? { state: "available", value: usage }
265
+ : { state: "unavailable", reason: "vm_stat invalid, unavailable or over budget" },
266
+ swap: parsedSwap
267
+ ? { state: "available", value: parsedSwap }
268
+ : { state: "unavailable", reason: "swapusage invalid, unavailable or over budget" },
269
+ };
214
270
  }
215
- /** PSI is optional and platform-specific; absence is not zero pressure. */
271
+ /**
272
+ * Collect optional platform-specific PSI; absence is not zero pressure.
273
+ * @param budget Shared file-read budget and cancellation.
274
+ * @param platform Host platform identifier.
275
+ * @returns Linux PSI availability or explicit unsupported state; aborts propagate.
276
+ */
216
277
  export async function pressure(budget, platform) {
217
278
  if (platform !== "linux")
218
279
  return { source: "unsupported", reason: "no comparable native PSI metric on this platform" };
@@ -1,5 +1,13 @@
1
1
  import type { CpuInfo } from "node:os";
2
2
  import type { Metric, PsiLine } from "./types.js";
3
+ /** A >60s native interval is stale/suspend/anomaly territory for ~2s dashboard polling; warm anew.
4
+ * Linux intervals retain their existing semantics and are not subject to this Darwin-only limit.
5
+ */
6
+ export declare const MAX_NATIVE_INTERVAL_MS = 60000;
7
+ /** sysctl vm.swapusage reports binary MiB, including fractional values. */
8
+ export declare const BYTES_PER_MEBIBYTE: number;
9
+ /** Three separately rounded hundredth-MiB fields can disagree; preserve the existing 0.02MiB bound. */
10
+ export declare const SWAP_ROUNDING_TOLERANCE_BYTES: number;
3
11
  /** Internal raw process counter with a per-read monotonic timestamp. */
4
12
  export interface ProcessCounter {
5
13
  pid: number;
@@ -9,35 +17,95 @@ export interface ProcessCounter {
9
17
  rssBytes: number;
10
18
  cpuMs: number;
11
19
  at: number;
20
+ /** Darwin native start identity and cumulative counters were read successfully. */
21
+ strongIdentity?: true;
22
+ footprintBytes?: number;
12
23
  }
13
24
  /**
14
25
  * Copy counters immediately. Bun's `os.cpus()` returns lazy placeholders that read native counters on
15
26
  * first property access, so a stored but unread array would silently describe a later instant.
27
+ * @param list Runtime CPU records whose lazy properties must be forced now.
28
+ * @returns Detached per-core counter copies.
16
29
  */
17
30
  export declare function cpuSnapshot(list: readonly CpuInfo[]): CpuInfo[];
18
- /** Compute an aggregate interval, validating each core and each counter before summing. */
31
+ /**
32
+ * Compute an aggregate interval, validating each core and counter before summing.
33
+ * @param previous Previous per-core snapshot, if any.
34
+ * @param current Current per-core snapshot.
35
+ * @returns Host utilization in 0..100, or warming for invalid/nonadvancing counters.
36
+ */
19
37
  export declare function hostCpu(previous: CpuInfo[] | undefined, current: CpuInfo[]): Metric<number>;
20
- /** CPU milliseconds divided by monotonic wall milliseconds, not a lifetime/decaying ps average. */
38
+ /**
39
+ * Divide CPU milliseconds by monotonic wall milliseconds, not a lifetime/decaying ps average.
40
+ * @param previous Previous authenticated process observation, if present.
41
+ * @param current Current cumulative CPU/identity observation.
42
+ * @returns Interval percentage (100 per core), or warming for reuse/reset/invalid intervals.
43
+ */
21
44
  export declare function processCpu(previous: ProcessCounter | undefined, current: ProcessCounter): Metric<number>;
22
- /** Bound display names by code point and replace terminal controls; directories never leave the parser. */
45
+ /**
46
+ * Bound display names by code point and replace terminal controls; discard directories.
47
+ * @param value Untrusted executable path or basename.
48
+ * @returns At most 128 display-safe basename code points.
49
+ */
23
50
  export declare function safeName(value: string): string;
24
- /** Basename of a Linux `/proc/PID/exe` target, without the kernel's unlinked-file marker. */
51
+ /**
52
+ * Strip the kernel's unlinked-file marker from a Linux executable link.
53
+ * @param target Untrusted /proc/PID/exe link target.
54
+ * @returns Sanitized executable basename without the deleted suffix.
55
+ */
25
56
  export declare function executableName(target: string): string;
26
57
  /**
27
58
  * Parse Linux stat, skipping the parenthesized comm safely (embedded spaces and ')' characters). comm is
28
59
  * NOT a name source: processes rewrite it (`prctl(PR_SET_NAME)`, `/proc/self/comm`, Node's
29
60
  * `process.title`). `name` stays ""; callers derive it from `/proc/PID/exe`.
61
+ * @param text Complete proc stat row.
62
+ * @param hz Host CLK_TCK rate in ticks per second.
63
+ * @param at Monotonic observation milliseconds.
64
+ * @returns Parsed identity/CPU counters with unknown name/RSS, or null for invalid data.
30
65
  */
31
66
  export declare function linuxStat(text: string, hz: number, at: number): ProcessCounter | null;
32
- /** RSS comes from status in KiB, avoiding an assumed host page size. */
67
+ /**
68
+ * Read RSS from status in KiB, avoiding an assumed host page size.
69
+ * @param text Complete proc status text.
70
+ * @returns Resident bytes, or null when absent/invalid.
71
+ */
33
72
  export declare function linuxRss(text: string): number | null;
34
73
  /**
35
74
  * Parse `ps -o pid=,ppid=,lstart=,time=,rss=,ucomm=`. `ucomm` is the kernel's `p_comm`, written only at
36
75
  * exec from the executable file name (at most 16 bytes); it is not argv[0] or the process title.
37
76
  * Darwin lstart has only one-second identity precision; do not derive interval CPU from it.
77
+ * @param line One fixed-format C-locale ps row.
78
+ * @param at Monotonic observation milliseconds.
79
+ * @returns Metadata/RSS fallback with no native CPU baseline, or null for malformed data.
38
80
  */
39
81
  export declare function darwinProcess(line: string, at: number): ProcessCounter | null;
40
- /** Parse native PSI percentages and cumulative stall microseconds, rejecting malformed values. */
82
+ /**
83
+ * vm_stat counters are pages, with the page size in the header (16KiB on Apple Silicon).
84
+ * App resident pages = anonymous - purgeable; add wired and physical compressor pages, NOT pages
85
+ * stored in the compressor. Available here means total minus this used estimate, not pressure.
86
+ * @param text C-locale vm_stat output including its page-size header.
87
+ * @param total Host physical RAM in bytes.
88
+ * @returns Validated App+Wired+Compressed usage and its complement, or null on invalid data.
89
+ */
90
+ export declare function darwinMemory(text: string, total: number): {
91
+ usedBytes: number;
92
+ availableBytes: number;
93
+ basis: "app+wired+compressed";
94
+ } | null;
95
+ /**
96
+ * Parse sysctl's fixed C-locale swapusage format (binary MiB, including fractions).
97
+ * @param text Fixed sysctl vm.swapusage output.
98
+ * @returns Rounded used/allocated bytes, or null for malformed or inconsistent counters.
99
+ */
100
+ export declare function darwinSwap(text: string): {
101
+ usedBytes: number;
102
+ totalBytes: number;
103
+ } | null;
104
+ /**
105
+ * Parse native PSI percentages and cumulative stall microseconds.
106
+ * @param text Linux memory pressure rows.
107
+ * @returns Valid some/optional full counters, or null for malformed data.
108
+ */
41
109
  export declare function psi(text: string): {
42
110
  some: PsiLine;
43
111
  full: PsiLine | null;
package/dist/counters.js CHANGED
@@ -1,7 +1,19 @@
1
1
  import { basename } from "node:path";
2
+ /** A >60s native interval is stale/suspend/anomaly territory for ~2s dashboard polling; warm anew.
3
+ * Linux intervals retain their existing semantics and are not subject to this Darwin-only limit.
4
+ */
5
+ export const MAX_NATIVE_INTERVAL_MS = 60_000;
6
+ /** sysctl vm.swapusage reports binary MiB, including fractional values. */
7
+ export const BYTES_PER_MEBIBYTE = 1024 ** 2;
8
+ /** Three separately rounded hundredth-MiB fields can disagree; preserve the existing 0.02MiB bound. */
9
+ export const SWAP_ROUNDING_TOLERANCE_BYTES = 0.02 * BYTES_PER_MEBIBYTE;
10
+ /** Each required vm_stat counter must occur exactly once; duplicates are ambiguous, not additive. */
11
+ const VM_COUNTER_OCCURRENCES = 1;
2
12
  /**
3
13
  * Copy counters immediately. Bun's `os.cpus()` returns lazy placeholders that read native counters on
4
14
  * first property access, so a stored but unread array would silently describe a later instant.
15
+ * @param list Runtime CPU records whose lazy properties must be forced now.
16
+ * @returns Detached per-core counter copies.
5
17
  */
6
18
  export function cpuSnapshot(list) {
7
19
  return list.map(({ model, speed, times }) => ({
@@ -10,7 +22,12 @@ export function cpuSnapshot(list) {
10
22
  times: { user: times.user, nice: times.nice, sys: times.sys, idle: times.idle, irq: times.irq },
11
23
  }));
12
24
  }
13
- /** Compute an aggregate interval, validating each core and each counter before summing. */
25
+ /**
26
+ * Compute an aggregate interval, validating each core and counter before summing.
27
+ * @param previous Previous per-core snapshot, if any.
28
+ * @param current Current per-core snapshot.
29
+ * @returns Host utilization in 0..100, or warming for invalid/nonadvancing counters.
30
+ */
14
31
  export function hostCpu(previous, current) {
15
32
  if (!previous || previous.length !== current.length || current.length === 0) {
16
33
  return { state: "warming", reason: "initial sample or CPU topology changed" };
@@ -35,14 +52,22 @@ export function hostCpu(previous, current) {
35
52
  ? { state: "available", value: ((total - idle) / total) * 100 }
36
53
  : { state: "warming", reason: "CPU counters have not advanced" };
37
54
  }
38
- /** CPU milliseconds divided by monotonic wall milliseconds, not a lifetime/decaying ps average. */
55
+ /**
56
+ * Divide CPU milliseconds by monotonic wall milliseconds, not a lifetime/decaying ps average.
57
+ * @param previous Previous authenticated process observation, if present.
58
+ * @param current Current cumulative CPU/identity observation.
59
+ * @returns Interval percentage (100 per core), or warming for reuse/reset/invalid intervals.
60
+ */
39
61
  export function processCpu(previous, current) {
40
- if (!previous || previous.identity !== current.identity)
62
+ if (!previous ||
63
+ previous.identity !== current.identity ||
64
+ (current.strongIdentity && (previous.parentPid !== current.parentPid || previous.name !== current.name)))
41
65
  return { state: "warming", reason: "initial sample or PID reused" };
42
66
  const elapsed = current.at - previous.at;
43
67
  const cpu = current.cpuMs - previous.cpuMs;
44
68
  if (!Number.isFinite(elapsed) ||
45
69
  elapsed <= 0 ||
70
+ (current.strongIdentity && elapsed > MAX_NATIVE_INTERVAL_MS) ||
46
71
  !Number.isFinite(cpu) ||
47
72
  previous.cpuMs < 0 ||
48
73
  current.cpuMs < 0 ||
@@ -51,13 +76,21 @@ export function processCpu(previous, current) {
51
76
  }
52
77
  return { state: "available", value: (cpu / elapsed) * 100 };
53
78
  }
54
- /** Bound display names by code point and replace terminal controls; directories never leave the parser. */
79
+ /**
80
+ * Bound display names by code point and replace terminal controls; discard directories.
81
+ * @param value Untrusted executable path or basename.
82
+ * @returns At most 128 display-safe basename code points.
83
+ */
55
84
  export function safeName(value) {
56
85
  return Array.from(basename(value).replace(/[\p{C}]/gu, "?"))
57
86
  .slice(0, 128)
58
87
  .join("");
59
88
  }
60
- /** Basename of a Linux `/proc/PID/exe` target, without the kernel's unlinked-file marker. */
89
+ /**
90
+ * Strip the kernel's unlinked-file marker from a Linux executable link.
91
+ * @param target Untrusted /proc/PID/exe link target.
92
+ * @returns Sanitized executable basename without the deleted suffix.
93
+ */
61
94
  export function executableName(target) {
62
95
  return safeName(target.endsWith(" (deleted)") ? target.slice(0, -" (deleted)".length) : target);
63
96
  }
@@ -65,6 +98,10 @@ export function executableName(target) {
65
98
  * Parse Linux stat, skipping the parenthesized comm safely (embedded spaces and ')' characters). comm is
66
99
  * NOT a name source: processes rewrite it (`prctl(PR_SET_NAME)`, `/proc/self/comm`, Node's
67
100
  * `process.title`). `name` stays ""; callers derive it from `/proc/PID/exe`.
101
+ * @param text Complete proc stat row.
102
+ * @param hz Host CLK_TCK rate in ticks per second.
103
+ * @param at Monotonic observation milliseconds.
104
+ * @returns Parsed identity/CPU counters with unknown name/RSS, or null for invalid data.
68
105
  */
69
106
  export function linuxStat(text, hz, at) {
70
107
  const start = text.indexOf("(");
@@ -95,7 +132,11 @@ export function linuxStat(text, hz, at) {
95
132
  at,
96
133
  };
97
134
  }
98
- /** RSS comes from status in KiB, avoiding an assumed host page size. */
135
+ /**
136
+ * Read RSS from status in KiB, avoiding an assumed host page size.
137
+ * @param text Complete proc status text.
138
+ * @returns Resident bytes, or null when absent/invalid.
139
+ */
99
140
  export function linuxRss(text) {
100
141
  const match = /^VmRSS:\s+(\d+)\s+kB$/m.exec(text);
101
142
  if (!match?.[1])
@@ -107,6 +148,9 @@ export function linuxRss(text) {
107
148
  * Parse `ps -o pid=,ppid=,lstart=,time=,rss=,ucomm=`. `ucomm` is the kernel's `p_comm`, written only at
108
149
  * exec from the executable file name (at most 16 bytes); it is not argv[0] or the process title.
109
150
  * Darwin lstart has only one-second identity precision; do not derive interval CPU from it.
151
+ * @param line One fixed-format C-locale ps row.
152
+ * @param at Monotonic observation milliseconds.
153
+ * @returns Metadata/RSS fallback with no native CPU baseline, or null for malformed data.
110
154
  */
111
155
  export function darwinProcess(line, at) {
112
156
  const match = /^\s*(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(\S+)\s+(\d+)\s+(.*?)\s*$/.exec(line);
@@ -119,7 +163,66 @@ export function darwinProcess(line, at) {
119
163
  return null;
120
164
  return { pid, parentPid, rssBytes, identity: `${pid}:${match[3]}`, name: safeName(match[6]), cpuMs: 0, at };
121
165
  }
122
- /** Parse native PSI percentages and cumulative stall microseconds, rejecting malformed values. */
166
+ /**
167
+ * vm_stat counters are pages, with the page size in the header (16KiB on Apple Silicon).
168
+ * App resident pages = anonymous - purgeable; add wired and physical compressor pages, NOT pages
169
+ * stored in the compressor. Available here means total minus this used estimate, not pressure.
170
+ * @param text C-locale vm_stat output including its page-size header.
171
+ * @param total Host physical RAM in bytes.
172
+ * @returns Validated App+Wired+Compressed usage and its complement, or null on invalid data.
173
+ */
174
+ export function darwinMemory(text, total) {
175
+ const [, pageSizeText] = /^Mach Virtual Memory Statistics: \(page size of (\d+) bytes\)\r?$/m.exec(text) ?? [];
176
+ const pageSize = Number(pageSizeText);
177
+ if (!Number.isSafeInteger(total) || total <= 0 || !Number.isSafeInteger(pageSize) || pageSize <= 0)
178
+ return null;
179
+ /**
180
+ * Read one uniquely present unsigned page count.
181
+ * @param name Exact vm_stat row label, excluding the colon.
182
+ * @returns Page count, or null for missing/duplicate/malformed rows.
183
+ */
184
+ const read = (name) => {
185
+ const rows = text.split("\n").filter((line) => line.startsWith(`${name}:`));
186
+ const [row] = rows;
187
+ const [, value] = rows.length === VM_COUNTER_OCCURRENCES ? (/^.*:\s+(\d+)\.\s*$/.exec(row ?? "") ?? []) : [];
188
+ const count = value === undefined ? Number.NaN : Number(value);
189
+ return Number.isSafeInteger(count) && count >= 0 ? count : null;
190
+ };
191
+ const anonymous = read("Anonymous pages");
192
+ const purgeable = read("Pages purgeable");
193
+ const wired = read("Pages wired down");
194
+ const compressed = read("Pages occupied by compressor");
195
+ if (anonymous === null || purgeable === null || wired === null || compressed === null || purgeable > anonymous)
196
+ return null;
197
+ const usedBytes = (anonymous - purgeable + wired + compressed) * pageSize;
198
+ if (!Number.isSafeInteger(usedBytes) || usedBytes < 0 || usedBytes > total)
199
+ return null;
200
+ return { usedBytes, availableBytes: total - usedBytes, basis: "app+wired+compressed" };
201
+ }
202
+ /**
203
+ * Parse sysctl's fixed C-locale swapusage format (binary MiB, including fractions).
204
+ * @param text Fixed sysctl vm.swapusage output.
205
+ * @returns Rounded used/allocated bytes, or null for malformed or inconsistent counters.
206
+ */
207
+ export function darwinSwap(text) {
208
+ const match = /^vm\.swapusage: total = (\d+\.\d+)M\s+used = (\d+\.\d+)M\s+free = (\d+\.\d+)M(?:\s+\(encrypted\))?\s*$/.exec(text);
209
+ if (!match)
210
+ return null;
211
+ const [, totalMebibytes, usedMebibytes, freeMebibytes] = match;
212
+ const totalBytes = Math.round(Number(totalMebibytes) * BYTES_PER_MEBIBYTE);
213
+ const usedBytes = Math.round(Number(usedMebibytes) * BYTES_PER_MEBIBYTE);
214
+ const freeBytes = Math.round(Number(freeMebibytes) * BYTES_PER_MEBIBYTE);
215
+ if (![totalBytes, usedBytes, freeBytes].every(Number.isSafeInteger) ||
216
+ usedBytes > totalBytes ||
217
+ Math.abs(totalBytes - usedBytes - freeBytes) > SWAP_ROUNDING_TOLERANCE_BYTES)
218
+ return null;
219
+ return { usedBytes, totalBytes };
220
+ }
221
+ /**
222
+ * Parse native PSI percentages and cumulative stall microseconds.
223
+ * @param text Linux memory pressure rows.
224
+ * @returns Valid some/optional full counters, or null for malformed data.
225
+ */
123
226
  export function psi(text) {
124
227
  const rows = new Map();
125
228
  for (const line of text.trim().split("\n")) {
@@ -0,0 +1,95 @@
1
+ import type { Budget } from "./collect.js";
2
+ import { type ProcessCounter } from "./counters.js";
3
+ /** Fixed Darwin LP64 ABI from sys/proc_info.h, sys/resource.h and mach/mach_time.h. */
4
+ export declare const DARWIN_ABI: {
5
+ /** proc_pid_rusage and mach_timebase_info return zero on success. */
6
+ readonly success: 0;
7
+ /** Kernel start/exit time zero means unset; a live process must have a nonzero start. */
8
+ readonly unsetTime: 0n;
9
+ /** C p_comm terminates at the first NUL byte, not the end of its fixed buffer. */
10
+ readonly nulByte: 0;
11
+ readonly bsd: {
12
+ /** sizeof(struct proc_bsdinfo), including fields we deliberately never decode. */
13
+ readonly bytes: 136;
14
+ /** PROC_PIDTBSDINFO flavor for proc_pidinfo. */
15
+ readonly flavor: 3;
16
+ /** This flavor has no auxiliary argument. */
17
+ readonly argument: 0n;
18
+ /** uint32_t pbi_pid byte offset. */
19
+ readonly pid: 12;
20
+ /** uint32_t pbi_ppid byte offset. */
21
+ readonly parentPid: 16;
22
+ /** char pbi_comm[MAXCOMLEN] starts here; pbi_name is NOT a name source. */
23
+ readonly comm: 48;
24
+ /** MAXCOMLEN bytes, excluding any adjacent pbi_name field. */
25
+ readonly commBytes: 16;
26
+ /** uint64_t pbi_start_tvsec byte offset. */
27
+ readonly startSeconds: 120;
28
+ /** uint64_t pbi_start_tvusec byte offset. */
29
+ readonly startMicros: 128;
30
+ };
31
+ readonly usage: {
32
+ /** sizeof(struct rusage_info_v0); later flavors are not requested. */
33
+ readonly bytes: 96;
34
+ /** RUSAGE_INFO_V0 flavor, providing CPU, footprint and start/exit identity. */
35
+ readonly flavor: 0;
36
+ /** uint64_t ri_user_time (Mach ticks) byte offset. */
37
+ readonly userTicks: 16;
38
+ /** uint64_t ri_system_time (Mach ticks) byte offset. */
39
+ readonly systemTicks: 24;
40
+ /** uint64_t ri_resident_size byte offset. */
41
+ readonly residentBytes: 64;
42
+ /** uint64_t ri_phys_footprint byte offset. */
43
+ readonly footprintBytes: 72;
44
+ /** uint64_t ri_proc_start_abstime byte offset. */
45
+ readonly startTicks: 80;
46
+ /** uint64_t ri_proc_exit_abstime byte offset. */
47
+ readonly exitTicks: 88;
48
+ };
49
+ readonly timebase: {
50
+ /** sizeof(mach_timebase_info_data_t), two uint32_t fields. */
51
+ readonly bytes: 8;
52
+ /** uint32_t numer byte offset. */
53
+ readonly numerator: 0;
54
+ /** uint32_t denom byte offset. */
55
+ readonly denominator: 4;
56
+ };
57
+ };
58
+ /** Charge every admitted fixed buffer, including failed syscalls, against the shared scan budget. */
59
+ export declare const DARWIN_NATIVE_READ_BYTES: number;
60
+ /** Convert native Mach-derived nanoseconds into the sampler's cumulative CPU milliseconds. */
61
+ export declare const NANOSECONDS_PER_MILLISECOND = 1000000;
62
+ /** The pbi_start_tvusec field must be strictly smaller than one second of microseconds. */
63
+ export declare const MICROSECONDS_PER_SECOND = 1000000n;
64
+ /** Runtime-independent fixed native bindings; the loader owns the returned library handle. */
65
+ export interface NativeCalls {
66
+ bsd(pid: number, buffer: Buffer): number;
67
+ usage(pid: number, buffer: Buffer): number;
68
+ timebase(buffer: Buffer): number;
69
+ close(): void;
70
+ }
71
+ /**
72
+ * Identity-check metadata between two rusage reads. Start absolute ticks distinguish same-second PID
73
+ * reuse; microsecond start, parent and exact p_comm bytes also participate. No sanitized-name collision
74
+ * can authenticate a baseline. Rusage CPU counters are Mach ticks; convert with mach_timebase_info,
75
+ * not an assumed nanosecond tick (Apple Silicon here reports 125/3 nanoseconds per tick).
76
+ * @param pid Expected process identifier from the bounded metadata enumeration.
77
+ * @param before First fixed rusage_info_v0 frame.
78
+ * @param bsd Intervening fixed proc_bsdinfo frame.
79
+ * @param after Second fixed rusage_info_v0 frame.
80
+ * @param at Monotonic observation time in milliseconds.
81
+ * @param ticksToNs Positive Mach timebase ratio, in nanoseconds per tick.
82
+ * @returns A strong-identity counter, or null for malformed/changed/invalid native data.
83
+ */
84
+ export declare function darwinNativeCounter(pid: number, before: Buffer, bsd: Buffer, after: Buffer, at: number, ticksToNs: number): ProcessCounter | null;
85
+ /**
86
+ * Enrich bounded ps rows with cheap native counters, retaining RSS/name rows when access fails.
87
+ * Charge all admitted fixed syscall buffers to the SAME scan budget, including unsuccessful reads.
88
+ * Synchronous syscalls, like os.cpus(), cannot be preempted; check admission before each PID.
89
+ * @param rows Bounded ps fallback rows, enriched in place only on successful native reads.
90
+ * @param budget Shared byte/deadline/abort admission state, charged even for failed syscalls.
91
+ * @param load Lazy native binding dependency; defaults to the platform's builtin FFI adapter.
92
+ * @returns The same array, retaining original rows for inaccessible or rejected PIDs.
93
+ * @throws If the shared abort signal is observed between native calls.
94
+ */
95
+ export declare function darwinNativeProcesses(rows: ProcessCounter[], budget: Budget, load?: () => NativeCalls | undefined): ProcessCounter[];
package/dist/darwin.js ADDED
@@ -0,0 +1,254 @@
1
+ import { performance } from "node:perf_hooks";
2
+ import { safeName } from "./counters.js";
3
+ /** Fixed Darwin LP64 ABI from sys/proc_info.h, sys/resource.h and mach/mach_time.h. */
4
+ export const DARWIN_ABI = {
5
+ /** proc_pid_rusage and mach_timebase_info return zero on success. */
6
+ success: 0,
7
+ /** Kernel start/exit time zero means unset; a live process must have a nonzero start. */
8
+ unsetTime: 0n,
9
+ /** C p_comm terminates at the first NUL byte, not the end of its fixed buffer. */
10
+ nulByte: 0,
11
+ bsd: {
12
+ /** sizeof(struct proc_bsdinfo), including fields we deliberately never decode. */
13
+ bytes: 136,
14
+ /** PROC_PIDTBSDINFO flavor for proc_pidinfo. */
15
+ flavor: 3,
16
+ /** This flavor has no auxiliary argument. */
17
+ argument: 0n,
18
+ /** uint32_t pbi_pid byte offset. */
19
+ pid: 12,
20
+ /** uint32_t pbi_ppid byte offset. */
21
+ parentPid: 16,
22
+ /** char pbi_comm[MAXCOMLEN] starts here; pbi_name is NOT a name source. */
23
+ comm: 48,
24
+ /** MAXCOMLEN bytes, excluding any adjacent pbi_name field. */
25
+ commBytes: 16,
26
+ /** uint64_t pbi_start_tvsec byte offset. */
27
+ startSeconds: 120,
28
+ /** uint64_t pbi_start_tvusec byte offset. */
29
+ startMicros: 128,
30
+ },
31
+ usage: {
32
+ /** sizeof(struct rusage_info_v0); later flavors are not requested. */
33
+ bytes: 96,
34
+ /** RUSAGE_INFO_V0 flavor, providing CPU, footprint and start/exit identity. */
35
+ flavor: 0,
36
+ /** uint64_t ri_user_time (Mach ticks) byte offset. */
37
+ userTicks: 16,
38
+ /** uint64_t ri_system_time (Mach ticks) byte offset. */
39
+ systemTicks: 24,
40
+ /** uint64_t ri_resident_size byte offset. */
41
+ residentBytes: 64,
42
+ /** uint64_t ri_phys_footprint byte offset. */
43
+ footprintBytes: 72,
44
+ /** uint64_t ri_proc_start_abstime byte offset. */
45
+ startTicks: 80,
46
+ /** uint64_t ri_proc_exit_abstime byte offset. */
47
+ exitTicks: 88,
48
+ },
49
+ timebase: {
50
+ /** sizeof(mach_timebase_info_data_t), two uint32_t fields. */
51
+ bytes: 8,
52
+ /** uint32_t numer byte offset. */
53
+ numerator: 0,
54
+ /** uint32_t denom byte offset. */
55
+ denominator: 4,
56
+ },
57
+ };
58
+ /** Rusage reads bracket the single metadata read to reject identity changes during collection. */
59
+ const RUSAGE_READS_PER_PID = 2;
60
+ /** Charge every admitted fixed buffer, including failed syscalls, against the shared scan budget. */
61
+ export const DARWIN_NATIVE_READ_BYTES = DARWIN_ABI.bsd.bytes + RUSAGE_READS_PER_PID * DARWIN_ABI.usage.bytes;
62
+ /** Convert native Mach-derived nanoseconds into the sampler's cumulative CPU milliseconds. */
63
+ export const NANOSECONDS_PER_MILLISECOND = 1_000_000;
64
+ /** The pbi_start_tvusec field must be strictly smaller than one second of microseconds. */
65
+ export const MICROSECONDS_PER_SECOND = 1000000n;
66
+ /**
67
+ * Load only fixed native symbols, lazily; unsupported runtimes retain unavailable process metrics.
68
+ * @returns Owned syscall bindings, or undefined for unsupported platform/architecture/runtime.
69
+ * @throws If opening the runtime FFI library fails.
70
+ */
71
+ function nativeCalls() {
72
+ if (process.platform !== "darwin" || !["arm64", "x64"].includes(process.arch))
73
+ return undefined;
74
+ if (process.versions.bun) {
75
+ const ffi = process.getBuiltinModule("bun:ffi");
76
+ if (!ffi)
77
+ return undefined;
78
+ const lib = ffi.dlopen("/usr/lib/libproc.dylib", {
79
+ proc_pidinfo: { args: ["i32", "i32", "u64", "ptr", "i32"], returns: "i32" },
80
+ proc_pid_rusage: { args: ["i32", "i32", "ptr"], returns: "i32" },
81
+ mach_timebase_info: { args: ["ptr"], returns: "i32" },
82
+ });
83
+ return {
84
+ timebase: (buffer) => lib.symbols.mach_timebase_info(ffi.ptr(buffer)),
85
+ bsd: (pid, buffer) => lib.symbols.proc_pidinfo(pid, DARWIN_ABI.bsd.flavor, DARWIN_ABI.bsd.argument, ffi.ptr(buffer), DARWIN_ABI.bsd.bytes),
86
+ usage: (pid, buffer) => lib.symbols.proc_pid_rusage(pid, DARWIN_ABI.usage.flavor, ffi.ptr(buffer)),
87
+ close: () => lib.close(),
88
+ };
89
+ }
90
+ const ffi = process.getBuiltinModule("node:ffi");
91
+ if (!ffi)
92
+ return undefined;
93
+ const lib = ffi.dlopen("/usr/lib/libproc.dylib", {
94
+ proc_pidinfo: { arguments: ["i32", "i32", "u64", "pointer", "i32"], return: "i32" },
95
+ proc_pid_rusage: { arguments: ["i32", "i32", "pointer"], return: "i32" },
96
+ mach_timebase_info: { arguments: ["pointer"], return: "i32" },
97
+ });
98
+ return {
99
+ timebase: (buffer) => lib.functions.mach_timebase_info(buffer),
100
+ bsd: (pid, buffer) => lib.functions.proc_pidinfo(pid, DARWIN_ABI.bsd.flavor, DARWIN_ABI.bsd.argument, buffer, DARWIN_ABI.bsd.bytes),
101
+ usage: (pid, buffer) => lib.functions.proc_pid_rusage(pid, DARWIN_ABI.usage.flavor, buffer),
102
+ close: () => lib.lib.close(),
103
+ };
104
+ }
105
+ /**
106
+ * Initialize the Mach timebase; close the owned library on failure, including runtime throws.
107
+ * @param load Lazy runtime binding loader, shared by production and deterministic failure tests.
108
+ * @returns Owned bindings with nanoseconds per tick, or undefined when unavailable/invalid.
109
+ * @throws If opening or initializing FFI throws (the caller retains fallback rows).
110
+ */
111
+ function nativeLibrary(load) {
112
+ const lib = load();
113
+ if (!lib)
114
+ return undefined;
115
+ let initialized = false;
116
+ try {
117
+ const timebase = Buffer.alloc(DARWIN_ABI.timebase.bytes);
118
+ if (lib.timebase(timebase) !== DARWIN_ABI.success ||
119
+ timebase.readUInt32LE(DARWIN_ABI.timebase.numerator) === 0 ||
120
+ timebase.readUInt32LE(DARWIN_ABI.timebase.denominator) === 0)
121
+ return undefined;
122
+ initialized = true;
123
+ return {
124
+ ...lib,
125
+ ticksToNs: timebase.readUInt32LE(DARWIN_ABI.timebase.numerator) / timebase.readUInt32LE(DARWIN_ABI.timebase.denominator),
126
+ };
127
+ }
128
+ finally {
129
+ if (!initialized)
130
+ lib.close();
131
+ }
132
+ }
133
+ /**
134
+ * Identity-check metadata between two rusage reads. Start absolute ticks distinguish same-second PID
135
+ * reuse; microsecond start, parent and exact p_comm bytes also participate. No sanitized-name collision
136
+ * can authenticate a baseline. Rusage CPU counters are Mach ticks; convert with mach_timebase_info,
137
+ * not an assumed nanosecond tick (Apple Silicon here reports 125/3 nanoseconds per tick).
138
+ * @param pid Expected process identifier from the bounded metadata enumeration.
139
+ * @param before First fixed rusage_info_v0 frame.
140
+ * @param bsd Intervening fixed proc_bsdinfo frame.
141
+ * @param after Second fixed rusage_info_v0 frame.
142
+ * @param at Monotonic observation time in milliseconds.
143
+ * @param ticksToNs Positive Mach timebase ratio, in nanoseconds per tick.
144
+ * @returns A strong-identity counter, or null for malformed/changed/invalid native data.
145
+ */
146
+ export function darwinNativeCounter(pid, before, bsd, after, at, ticksToNs) {
147
+ if (!Number.isFinite(ticksToNs) || ticksToNs <= 0)
148
+ return null;
149
+ if (before.length !== DARWIN_ABI.usage.bytes ||
150
+ after.length !== DARWIN_ABI.usage.bytes ||
151
+ bsd.length !== DARWIN_ABI.bsd.bytes)
152
+ return null;
153
+ const start = after.readBigUInt64LE(DARWIN_ABI.usage.startTicks);
154
+ if (start === DARWIN_ABI.unsetTime ||
155
+ before.readBigUInt64LE(DARWIN_ABI.usage.startTicks) !== start ||
156
+ bsd.readUInt32LE(DARWIN_ABI.bsd.pid) !== pid)
157
+ return null;
158
+ if (before.readBigUInt64LE(DARWIN_ABI.usage.exitTicks) !== DARWIN_ABI.unsetTime ||
159
+ after.readBigUInt64LE(DARWIN_ABI.usage.exitTicks) !== DARWIN_ABI.unsetTime)
160
+ return null;
161
+ const seconds = bsd.readBigUInt64LE(DARWIN_ABI.bsd.startSeconds);
162
+ const micros = bsd.readBigUInt64LE(DARWIN_ABI.bsd.startMicros);
163
+ if (seconds === DARWIN_ABI.unsetTime || micros >= MICROSECONDS_PER_SECOND)
164
+ return null;
165
+ /** Cumulative user/system Mach ticks from one size-checked rusage frame. */
166
+ const beforeCpu = before.readBigUInt64LE(DARWIN_ABI.usage.userTicks) + before.readBigUInt64LE(DARWIN_ABI.usage.systemTicks);
167
+ const afterCpu = after.readBigUInt64LE(DARWIN_ABI.usage.userTicks) + after.readBigUInt64LE(DARWIN_ABI.usage.systemTicks);
168
+ const cpuMs = afterCpu < beforeCpu ? Number.NaN : (Number(afterCpu) * ticksToNs) / NANOSECONDS_PER_MILLISECOND;
169
+ const rssBytes = Number(after.readBigUInt64LE(DARWIN_ABI.usage.residentBytes));
170
+ const footprintBytes = Number(after.readBigUInt64LE(DARWIN_ABI.usage.footprintBytes));
171
+ if (![rssBytes, footprintBytes].every(Number.isSafeInteger) || !Number.isFinite(cpuMs) || !Number.isFinite(at))
172
+ return null;
173
+ const parentPid = bsd.readUInt32LE(DARWIN_ABI.bsd.parentPid);
174
+ const rawName = bsd.subarray(DARWIN_ABI.bsd.comm, DARWIN_ABI.bsd.comm + DARWIN_ABI.bsd.commBytes);
175
+ const nul = rawName.indexOf(DARWIN_ABI.nulByte);
176
+ const nameBytes = nul < 0 ? rawName : rawName.subarray(0, nul);
177
+ return {
178
+ pid,
179
+ parentPid,
180
+ name: safeName(nameBytes.toString("utf8")),
181
+ identity: `${pid}:native:${start}:${seconds}:${micros}:${parentPid}:${nameBytes.toString("hex")}`,
182
+ rssBytes,
183
+ footprintBytes,
184
+ cpuMs,
185
+ at,
186
+ strongIdentity: true,
187
+ };
188
+ }
189
+ /**
190
+ * Enrich bounded ps rows with cheap native counters, retaining RSS/name rows when access fails.
191
+ * Charge all admitted fixed syscall buffers to the SAME scan budget, including unsuccessful reads.
192
+ * Synchronous syscalls, like os.cpus(), cannot be preempted; check admission before each PID.
193
+ * @param rows Bounded ps fallback rows, enriched in place only on successful native reads.
194
+ * @param budget Shared byte/deadline/abort admission state, charged even for failed syscalls.
195
+ * @param load Lazy native binding dependency; defaults to the platform's builtin FFI adapter.
196
+ * @returns The same array, retaining original rows for inaccessible or rejected PIDs.
197
+ * @throws If the shared abort signal is observed between native calls.
198
+ */
199
+ export function darwinNativeProcesses(rows, budget, load = nativeCalls) {
200
+ if (!budget.ready())
201
+ return rows;
202
+ if (budget.maxBytes - budget.bytesRead < DARWIN_ABI.timebase.bytes) {
203
+ budget.bytesRead = budget.maxBytes;
204
+ budget.reasons.add("byte-limit");
205
+ return rows;
206
+ }
207
+ budget.bytesRead += DARWIN_ABI.timebase.bytes;
208
+ let lib;
209
+ try {
210
+ lib = nativeLibrary(load);
211
+ }
212
+ catch {
213
+ return rows;
214
+ }
215
+ if (!lib)
216
+ return rows;
217
+ try {
218
+ for (let i = 0; i < rows.length; i++) {
219
+ if (!budget.ready())
220
+ break;
221
+ if (budget.maxBytes - budget.bytesRead < DARWIN_NATIVE_READ_BYTES) {
222
+ budget.bytesRead = budget.maxBytes;
223
+ budget.reasons.add("byte-limit");
224
+ break;
225
+ }
226
+ budget.bytesRead += DARWIN_NATIVE_READ_BYTES;
227
+ const row = rows[i];
228
+ if (!row)
229
+ continue;
230
+ const before = Buffer.alloc(DARWIN_ABI.usage.bytes);
231
+ const bsd = Buffer.alloc(DARWIN_ABI.bsd.bytes);
232
+ const after = Buffer.alloc(DARWIN_ABI.usage.bytes);
233
+ try {
234
+ if (lib.usage(row.pid, before) !== DARWIN_ABI.success ||
235
+ !budget.ready() ||
236
+ lib.bsd(row.pid, bsd) !== DARWIN_ABI.bsd.bytes ||
237
+ !budget.ready() ||
238
+ lib.usage(row.pid, after) !== DARWIN_ABI.success)
239
+ continue;
240
+ const counter = darwinNativeCounter(row.pid, before, bsd, after, performance.now(), lib.ticksToNs);
241
+ if (counter)
242
+ rows[i] = counter;
243
+ }
244
+ catch {
245
+ // Runtime FFI failures belong to this PID, not the entire already-collected ps list.
246
+ budget.signal.throwIfAborted();
247
+ }
248
+ }
249
+ return rows;
250
+ }
251
+ finally {
252
+ lib.close();
253
+ }
254
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,8 @@
1
1
  import type { ResourceSampler, SamplerOptions } from "./types.js";
2
2
  export type { Metric, ProcessSample, PsiLine, ResourceSampler, ResourceSnapshot, SamplerOptions } from "./types.js";
3
- /** Create an isolated, passive sampler. No timers or child processes exist until sample(). */
3
+ /**
4
+ * Create an isolated, passive sampler. No timers or children exist until sample().
5
+ * @param options Optional validated scan limits.
6
+ * @returns Sampler owning its own baselines and awaited collection/disposal lifecycle.
7
+ */
4
8
  export declare function createResourceSampler(options?: SamplerOptions): ResourceSampler;
package/dist/index.js CHANGED
@@ -1,15 +1,26 @@
1
1
  import { cpus, freemem, loadavg, platform, totalmem } from "node:os";
2
2
  import { performance } from "node:perf_hooks";
3
- import { Budget, command, darwinProcesses, linuxProcesses, pressure } from "./collect.js";
3
+ import { Budget, command, darwinHostMemory, darwinProcesses, linuxProcesses, pressure } from "./collect.js";
4
4
  import { cpuSnapshot, hostCpu, processCpu } from "./counters.js";
5
- /** Validate bounded integers before collecting any host information. */
5
+ /**
6
+ * Validate bounded integers before collecting host information.
7
+ * @param value Requested bound, if supplied.
8
+ * @param fallback Default bound when absent.
9
+ * @param min Inclusive lower bound.
10
+ * @param max Inclusive upper bound.
11
+ * @returns Validated integer; throws RangeError for invalid input.
12
+ */
6
13
  function bounded(value, fallback, min, max) {
7
14
  const result = value ?? fallback;
8
15
  if (!Number.isInteger(result) || result < min || result > max)
9
16
  throw new RangeError(`Sampler bound must be an integer from ${min} to ${max}`);
10
17
  return result;
11
18
  }
12
- /** Create an isolated, passive sampler. No timers or child processes exist until sample(). */
19
+ /**
20
+ * Create an isolated, passive sampler. No timers or children exist until sample().
21
+ * @param options Optional validated scan limits.
22
+ * @returns Sampler owning its own baselines and awaited collection/disposal lifecycle.
23
+ */
13
24
  export function createResourceSampler(options = {}) {
14
25
  const duration = bounded(options.maxDurationMs, 250, 10, 5000);
15
26
  const maxPids = bounded(options.maxPids, 2048, 1, 16384);
@@ -22,6 +33,11 @@ export function createResourceSampler(options = {}) {
22
33
  let active;
23
34
  let controller;
24
35
  let disposed = false;
36
+ /**
37
+ * Collect one scan and advance baselines only after successful completion.
38
+ * @param signal Combined caller/disposal cancellation signal.
39
+ * @returns Typed snapshot with explicit coverage and metric availability; aborts reject.
40
+ */
25
41
  async function collect(signal) {
26
42
  const start = performance.now();
27
43
  const wallTimeMs = Date.now();
@@ -32,6 +48,8 @@ export function createResourceSampler(options = {}) {
32
48
  ? { state: "warming", reason: "invalid monotonic interval" }
33
49
  : hostCpu(previousCpus, currentCpus);
34
50
  const nativePressure = await pressure(budget, host);
51
+ const totalBytes = totalmem();
52
+ const nativeMemory = host === "darwin" ? await darwinHostMemory(budget, totalBytes) : {};
35
53
  let counters = [];
36
54
  try {
37
55
  if (host === "linux") {
@@ -62,10 +80,17 @@ export function createResourceSampler(options = {}) {
62
80
  name: counter.name,
63
81
  identity: counter.identity,
64
82
  rssBytes: counter.rssBytes,
65
- cpu: host === "darwin"
83
+ ...(host === "darwin"
84
+ ? {
85
+ footprint: counter.footprintBytes === undefined
86
+ ? { state: "unavailable", reason: "native footprint inaccessible or builtin FFI unavailable" }
87
+ : { state: "available", value: counter.footprintBytes },
88
+ }
89
+ : {}),
90
+ cpu: host === "darwin" && !counter.strongIdentity
66
91
  ? {
67
92
  state: "unavailable",
68
- reason: "ps start identity precision is one second; PID reuse cannot be excluded",
93
+ reason: "native counters inaccessible or builtin FFI unavailable; ps identity has only whole seconds",
69
94
  }
70
95
  : processCpu(previousProcesses.get(counter.pid), counter),
71
96
  }));
@@ -84,7 +109,7 @@ export function createResourceSampler(options = {}) {
84
109
  cpu,
85
110
  logicalCpus: currentCpus.length,
86
111
  loadAverage: host === "win32" ? [] : loadavg(),
87
- memory: { totalBytes: totalmem(), freeBytes: freemem() },
112
+ memory: { totalBytes, freeBytes: freemem(), ...nativeMemory },
88
113
  processes,
89
114
  coverage: {
90
115
  complete: budget.reasons.size === 0,
@@ -98,6 +123,11 @@ export function createResourceSampler(options = {}) {
98
123
  };
99
124
  }
100
125
  return {
126
+ /**
127
+ * Start the sole active sample.
128
+ * @param signal Optional caller cancellation signal.
129
+ * @returns Snapshot promise, rejecting on concurrent/disposed use or cancellation.
130
+ */
101
131
  sample(signal) {
102
132
  if (disposed)
103
133
  return Promise.reject(new Error("Resource sampler is disposed"));
@@ -105,6 +135,7 @@ export function createResourceSampler(options = {}) {
105
135
  return Promise.reject(new Error("Resource sampler already has an active sample"));
106
136
  controller = new AbortController();
107
137
  const local = controller;
138
+ /** @returns Nothing; forward caller cancellation to this scan. */
108
139
  const abort = () => local.abort(signal?.reason);
109
140
  if (signal?.aborted)
110
141
  abort();
@@ -116,6 +147,7 @@ export function createResourceSampler(options = {}) {
116
147
  });
117
148
  return active;
118
149
  },
150
+ /** @returns Cleanup completion after aborting any scan and clearing baselines. */
119
151
  async dispose() {
120
152
  disposed = true;
121
153
  controller?.abort();
package/dist/types.d.ts CHANGED
@@ -19,6 +19,8 @@ export interface ProcessSample {
19
19
  name: string;
20
20
  identity: string;
21
21
  rssBytes: number;
22
+ /** Darwin physical footprint (includes compressed memory); failure is never zero. */
23
+ footprint?: Metric<number>;
22
24
  /** Interval utilization: 100 is one logical core, values may exceed 100. */
23
25
  cpu: Metric<number>;
24
26
  }
@@ -43,7 +45,18 @@ export interface ResourceSnapshot {
43
45
  loadAverage: number[];
44
46
  memory: {
45
47
  totalBytes: number;
48
+ /** Free pages only, not reclaimable cache. */
46
49
  freeBytes: number;
50
+ /** Optional additive v1 fields; absent in older producers and on non-Darwin platforms. */
51
+ usage?: Metric<{
52
+ usedBytes: number;
53
+ availableBytes: number;
54
+ basis: "app+wired+compressed";
55
+ }>;
56
+ swap?: Metric<{
57
+ usedBytes: number;
58
+ totalBytes: number;
59
+ }>;
47
60
  };
48
61
  processes: ProcessSample[];
49
62
  coverage: {
package/package.json CHANGED
@@ -1,23 +1,47 @@
1
1
  {
2
2
  "name": "@nredd/pi-resource-sampler",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Bounded, privacy-safe host resource interval sampling without Pi dependencies.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "nredd",
8
- "publishConfig": { "access": "public" },
9
- "engines": { "node": ">=22.14.0" },
10
- "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } },
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "engines": {
12
+ "node": ">=22.14.0"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ }
19
+ },
11
20
  "types": "./dist/index.d.ts",
12
- "files": ["dist", "LICENSE", "README.md"],
13
- "repository": { "type": "git", "url": "git+https://github.com/nredd/pi-harness.git", "directory": "packages/resource-sampler" },
21
+ "files": [
22
+ "dist",
23
+ "LICENSE",
24
+ "README.md"
25
+ ],
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/nredd/pi-harness.git",
29
+ "directory": "packages/resource-sampler"
30
+ },
14
31
  "scripts": {
15
32
  "build": "tsc -p tsconfig.build.json",
16
33
  "lint": "biome check src test",
17
34
  "typecheck": "tsc --noEmit",
18
- "test": "vitest run --maxWorkers=1",
19
- "test:bun": "bun test test/runtime.test.ts",
35
+ "test": "vitest run --coverage --maxWorkers=1",
36
+ "test:bun": "node ../../scripts/run-vitest.ts bun --maxWorkers=1 --coverage --coverage.provider=istanbul --coverage.reporter=text --coverage.reporter=lcov --coverage.reportsDirectory=coverage/bun",
20
37
  "check": "npm run lint && npm run typecheck && npm run build && npm test && npm run test:bun"
21
38
  },
22
- "devDependencies": { "@biomejs/biome": "2.5.15", "@types/node": "26.6.5", "typescript": "7.0.2", "vitest": "5.0.3" }
39
+ "devDependencies": {
40
+ "@biomejs/biome": "2.5.15",
41
+ "@types/node": "26.6.5",
42
+ "@vitest/coverage-istanbul": "5.0.3",
43
+ "@vitest/coverage-v8": "5.0.3",
44
+ "typescript": "7.0.2",
45
+ "vitest": "5.0.3"
46
+ }
23
47
  }