@nredd/pi-resource-sampler 0.1.1 → 0.2.1

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,14 @@ 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
+ Sampler `0.2.0` adds native Darwin interval CPU/footprint and host used/swap metrics. Its
8
+ consumer pins are exact registry dependencies, never workspace links.
9
+
10
+ Unreleased after `0.2.0`: published `0.2.0` lists `/proc` with `opendir`, so on Linux any PID exiting
11
+ mid-listing rejects the whole listing (`lstat` ENOENT on the `DT_UNKNOWN` entry). That scan returns no
12
+ processes (`process-collection-unavailable`) and, as a baseline, leaves every next-scan process
13
+ `warming` (#499). This source lists names only; it needs a release and consumer pin bumps.
14
+
7
15
  Upgrade from `0.1.0`, which is unsafe: on Darwin it reported `ps -c -o comm`, the basename of argv[0],
8
16
  so a launcher-chosen argv[0] or Node `process.title` (e.g. `npm exec <package> mcp`) leaked into
9
17
  `processes[].name`. On Bun, host `cpu` read lazily populated `os.cpus()` objects, so the second sample
@@ -29,7 +37,7 @@ Semantics:
29
37
  - `cpu`: aggregate host CPU counter delta, 0..100. Core count/model changes, individual counter
30
38
  rollback, initial samples, invalid intervals and counters that have not advanced are `warming`,
31
39
  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.
40
+ - `processes[].cpu`: cumulative user+system counter delta divided by monotonic elapsed milliseconds.
33
41
  100 means one logical core, multi-threaded processes can exceed 100. Linux `CLK_TCK` is read
34
42
  once with fixed `/usr/bin/getconf CLK_TCK`; no assumed tick rate or RSS page size.
35
43
  - Linux identity includes the exact `/proc/PID/stat` start tick string. Read stat/exe/status/stat and
@@ -37,20 +45,44 @@ Semantics:
37
45
  invalidate their old baselines. New/reused PIDs and counter resets warm rather than showing zero.
38
46
  - `cpu` copies every `os.cpus()` counter when sampled. Bun returns lazy placeholders that read native
39
47
  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.
48
+ - Darwin enumerates metadata with fixed `/bin/ps -A -o pid=,ppid=,lstart=,time=,rss=,ucomm=`
49
+ and `LC_ALL=C`. Builtin FFI (Node >=26.1, Bun; toolchain pin in root `.bun-version`) then reads fixed symbols
50
+ `proc_pidinfo`, `proc_pid_rusage` and `mach_timebase_info` from `/usr/lib/libproc.dylib`, without
51
+ root, a compiler, addon or new binary/package dependency. Import/construction does not load FFI.
52
+ Node emits its builtin experimental-FFI warning on first use; Bun does not. Node 22-25 keeps
53
+ metadata/RSS but explicitly unavailable CPU/footprint. ABI access is restricted to Darwin arm64/x64.
54
+ - Native Darwin identity includes PID, kernel process-start absolute ticks, microsecond start time,
55
+ PPID and exact `p_comm` bytes. Rusage reads bracket metadata; changed start/exit state or counter
56
+ rollback rejects the native read. Same-second PID reuse cannot authenticate an old baseline even
57
+ with identical parent/name and nondecreasing CPU. Each observation has its own monotonic timestamp.
58
+ Identity/parent/name changes, negative deltas, nonpositive/nonfinite intervals and native intervals
59
+ over 60s warm instead of fabricating CPU. Native CPU counters are Mach ticks converted using the
60
+ kernel timebase (125/3 ns per tick on this Apple Silicon Mac), NOT assumed nanoseconds.
61
+ - `processes[].footprint` is an optional Darwin metric from `ri_phys_footprint`, including compressed
62
+ memory. Native `rssBytes` comes from `ri_resident_size`. Inaccessible/exited/reused PIDs or exhausted
63
+ native budgets retain the enumerated metadata/RSS row with unavailable CPU/footprint; unsupported
64
+ runtimes do the same. No failed footprint is encoded as zero. `ps` fallback identity has only
65
+ whole-second precision, so it NEVER supplies interval CPU. No decaying `%cpu` is relabelled.
45
66
  - `wallTimeMs` labels the start; `monotonicTimeMs` controls intervals. Per-process reads have their own
46
67
  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.
68
+ - `memory.freeBytes` means free, NOT available or pressure. Darwin adds optional v1 `memory.usage`
69
+ and `memory.swap` metrics. `usage.value.usedBytes` estimates resident App + Wired + Compressed RAM:
70
+ `(Anonymous pages - Pages purgeable + Pages wired down + Pages occupied by compressor) * page size`
71
+ from fixed `/usr/bin/vm_stat` output. The page size comes from its header, never an assumed 4KiB.
72
+ `availableBytes` is total minus that estimate (reclaimable cache included), NOT a pressure score or
73
+ an allocation guarantee. Compressor occupancy is physical RAM, not `Pages stored in compressor`.
74
+ Swap used/allocated bytes come from fixed `/usr/sbin/sysctl vm.swapusage` (binary MiB).
75
+ Invalid/missing/over-budget counters are `unavailable`, never zero or a silent total-free fallback.
76
+ Older producers and non-Darwin platforms omit these additive fields. Linux's existing free-page/PSI
77
+ semantics are unchanged; this library did not expose Linux MemAvailable.
78
+ Both helpers share the existing scan budget, fixed environment, output bound and awaited reaping.
79
+ `loadAverage` is load, NOT percent.
48
80
  Linux memory PSI preserves native `some`/optional `full`, avg10/60/300 percentages and cumulative
49
81
  stall microseconds. Missing/invalid PSI is unavailable. Other platforms explicitly have no PSI.
50
82
  - `processes[].name` is an executable basename from kernel metadata. It excludes argv, environment,
51
83
  process title and Linux comm, but it is still untrusted metadata that the process or its launcher can
52
84
  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
85
+ - Darwin: native `proc_bsdinfo.pbi_comm`, or `ps ucomm` from kinfo `p_comm`. XNU writes it at exec, from the
54
86
  looked-up executable file name, truncated to 16 bytes (`Google Chrome He`). `ps -c -o comm` is
55
87
  argv[0] and is NOT used.
56
88
  - Linux: basename of `readlink /proc/PID/exe` (` (deleted)` marker removed), read between the two
@@ -67,14 +99,26 @@ Semantics:
67
99
  Bounds:
68
100
 
69
101
  - Default scan budget 250ms, 2048 PIDs, 2MiB captured bytes; options allow at most 5s, 16384 PIDs,
70
- 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.
102
+ 16MiB. Linux proc files read sequentially (concurrency one), at most 8KiB each. Linux lists `/proc`
103
+ names only, never `opendir` Dirents: a PID that exits mid-listing comes back `DT_UNKNOWN` and the
104
+ runtime would `lstat` it, so it is instead one skipped row (`process-unreadable-or-changed`) when
105
+ its own stat read fails. RESIDUAL: that one `readdir` is read whole (one short name per process,
106
+ e.g. ~100KiB at 16384 PIDs) before the PID cap, deadline or abort can apply; per-PID reads stop at
107
+ the budget; Darwin output stops at the PID/output budget and reaps the fixed helper. Native reads charge
108
+ 8 bytes for the timebase and 328 bytes per admitted PID (two 96-byte rusage buffers and one 136-byte
109
+ metadata buffer), including failed calls, to that SAME byte budget. Only `pbi_comm` and numeric
110
+ fields are inspected; `pbi_name`, arguments and environment are never decoded or exported. Native
111
+ syscalls are synchronous/non-preemptible like `os.cpus()`; admission is checked between reads.
72
112
  - `/proc/PID/exe` is a `readlink`, which Node and Bun cannot cap: each call copies up to PATH_MAX
73
113
  (4096) bytes into a fixed runtime buffer before the length is known. That fixed per-call syscall
74
114
  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 `""`.
115
+ is charged the remainder, so `bytesRead <= maxBytes`, and the budget is then exhausted: that
116
+ process's `status` read is refused, so the whole process is skipped
117
+ (`process-unreadable-or-changed`, `byte-limit`), not kept with an empty name, and the scan stops.
118
+ A target filling the 4096-byte buffer may be truncated: Node returns it silently, the name is
119
+ dropped (`""`, `file-byte-limit`) and the process is kept. Bun's readlink source refuses such a
120
+ target with `ENAMETOOLONG`, which would take the unreadable-link path (`""`, no reason); that Bun
121
+ path was read in source only, never executed here.
78
122
  - `coverage.complete`, `enumerated`, `sampled`, `skipped`, `bytesRead` and reasons describe partial
79
123
  coverage explicitly. `enumerated` is encountered rows, not total processes when partial. Truncation
80
124
  is not a host-wide top-process ranking. OS enumeration order may favor the same subset each time.
@@ -84,6 +128,11 @@ Bounds:
84
128
  immediate SIGKILL on abort/deadline/cap, and resolve only on close. No persistent children or workers.
85
129
  - Unsupported platforms keep native host metrics but report process coverage unavailable.
86
130
 
131
+ macOS measurement/definition comparison, native ABI evidence and future publication checklist:
132
+ [here](../../docs/mon-accuracy.md). Process `rssBytes` still excludes compressed pages; it is not
133
+ Activity Monitor's physical footprint; use the separate `footprint` metric for that comparison.
134
+ Names remain executable names, so Pi commonly appears as `node`.
135
+
87
136
  Local overhead observation (2026-10-22, Darwin arm64, Node 26.12.0, 10 logical CPUs, 16GiB RAM,
88
137
  load about 6, not a quiet-runner benchmark): ten scans of 557 processes took 17.5-24.9ms each,
89
138
  about 41.3KB captured, all complete. The Node collector consumed 25.7ms CPU total across ten
@@ -93,11 +142,29 @@ scans (2.6ms/sample, excludes helper CPU); a separate fixed `ps` invocation meas
93
142
  real-input gate and reports its snapshot duration/coverage.
94
143
 
95
144
  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.
145
+ actual host samples and child cleanup). The full suite runs through Vitest on Node and pinned Bun.
146
+ Native failure tests inject fixed bindings through the same lazy loader seam used by production,
147
+ and `nativeCalls(host)` takes a fake `process` (platform, arch, `versions.bun`, `getBuiltinModule`)
148
+ with recording `bun:ffi`/`node:ffi` fakes, never a patched global. Both adapters and the per-PID
149
+ loop therefore run on every OS without the runtime's real FFI; macOS also runs the real libproc path.
150
+ `test/runtime.test.ts` runs under both engines: it starts a child whose argv[0], argv, environment, process title and (Linux) comm hold a
151
+ random secret, proves the 0.1.0 source exposes it, then requires the child in the snapshot and no
152
+ 12-character fragment of the secret, plus three real CPU samples. Everything after spawn, readiness
153
+ included, is followed by SIGTERM, then SIGKILL, with a bounded wait for the runtime's exit status
154
+ of that exact child (never a PID probe); a cleanup failure is reported alongside the original error
155
+ (`AggregateError`), never instead of it. Regressions make readiness and the negative control fail
156
+ and require the child reaped, including a child that ignores SIGTERM and needs SIGKILL, and inject a
157
+ cleanup failure to require both errors. This cleanup is in-process only: if the test worker itself
158
+ is SIGKILLed, no JavaScript runs and the child outlives it. The packed contract probe below instead
159
+ runs in its own process group, which the gate kills on its Python timeout or `KeyboardInterrupt`
160
+ while the leader is unreaped; an already reaped leader, or an unhandled SIGTERM/SIGHUP or SIGKILL of
161
+ the gate, skips that cleanup and may leave members behind. The privacy
162
+ check samples with the library maxima (5s, 16384 PIDs, 16MiB) and never accepts a missing child as
163
+ a pass: on a host whose processes exceed those bounds, or whose enumeration reaches the child only
164
+ after them, it fails with the snapshot's coverage in the error. On Linux each process costs two
165
+ `stat` reads, the `/proc/PID/exe` target bytes and `status`, so the byte bound can bind before the
166
+ PID bound. `make check-resource-sampler-contract` builds and exercises an isolated installed
167
+ tarball, with no Pi or siblings. Both run on existing macOS/Linux CI jobs.
101
168
  `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.
169
+ scripts or runtime dependencies. Releases publish through `publish.yml` with npm provenance; see
170
+ [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,52 @@ 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 over a names-only `/proc` listing.
56
+ *
57
+ * Names only, never `opendir` Dirents: `/proc` reports a PID that exits mid-listing as `DT_UNKNOWN`, and
58
+ * Node's `Dir` then `lstat`s it, and that ENOENT rejects the iterator with its batch, which cannot resume, so
59
+ * the whole scan was lost (`process-collection-unavailable`). A vanished PID must fail its own stat read instead.
60
+ * @param budget Shared scan limits and cancellation.
61
+ * @param hz Host CLK_TCK rate in ticks per second.
62
+ * @returns Validated identity-bracketed process counters; aborts propagate.
63
+ */
33
64
  export declare function linuxProcesses(budget: Budget, hz: number): Promise<ProcessCounter[]>;
34
65
  /**
35
66
  * Fixed metadata-only ps format. `ucomm` prints kinfo `p_comm`, never `comm`: `ps -c -o comm` shows the
36
67
  * basename of argv[0], which any launcher picks and Node's `process.title` rewrites in place.
68
+ * @param budget Shared helper/native scan limits and cancellation.
69
+ * @returns Bounded fallback rows enriched with accessible native metrics; aborts propagate.
37
70
  */
38
71
  export declare function darwinProcesses(budget: Budget): Promise<ProcessCounter[]>;
39
- /** PSI is optional and platform-specific; absence is not zero pressure. */
72
+ /**
73
+ * Run fixed metadata-only helpers sharing the process deadline, cap and awaited reaping.
74
+ * @param budget Shared helper capture budget and cancellation.
75
+ * @param total Host physical RAM in bytes.
76
+ * @returns Explicit available/unavailable host usage and swap metrics.
77
+ */
78
+ export declare function darwinHostMemory(budget: Budget, total: number): Promise<Pick<ResourceSnapshot["memory"], "usage" | "swap">>;
79
+ /**
80
+ * Collect optional platform-specific PSI; absence is not zero pressure.
81
+ * @param budget Shared file-read budget and cancellation.
82
+ * @param platform Host platform identifier.
83
+ * @returns Linux PSI availability or explicit unsupported state; aborts propagate.
84
+ */
40
85
  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
- import { open, opendir, readlink } from "node:fs/promises";
2
+ import { open, readdir, 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,17 +122,21 @@ 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());
138
+ // No abort can land unobserved: `ready()` threw on an aborted signal, and nothing since has yielded.
109
139
  budget.signal.addEventListener("abort", abort, { once: true });
110
- // Close the race between the ready check and listener registration.
111
- if (budget.signal.aborted)
112
- abort();
113
140
  child.stdout.on("data", (data) => {
114
141
  if (!complete)
115
142
  return;
@@ -152,12 +179,20 @@ export async function command(executable, args, budget, maxLines = Number.POSITI
152
179
  });
153
180
  });
154
181
  }
155
- /** Linux scan is sequential and closes the directory even on cancellation. */
182
+ /**
183
+ * Scan Linux sequentially over a names-only `/proc` listing.
184
+ *
185
+ * Names only, never `opendir` Dirents: `/proc` reports a PID that exits mid-listing as `DT_UNKNOWN`, and
186
+ * Node's `Dir` then `lstat`s it, and that ENOENT rejects the iterator with its batch, which cannot resume, so
187
+ * the whole scan was lost (`process-collection-unavailable`). A vanished PID must fail its own stat read instead.
188
+ * @param budget Shared scan limits and cancellation.
189
+ * @param hz Host CLK_TCK rate in ticks per second.
190
+ * @returns Validated identity-bracketed process counters; aborts propagate.
191
+ */
156
192
  export async function linuxProcesses(budget, hz) {
157
193
  const result = [];
158
- const directory = await opendir("/proc");
159
- for await (const entry of directory) {
160
- if (!/^\d+$/.test(entry.name))
194
+ for (const pid of await readdir("/proc")) {
195
+ if (!/^\d+$/.test(pid))
161
196
  continue;
162
197
  if (!budget.ready())
163
198
  break;
@@ -167,7 +202,7 @@ export async function linuxProcesses(budget, hz) {
167
202
  }
168
203
  budget.enumerated++;
169
204
  try {
170
- const path = `/proc/${entry.name}`;
205
+ const path = `/proc/${pid}`;
171
206
  const first = linuxStat(await budget.read(`${path}/stat`), hz, performance.now());
172
207
  if (!first)
173
208
  throw new Error("process incomplete");
@@ -175,7 +210,7 @@ export async function linuxProcesses(budget, hz) {
175
210
  const rssBytes = linuxRss(await budget.read(`${path}/status`));
176
211
  const last = linuxStat(await budget.read(`${path}/stat`), hz, performance.now());
177
212
  // The name and RSS reads sit between two stat reads, so PID reuse rejects both.
178
- if (!last || first.pid !== Number(entry.name) || first.identity !== last.identity || rssBytes === null)
213
+ if (!last || first.pid !== Number(pid) || first.identity !== last.identity || rssBytes === null)
179
214
  throw new Error("process changed or incomplete");
180
215
  result.push({ ...last, name, rssBytes });
181
216
  }
@@ -190,6 +225,8 @@ export async function linuxProcesses(budget, hz) {
190
225
  /**
191
226
  * Fixed metadata-only ps format. `ucomm` prints kinfo `p_comm`, never `comm`: `ps -c -o comm` shows the
192
227
  * basename of argv[0], which any launcher picks and Node's `process.title` rewrites in place.
228
+ * @param budget Shared helper/native scan limits and cancellation.
229
+ * @returns Bounded fallback rows enriched with accessible native metrics; aborts propagate.
193
230
  */
194
231
  export async function darwinProcesses(budget) {
195
232
  const { text } = await command("/bin/ps", ["-A", "-o", "pid=,ppid=,lstart=,time=,rss=,ucomm="], budget, budget.maxPids);
@@ -210,9 +247,34 @@ export async function darwinProcesses(budget) {
210
247
  budget.reasons.add("malformed-process-row");
211
248
  }
212
249
  }
213
- return result;
250
+ return darwinNativeProcesses(result, budget);
251
+ }
252
+ /**
253
+ * Run fixed metadata-only helpers sharing the process deadline, cap and awaited reaping.
254
+ * @param budget Shared helper capture budget and cancellation.
255
+ * @param total Host physical RAM in bytes.
256
+ * @returns Explicit available/unavailable host usage and swap metrics.
257
+ */
258
+ export async function darwinHostMemory(budget, total) {
259
+ const vm = await command("/usr/bin/vm_stat", [], budget);
260
+ const usage = vm.complete ? darwinMemory(vm.text, total) : null;
261
+ const swap = await command("/usr/sbin/sysctl", ["vm.swapusage"], budget);
262
+ const parsedSwap = swap.complete ? darwinSwap(swap.text) : null;
263
+ return {
264
+ usage: usage
265
+ ? { state: "available", value: usage }
266
+ : { state: "unavailable", reason: "vm_stat invalid, unavailable or over budget" },
267
+ swap: parsedSwap
268
+ ? { state: "available", value: parsedSwap }
269
+ : { state: "unavailable", reason: "swapusage invalid, unavailable or over budget" },
270
+ };
214
271
  }
215
- /** PSI is optional and platform-specific; absence is not zero pressure. */
272
+ /**
273
+ * Collect optional platform-specific PSI; absence is not zero pressure.
274
+ * @param budget Shared file-read budget and cancellation.
275
+ * @param platform Host platform identifier.
276
+ * @returns Linux PSI availability or explicit unsupported state; aborts propagate.
277
+ */
216
278
  export async function pressure(budget, platform) {
217
279
  if (platform !== "linux")
218
280
  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,68 @@ 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 values = text
186
+ .split("\n")
187
+ .filter((line) => line.startsWith(`${name}:`))
188
+ .map((line) => /^.*:\s+(\d+)\.\s*$/.exec(line)?.[1]);
189
+ const [value] = values.length === VM_COUNTER_OCCURRENCES ? values : [];
190
+ const count = value === undefined ? Number.NaN : Number(value);
191
+ return Number.isSafeInteger(count) && count >= 0 ? count : null;
192
+ };
193
+ const anonymous = read("Anonymous pages");
194
+ const purgeable = read("Pages purgeable");
195
+ const wired = read("Pages wired down");
196
+ const compressed = read("Pages occupied by compressor");
197
+ if (anonymous === null || purgeable === null || wired === null || compressed === null || purgeable > anonymous)
198
+ return null;
199
+ const usedBytes = (anonymous - purgeable + wired + compressed) * pageSize;
200
+ if (!Number.isSafeInteger(usedBytes) || usedBytes < 0 || usedBytes > total)
201
+ return null;
202
+ return { usedBytes, availableBytes: total - usedBytes, basis: "app+wired+compressed" };
203
+ }
204
+ /**
205
+ * Parse sysctl's fixed C-locale swapusage format (binary MiB, including fractions).
206
+ * @param text Fixed sysctl vm.swapusage output.
207
+ * @returns Rounded used/allocated bytes, or null for malformed or inconsistent counters.
208
+ */
209
+ export function darwinSwap(text) {
210
+ const match = /^vm\.swapusage: total = (\d+\.\d+)M\s+used = (\d+\.\d+)M\s+free = (\d+\.\d+)M(?:\s+\(encrypted\))?\s*$/.exec(text);
211
+ if (!match)
212
+ return null;
213
+ const [, totalMebibytes, usedMebibytes, freeMebibytes] = match;
214
+ const totalBytes = Math.round(Number(totalMebibytes) * BYTES_PER_MEBIBYTE);
215
+ const usedBytes = Math.round(Number(usedMebibytes) * BYTES_PER_MEBIBYTE);
216
+ const freeBytes = Math.round(Number(freeMebibytes) * BYTES_PER_MEBIBYTE);
217
+ if (![totalBytes, usedBytes, freeBytes].every(Number.isSafeInteger) ||
218
+ usedBytes > totalBytes ||
219
+ Math.abs(totalBytes - usedBytes - freeBytes) > SWAP_ROUNDING_TOLERANCE_BYTES)
220
+ return null;
221
+ return { usedBytes, totalBytes };
222
+ }
223
+ /**
224
+ * Parse native PSI percentages and cumulative stall microseconds.
225
+ * @param text Linux memory pressure rows.
226
+ * @returns Valid some/optional full counters, or null for malformed data.
227
+ */
123
228
  export function psi(text) {
124
229
  const rows = new Map();
125
230
  for (const line of text.trim().split("\n")) {
@@ -0,0 +1,110 @@
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
+ /** The `process` fields that select an FFI adapter; tests inject a fake host to run both on any OS. */
72
+ export interface NativeHost {
73
+ readonly platform: string;
74
+ readonly arch: string;
75
+ /** Runtime versions; only a `bun` entry selects the Bun adapter. */
76
+ readonly versions: Readonly<Record<string, string | undefined>>;
77
+ getBuiltinModule(id: string): unknown;
78
+ }
79
+ /**
80
+ * Load only fixed native symbols, lazily; unsupported runtimes retain unavailable process metrics.
81
+ * @param host Platform, architecture, runtime and builtin loader; defaults to the running `process`.
82
+ * @returns Owned syscall bindings, or undefined for unsupported platform/architecture/runtime.
83
+ * @throws If opening the runtime FFI library fails.
84
+ */
85
+ export declare function nativeCalls(host?: NativeHost): NativeCalls | undefined;
86
+ /**
87
+ * Identity-check metadata between two rusage reads. Start absolute ticks distinguish same-second PID
88
+ * reuse; microsecond start, parent and exact p_comm bytes also participate. No sanitized-name collision
89
+ * can authenticate a baseline. Rusage CPU counters are Mach ticks; convert with mach_timebase_info,
90
+ * not an assumed nanosecond tick (Apple Silicon here reports 125/3 nanoseconds per tick).
91
+ * @param pid Expected process identifier from the bounded metadata enumeration.
92
+ * @param before First fixed rusage_info_v0 frame.
93
+ * @param bsd Intervening fixed proc_bsdinfo frame.
94
+ * @param after Second fixed rusage_info_v0 frame.
95
+ * @param at Monotonic observation time in milliseconds.
96
+ * @param ticksToNs Positive Mach timebase ratio, in nanoseconds per tick.
97
+ * @returns A strong-identity counter, or null for malformed/changed/invalid native data.
98
+ */
99
+ export declare function darwinNativeCounter(pid: number, before: Buffer, bsd: Buffer, after: Buffer, at: number, ticksToNs: number): ProcessCounter | null;
100
+ /**
101
+ * Enrich bounded ps rows with cheap native counters, retaining RSS/name rows when access fails.
102
+ * Charge all admitted fixed syscall buffers to the SAME scan budget, including unsuccessful reads.
103
+ * Synchronous syscalls, like os.cpus(), cannot be preempted; check admission before each PID.
104
+ * @param rows Bounded ps fallback rows, enriched in place only on successful native reads.
105
+ * @param budget Shared byte/deadline/abort admission state, charged even for failed syscalls.
106
+ * @param load Lazy native binding dependency; defaults to the platform's builtin FFI adapter.
107
+ * @returns The same array, retaining original rows for inaccessible or rejected PIDs.
108
+ * @throws If the shared abort signal is observed between native calls.
109
+ */
110
+ export declare function darwinNativeProcesses(rows: ProcessCounter[], budget: Budget, load?: () => NativeCalls | undefined): ProcessCounter[];
package/dist/darwin.js ADDED
@@ -0,0 +1,252 @@
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
+ * @param host Platform, architecture, runtime and builtin loader; defaults to the running `process`.
69
+ * @returns Owned syscall bindings, or undefined for unsupported platform/architecture/runtime.
70
+ * @throws If opening the runtime FFI library fails.
71
+ */
72
+ export function nativeCalls(host = process) {
73
+ if (host.platform !== "darwin" || !["arm64", "x64"].includes(host.arch))
74
+ return undefined;
75
+ if (host.versions.bun) {
76
+ const ffi = host.getBuiltinModule("bun:ffi");
77
+ if (!ffi)
78
+ return undefined;
79
+ const lib = ffi.dlopen("/usr/lib/libproc.dylib", {
80
+ proc_pidinfo: { args: ["i32", "i32", "u64", "ptr", "i32"], returns: "i32" },
81
+ proc_pid_rusage: { args: ["i32", "i32", "ptr"], returns: "i32" },
82
+ mach_timebase_info: { args: ["ptr"], returns: "i32" },
83
+ });
84
+ return {
85
+ timebase: (buffer) => lib.symbols.mach_timebase_info(ffi.ptr(buffer)),
86
+ bsd: (pid, buffer) => lib.symbols.proc_pidinfo(pid, DARWIN_ABI.bsd.flavor, DARWIN_ABI.bsd.argument, ffi.ptr(buffer), DARWIN_ABI.bsd.bytes),
87
+ usage: (pid, buffer) => lib.symbols.proc_pid_rusage(pid, DARWIN_ABI.usage.flavor, ffi.ptr(buffer)),
88
+ close: () => lib.close(),
89
+ };
90
+ }
91
+ const ffi = host.getBuiltinModule("node:ffi");
92
+ if (!ffi)
93
+ return undefined;
94
+ const lib = ffi.dlopen("/usr/lib/libproc.dylib", {
95
+ proc_pidinfo: { arguments: ["i32", "i32", "u64", "pointer", "i32"], return: "i32" },
96
+ proc_pid_rusage: { arguments: ["i32", "i32", "pointer"], return: "i32" },
97
+ mach_timebase_info: { arguments: ["pointer"], return: "i32" },
98
+ });
99
+ return {
100
+ timebase: (buffer) => lib.functions.mach_timebase_info(buffer),
101
+ bsd: (pid, buffer) => lib.functions.proc_pidinfo(pid, DARWIN_ABI.bsd.flavor, DARWIN_ABI.bsd.argument, buffer, DARWIN_ABI.bsd.bytes),
102
+ usage: (pid, buffer) => lib.functions.proc_pid_rusage(pid, DARWIN_ABI.usage.flavor, buffer),
103
+ close: () => lib.lib.close(),
104
+ };
105
+ }
106
+ /**
107
+ * Initialize the Mach timebase; close the owned library on failure, including runtime throws.
108
+ * @param load Lazy runtime binding loader, shared by production and deterministic failure tests.
109
+ * @returns Owned bindings with nanoseconds per tick, or undefined when unavailable/invalid.
110
+ * @throws If opening or initializing FFI throws (the caller retains fallback rows).
111
+ */
112
+ function nativeLibrary(load) {
113
+ const lib = load();
114
+ if (!lib)
115
+ return undefined;
116
+ let initialized = false;
117
+ try {
118
+ const timebase = Buffer.alloc(DARWIN_ABI.timebase.bytes);
119
+ if (lib.timebase(timebase) !== DARWIN_ABI.success ||
120
+ timebase.readUInt32LE(DARWIN_ABI.timebase.numerator) === 0 ||
121
+ timebase.readUInt32LE(DARWIN_ABI.timebase.denominator) === 0)
122
+ return undefined;
123
+ initialized = true;
124
+ return {
125
+ ...lib,
126
+ ticksToNs: timebase.readUInt32LE(DARWIN_ABI.timebase.numerator) / timebase.readUInt32LE(DARWIN_ABI.timebase.denominator),
127
+ };
128
+ }
129
+ finally {
130
+ if (!initialized)
131
+ lib.close();
132
+ }
133
+ }
134
+ /**
135
+ * Identity-check metadata between two rusage reads. Start absolute ticks distinguish same-second PID
136
+ * reuse; microsecond start, parent and exact p_comm bytes also participate. No sanitized-name collision
137
+ * can authenticate a baseline. Rusage CPU counters are Mach ticks; convert with mach_timebase_info,
138
+ * not an assumed nanosecond tick (Apple Silicon here reports 125/3 nanoseconds per tick).
139
+ * @param pid Expected process identifier from the bounded metadata enumeration.
140
+ * @param before First fixed rusage_info_v0 frame.
141
+ * @param bsd Intervening fixed proc_bsdinfo frame.
142
+ * @param after Second fixed rusage_info_v0 frame.
143
+ * @param at Monotonic observation time in milliseconds.
144
+ * @param ticksToNs Positive Mach timebase ratio, in nanoseconds per tick.
145
+ * @returns A strong-identity counter, or null for malformed/changed/invalid native data.
146
+ */
147
+ export function darwinNativeCounter(pid, before, bsd, after, at, ticksToNs) {
148
+ if (!Number.isFinite(ticksToNs) || ticksToNs <= 0)
149
+ return null;
150
+ if (before.length !== DARWIN_ABI.usage.bytes ||
151
+ after.length !== DARWIN_ABI.usage.bytes ||
152
+ bsd.length !== DARWIN_ABI.bsd.bytes)
153
+ return null;
154
+ const start = after.readBigUInt64LE(DARWIN_ABI.usage.startTicks);
155
+ if (start === DARWIN_ABI.unsetTime ||
156
+ before.readBigUInt64LE(DARWIN_ABI.usage.startTicks) !== start ||
157
+ bsd.readUInt32LE(DARWIN_ABI.bsd.pid) !== pid)
158
+ return null;
159
+ if (before.readBigUInt64LE(DARWIN_ABI.usage.exitTicks) !== DARWIN_ABI.unsetTime ||
160
+ after.readBigUInt64LE(DARWIN_ABI.usage.exitTicks) !== DARWIN_ABI.unsetTime)
161
+ return null;
162
+ const seconds = bsd.readBigUInt64LE(DARWIN_ABI.bsd.startSeconds);
163
+ const micros = bsd.readBigUInt64LE(DARWIN_ABI.bsd.startMicros);
164
+ if (seconds === DARWIN_ABI.unsetTime || micros >= MICROSECONDS_PER_SECOND)
165
+ return null;
166
+ /** Cumulative user/system Mach ticks from one size-checked rusage frame. */
167
+ const beforeCpu = before.readBigUInt64LE(DARWIN_ABI.usage.userTicks) + before.readBigUInt64LE(DARWIN_ABI.usage.systemTicks);
168
+ const afterCpu = after.readBigUInt64LE(DARWIN_ABI.usage.userTicks) + after.readBigUInt64LE(DARWIN_ABI.usage.systemTicks);
169
+ const cpuMs = afterCpu < beforeCpu ? Number.NaN : (Number(afterCpu) * ticksToNs) / NANOSECONDS_PER_MILLISECOND;
170
+ const rssBytes = Number(after.readBigUInt64LE(DARWIN_ABI.usage.residentBytes));
171
+ const footprintBytes = Number(after.readBigUInt64LE(DARWIN_ABI.usage.footprintBytes));
172
+ if (![rssBytes, footprintBytes].every(Number.isSafeInteger) || !Number.isFinite(cpuMs) || !Number.isFinite(at))
173
+ return null;
174
+ const parentPid = bsd.readUInt32LE(DARWIN_ABI.bsd.parentPid);
175
+ const rawName = bsd.subarray(DARWIN_ABI.bsd.comm, DARWIN_ABI.bsd.comm + DARWIN_ABI.bsd.commBytes);
176
+ const nul = rawName.indexOf(DARWIN_ABI.nulByte);
177
+ const nameBytes = nul < 0 ? rawName : rawName.subarray(0, nul);
178
+ return {
179
+ pid,
180
+ parentPid,
181
+ name: safeName(nameBytes.toString("utf8")),
182
+ identity: `${pid}:native:${start}:${seconds}:${micros}:${parentPid}:${nameBytes.toString("hex")}`,
183
+ rssBytes,
184
+ footprintBytes,
185
+ cpuMs,
186
+ at,
187
+ strongIdentity: true,
188
+ };
189
+ }
190
+ /**
191
+ * Enrich bounded ps rows with cheap native counters, retaining RSS/name rows when access fails.
192
+ * Charge all admitted fixed syscall buffers to the SAME scan budget, including unsuccessful reads.
193
+ * Synchronous syscalls, like os.cpus(), cannot be preempted; check admission before each PID.
194
+ * @param rows Bounded ps fallback rows, enriched in place only on successful native reads.
195
+ * @param budget Shared byte/deadline/abort admission state, charged even for failed syscalls.
196
+ * @param load Lazy native binding dependency; defaults to the platform's builtin FFI adapter.
197
+ * @returns The same array, retaining original rows for inaccessible or rejected PIDs.
198
+ * @throws If the shared abort signal is observed between native calls.
199
+ */
200
+ export function darwinNativeProcesses(rows, budget, load = nativeCalls) {
201
+ if (!budget.ready())
202
+ return rows;
203
+ if (budget.maxBytes - budget.bytesRead < DARWIN_ABI.timebase.bytes) {
204
+ budget.bytesRead = budget.maxBytes;
205
+ budget.reasons.add("byte-limit");
206
+ return rows;
207
+ }
208
+ budget.bytesRead += DARWIN_ABI.timebase.bytes;
209
+ let lib;
210
+ try {
211
+ lib = nativeLibrary(load);
212
+ }
213
+ catch {
214
+ return rows;
215
+ }
216
+ if (!lib)
217
+ return rows;
218
+ try {
219
+ for (const [i, row] of rows.entries()) {
220
+ if (!budget.ready())
221
+ break;
222
+ if (budget.maxBytes - budget.bytesRead < DARWIN_NATIVE_READ_BYTES) {
223
+ budget.bytesRead = budget.maxBytes;
224
+ budget.reasons.add("byte-limit");
225
+ break;
226
+ }
227
+ budget.bytesRead += DARWIN_NATIVE_READ_BYTES;
228
+ const before = Buffer.alloc(DARWIN_ABI.usage.bytes);
229
+ const bsd = Buffer.alloc(DARWIN_ABI.bsd.bytes);
230
+ const after = Buffer.alloc(DARWIN_ABI.usage.bytes);
231
+ try {
232
+ if (lib.usage(row.pid, before) !== DARWIN_ABI.success ||
233
+ !budget.ready() ||
234
+ lib.bsd(row.pid, bsd) !== DARWIN_ABI.bsd.bytes ||
235
+ !budget.ready() ||
236
+ lib.usage(row.pid, after) !== DARWIN_ABI.success)
237
+ continue;
238
+ const counter = darwinNativeCounter(row.pid, before, bsd, after, performance.now(), lib.ticksToNs);
239
+ if (counter)
240
+ rows[i] = counter;
241
+ }
242
+ catch {
243
+ // Runtime FFI failures belong to this PID, not the entire already-collected ps list.
244
+ budget.signal.throwIfAborted();
245
+ }
246
+ }
247
+ return rows;
248
+ }
249
+ finally {
250
+ lib.close();
251
+ }
252
+ }
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.1",
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": "JITI_FS_CACHE=false vitest run --coverage --maxWorkers=1",
36
+ "test:bun": "node ../../scripts/run-vitest.ts bun --maxWorkers=1",
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
  }