From 5f32dfd09a0bc72c4f99e3076ab6703ec99bc78c Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 20:31:48 +0500 Subject: [PATCH 1/3] feat(node,trackers): ram_system_free means memory available to new work (C6); retire ram_system_available MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit πŸ€– Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/node-runtime-traces.md | 3 +- .changeset/ram-system-free-semantics.md | 11 ++ docs/PROGRESS.md | 4 +- packages/bun/src/launch.test.ts | 4 +- packages/bun/src/launch.ts | 5 +- packages/deno/src/launch.test.ts | 4 +- packages/deno/src/launch.ts | 4 +- packages/node/src/trace-producers.test.ts | 65 ++++++----- packages/node/src/trace-producers.ts | 18 +--- packages/trackers/README.md | 2 +- packages/trackers/src/node/index.test.ts | 4 +- packages/trackers/src/node/index.ts | 4 +- .../trackers/src/node/process-tracker.test.ts | 51 ++++++--- packages/trackers/src/node/process-tracker.ts | 57 ++++++---- .../trackers/src/node/runtime-readers.test.ts | 101 ++++++++++++++++-- packages/trackers/src/node/runtime-readers.ts | 84 +++++++++++++-- 16 files changed, 303 insertions(+), 118 deletions(-) create mode 100644 .changeset/ram-system-free-semantics.md diff --git a/.changeset/node-runtime-traces.md b/.changeset/node-runtime-traces.md index 0e2baf5e4..4d54a8781 100644 --- a/.changeset/node-runtime-traces.md +++ b/.changeset/node-runtime-traces.md @@ -9,6 +9,5 @@ Node, Bun and Deno now report more runtime traces in `traces.system`: - `v8_heap_size_limit`, `v8_heap_available`, `v8_heap_malloced`, `v8_heap_peak_malloced` and the ceiling-based `ram_js_heap_total` / `_used` / `_free` (`total` is the heap limit, not the committed heap). Node and Deno only; omitted on Bun, whose heap statistics are not a V8 ceiling. - `process_memory_limit` (the cgroup cap), reported only for a real cap: omitted when `process.constrainedMemory()` is 0, the 2^64 sentinel, or at least total RAM. - `process_uptime_s`. -- `ram_system_available`, on Node only: on Bun and Deno it ignores a container memory cap on Linux (measured), so it is omitted there. -`createNodeSystemTraceProducers` gains `measuresV8Heap` and `measuresAvailableMemory` (default `true`) for runtimes that cannot answer honestly. +`createNodeSystemTraceProducers` gains `measuresV8Heap` (default `true`) for runtimes that cannot answer honestly. diff --git a/.changeset/ram-system-free-semantics.md b/.changeset/ram-system-free-semantics.md new file mode 100644 index 000000000..00013a107 --- /dev/null +++ b/.changeset/ram-system-free-semantics.md @@ -0,0 +1,11 @@ +--- +'@bugsee/node': minor +'@bugsee/bun': minor +'@bugsee/deno': minor +'@bugsee/electron': minor +'@bugsee/trackers': minor +--- + +`ram_system_free` now means memory available to new work, as on Android, instead of raw free pages. On Node it is `os.freemem()` (libuv reads `MemAvailable` on Linux and `ullAvailPhys` on Windows); on Bun and Deno it is `MemAvailable` from `/proc/meminfo` on Linux, then `os.freemem()`. On macOS `os.freemem()` still counts only free pages and undercounts reclaimable memory. The value is omitted when no source gives a finite, non-negative number not above total RAM. + +The `ram_system_available` trace is removed (it was Node-only and never released in a stable version): `process.availableMemory()` equals `os.freemem()` without a cgroup limit and reads lower inside one, and it is not comparable on Bun and Deno. `@bugsee/trackers/node` drops the `availableMemory` stage and `createAvailableMemoryReader`, and gains `createSystemFreeReader`, `createProcMeminfoReader` and `parseMemAvailable`. `measuresAvailableMemory` now means "`os.freemem()` is memory available to new work" (default `true`; Bun and Deno pass `false`). diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index c997c8215..50adb6777 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -64,7 +64,7 @@ Read this first; then `docs/design/sdk-design.md` (Draft v3) for the full archit - `buildNodeEnvironment(input, probe)` β€” Β§8.6 envelope via injectable `SystemProbe`. Applies `optionsToWire` to `sdk.options` (dots β†’ colons; server treats dots as nested-document paths). - `createUncaughtExceptionProvider` / `createUnhandledRejectionProvider` β€” process-event detection, V8 stack parsed + scrubbed. - `createNodeHttpInterceptor` β€” wraps `node:http(s)` `request` + `get` (mechanism `'http'`), captures axios/got/node-fetch that bypass global fetch. **Transparent error handling**: re-raises the original error when it is the sole `'error'` listener so an otherwise-uncaught request error still crashes the app. -- `createNodeSystemTraceProducers` (the only built-in node trace source; the legacy `createNodeSystemMetricsSampler` / `createGuardedSystemMetricsSampler` were deleted in ST0β€²-D, `systemMetricsSampler` remains as a caller-supplied override) β€” process memory (rss/heapTotal/heapUsed/external/**arrayBuffers**), **system memory (`ram_system_total`/`ram_system_free` β€” Android parity)**, CPU user/system per-sample deltas + **normalized `cpu_usage_process` %** (over wall-time/cores), event-loop lag **mean/max/p99** + **utilization** (perf_hooks `monitorEventLoopDelay` + `eventLoopUtilization`). All readers injectable. **ST1 added** (measured on real node/bun/deno + a Linux cgroup container, 2026-10-17): `v8_heap_{size_limit,available,malloced,peak_malloced}` + ceiling-based `ram_js_heap_{total,used,free}` (Node/Deno; `measuresV8Heap:false` on Bun), `process_memory_limit` (only a real cap: `0`, the 2^64 sentinel and `>= totalmem` β€” which Bun answers when unconstrained β€” are omitted), `process_uptime_s`, `ram_system_available` (Node only; `measuresAvailableMemory:false` on Bun/Deno: under `docker -m 256m` they answer ~11 GB where Node answers 253 MB). Linux probes: Bun's unconstrained `constrainedMemory()` equals `totalmem` exactly, Deno's is `0`, both report a real cap under `-m`. **ST2 added:** `gc_count` / `gc_pause_ms` / `gc_pause_max_ms` per interval from a lazy `PerformanceObserver({entryTypes:['gc']})` (`trackers/gc-observer.ts`, started/stopped by the tracker with the other sources); a quiet interval is a true zero. The observer is BLIND on Bun and Deno (measured), so both launches pass `measuresGc:false` and never construct it. **ST3 added:** opt-in `captureDiskSpace` β†’ `disk_mem_free`/`disk_mem_total` (integer binary MB via `bytesToMegabytes`) for the volume of the launch's `effectiveDataDir` (`disk-space-producer.ts`, async `fs.promises.statfs` every 5 s, polled and NOT held so a failing statfs leaves a gap, generation-guarded against stale reads, one `onError` per failure streak). Appended by `nodeLaunchCore` (also to caller-supplied/Bun/Deno producer lists); absent with no data dir, never `/` or cwd. +- `createNodeSystemTraceProducers` (the only built-in node trace source; the legacy `createNodeSystemMetricsSampler` / `createGuardedSystemMetricsSampler` were deleted in ST0β€²-D, `systemMetricsSampler` remains as a caller-supplied override) β€” process memory (rss/heapTotal/heapUsed/external/**arrayBuffers**), **system memory (`ram_system_total`/`ram_system_free` β€” Android parity; C6: `free` is memory AVAILABLE to new work: `os.freemem()` on Node (libuv MemAvailable on Linux, ullAvailPhys on Windows), `/proc/meminfo` MemAvailable first on Bun/Deno Linux via `measuresAvailableMemory:false`; omitted if no source is plausible; macOS `freemem` undercounts reclaimable memory)**, CPU user/system per-sample deltas + **normalized `cpu_usage_process` %** (over wall-time/cores), event-loop lag **mean/max/p99** + **utilization** (perf_hooks `monitorEventLoopDelay` + `eventLoopUtilization`). All readers injectable. **ST1 added** (measured on real node/bun/deno + a Linux cgroup container, 2026-10-17): `v8_heap_{size_limit,available,malloced,peak_malloced}` + ceiling-based `ram_js_heap_{total,used,free}` (Node/Deno; `measuresV8Heap:false` on Bun), `process_memory_limit` (only a real cap: `0`, the 2^64 sentinel and `>= totalmem` β€” which Bun answers when unconstrained β€” are omitted), `process_uptime_s`, `ram_system_available` (RETIRED by C6: `process.availableMemory()` equals `os.freemem()` without a cgroup limit, reads lower inside one, and is not comparable on Bun/Deno where under `docker -m 256m` it answered ~11 GB vs Node's 253 MB). Linux probes: Bun's unconstrained `constrainedMemory()` equals `totalmem` exactly, Deno's is `0`, both report a real cap under `-m`. **ST2 added:** `gc_count` / `gc_pause_ms` / `gc_pause_max_ms` per interval from a lazy `PerformanceObserver({entryTypes:['gc']})` (`trackers/gc-observer.ts`, started/stopped by the tracker with the other sources); a quiet interval is a true zero. The observer is BLIND on Bun and Deno (measured), so both launches pass `measuresGc:false` and never construct it. **ST3 added:** opt-in `captureDiskSpace` β†’ `disk_mem_free`/`disk_mem_total` (integer binary MB via `bytesToMegabytes`) for the volume of the launch's `effectiveDataDir` (`disk-space-producer.ts`, async `fs.promises.statfs` every 5 s, polled and NOT held so a failing statfs leaves a gap, generation-guarded against stale reads, one `onError` per failure streak). Appended by `nodeLaunchCore` (also to caller-supplied/Bun/Deno producer lists); absent with no data dir, never `/` or cwd. - `createNodeSystemEventsSource` β€” process lifecycle (`process_started` on activate, `process_exiting`, **`process_before_exit`** clean-drain, `process_warning`, and **`process_signal`** for SIGTERM/SIGINT). Signal capture is PASSIVE: it emits the event, and only when the SDK is the sole handler does it remove itself and **re-raise** (`process.kill`) to restore Node's default termination β€” so it never hangs a process or hijacks an app's own signal handler. - **`launch(appToken, options)`** β€” the composition root: builds the transport (internal-tagged), api/uploader/upload pipeline, durable wrapper (when `dataDir`/`bundleStore` present), env builder, store (in-memory / file-backed), resolves the friendly options once via `NODE_OPTION_DEFINITIONS`, registers gated capture providers (consoleβ†’log; network umbrella with `node:http` folded in; system traces/events) + detection providers, calls `client.launch()`, runs durable `recover()` on start, installs the uncaughtException β†’ `flush(timeout)` β†’ `proc.exit(1)` policy (opt-out `exitOnUncaught`, default `shutdownTimeoutMs: 3000`), and augments `client.stop()` to remove its process listener. Returns the started `BugseeClient`. @@ -413,7 +413,7 @@ solid), in slices: - **TR6 (DONE, `feat/storage-tracker`):** domain **`StorageTracker`** (`packages/trackers/src/browser/storage-tracker.ts`), singleton per window via `createTrackerRegistry` (`storageTrackerFor(env, onError?)`, `resetStorageTracker`; keyed window -> navigator -> env object, `rebind` as PowerTracker). Wraps `navigator.storage.estimate()` + `persisted()`; ONE stage `storageEstimate` `{usageBytes?, quotaBytes?, persisted?}`. This is an ORIGIN quota ESTIMATE (browsers fuzz/pad it), NOT device free space. No change event, so it polls sparsely: on activation, on `visibilitychange` -> visible, then a slow timer (default 5 min via an injectable scheduler; ticks while the page is hidden are skipped). A field that is non-finite/negative/non-number is omitted (never 0); `persisted` only when boolean; an estimate with no usable field emits nothing. A rejected/throwing `estimate()`/`persisted()` is reported via `onError` and costs only its own field (host getters through `hostRead`); launch is never failed. **Retention rule (tested):** the LAST estimate survives the last unsubscribe (`current()` answers at once; a failed poll never erases it); timer and visibility listener do not (released, re-armed on the next subscriber, which also polls afresh). A single epoch counter is bumped by every poll/stop/reset, so a stale in-flight promise (after stop/reset, or superseded by a newer poll) is inert. `rebind` keeps every defined seam (undefined never clobbers) and applies it from the NEXT activation; a tracker that is attached keeps the navigator/document/scheduler it armed (only `onError` changes at once). Visibility-triggered polls are throttled to one per 60 s (`VISIBILITY_MIN_GAP_MS`, injectable `now`); the slow timer is not. Poll failures are reported ONCE per failure streak (reset by a poll without failures, and by `reset()`), not on every tick. A PARTIAL poll (one of `estimate()`/`persisted()` failed) merges: the failed call's retained fields are kept, answered fields replace, and the estimate's age advances only when usage/quota were refreshed. `currentFresh()` returns the retained estimate only while younger than 2x the poll interval (`current()` still returns it regardless). `StorageProducer` (browser `trace-producers.ts`, built after the `sensors:false` gate like the other sensor producers, so a `systemMetricsSampler` replaces it) emits the NEW JS-specific trace `storage_estimate` `{usage, quota}` in integer MB (`bytesToMegabytes`, floored; a missing key is omitted, `persisted` is not a trace) - NOT the Android `disk_mem_*` group. It is held/de-duplicated (`emitIfChanged`) because the poll period (5 min) far exceeds the default 60 s recording window; a non-held value would almost never appear in a report. `StorageProducer.onStart` seeds only from `currentFresh()` (never a snapshot older than 2x the interval). **OWNER DECISION PENDING:** a held polled value cannot be retracted, so after failed polls the last known estimate keeps being re-recorded every `refreshMs`. Alternatives: plain `emit` (the value would rarely land in a 60 s window) or a provider retract/release mechanism (same open question as the TR4 time traces). Usage under 1 MiB floors to 0 MB (an honest floor, not a measurement of zero). Shared by the WebView launch via the browser producers. Launch-level test proves launch goes through `storageTrackerFor` (the window's singleton holds the estimate). - **TR7 (DONE, `feat/environment-tracker`):** domain **`EnvironmentTracker`** (`packages/trackers/src/browser/environment-tracker.ts`), singleton per window via `createTrackerRegistry` (`environmentTrackerFor(env, onError?)`, `resetEnvironmentTracker`; keyed window -> navigator -> env object; `rebind` merges seams, never drops a defined one; a RUNNING tracker whose window/navigator/document/scheduler/interval changed detaches with the OLD seams, swaps in place, then re-attaches; `detectPrivateMode` turned on while running probes at once, turned off drops the result and any in-flight probe). Five stages: `language` `{language?, languages?, previous}` (`navigator.language(s)` + `languagechange`), `timezone` `{timeZone?, utcOffsetMinutes?, previous}` (no browser event, so re-read on a slow injectable timer, default 60 s with hidden-page ticks skipped, and on visibility -> visible; a DST shift is an offset change), `hints` `{cookiesEnabled?, secureContext?, crossOriginIsolated?, serviceWorkerControlled?, automation?, doNotTrack?, globalPrivacyControl?}`, `permissions` `{camera?, microphone?, geolocation?, notifications?, 'idle-detection'?: 'granted'|'denied'|'prompt'}` and `privateMode` `{private: 'yes'|'no'|'unknown', method?}`. `language`/`timezone` are CHANGE-ONLY (the first reading is a silent baseline held in `current()`, because they back `*_changed` events); `hints`/`permissions` are SNAPSHOT stages (first reading + every change); `privateMode` emits when its answer first arrives and when it changes. **Never prompts:** only `navigator.permissions.query()` is called (never requestPermission/getUserMedia/...), only the state STRING is kept, a PermissionStatus `change` refreshes it; a name the browser rejects with TypeError is omitted silently (Firefox does not know `camera`), other rejections are reported once per failure streak. **Private mode** is a HEURISTIC, never a certainty: one method `storage-quota` (`estimate().quota` under 120 MiB -> `yes`, at/over 1 GiB -> `no`, between or unreadable -> `unknown`; Chromium gives incognito a small fixed quota, Safari fuzzes). Omit-never-fabricate everywhere (empty/non-string language, NaN offset, non-boolean hints, unusable permission states are omitted; unknown DNT values omitted). Every host read goes through `hostRead` (a hostile getter costs only its field and is reported), a throwing `onError` never escapes. **Retention rule (tested):** the last language/time zone/hints/permissions/private-mode readings survive the last unsubscribe (and the change-only stages compare a restart against them); DOM listeners (languagechange, visibilitychange, PermissionStatus change), the timer and async work in flight do not (epoch tokens make a stale query/probe inert). **Events (`events.system`, `createBrowserSystemEventsSource`; the WebView launch shares the same source):** `language_changed` `{language?, languages?, previousLanguage?}`, `timezone_changed` `{timezone?, utcOffsetMinutes?, previousTimezone?, previousUtcOffsetMinutes?}`, `private_mode_detected` `{method?}` (ONLY for a `yes`; `no`/`unknown` never produce an event). Event names are free-form in `SystemEvent` (no registry/schema list exists to extend). **Launch option `captureEnvironmentHints`** (canonical `com.bugsee.option.capture.environment-hints`, browser launch only, default TRUE (opt-out), fail-closed boolean: anything but a boolean is OFF and reported) -> tracker `detectPrivateMode`; the WebView launch never enables it. **OWNER DECISION (2026-10-20, binding): private/incognito detection is OPT-OUT, ON by default** (the launch option keeps its name `captureEnvironmentHints`, default TRUE, `false` opts out, an invalid value is OFF and reported); still a tri-state heuristic (`yes`/`no`/`unknown`, method `storage-quota`), never a certainty. The decision covers private mode only, not other sensitive signals. The WebView launch still passes `detectPrivateMode: false` (no launch option there; a WebView's storage quota is not a private-window signal). **Not done / scope notes:** no `displayMode` stage (the UiTracker owns display-mode; `display_mode_changed` will be derived from it later); `hints` and `permissions` are tracker-level only, they have no wire consumer (the environment envelope schema is closed and has no field for them, so language/timezone were NOT added to `environment` either: `platform.locale`/`utc_offset` are still read once at launch by `buildBrowserEnvironment`, and the new events carry the later changes); **hints and permissions are NOT read by default (PR #84 review):** tracker env flags `observeHints` / `queryPermissions` (default false; a change while running re-attaches, turning one off drops its reading and, for permissions, the status listeners and in-flight queries); the browser system-events source passes both `false` explicitly (never inherited from the window's shared tracker), so a launch issues no `permissions.query()` and reads no hints until a real consumer sets them. Launch tests prove launch goes through `environmentTrackerFor` (the window's singleton holds the readings; mutating the source to `new EnvironmentTracker` fails them) and that private mode is ON by default and off with `captureEnvironmentHints: false`; the WebView launch has the same singleton test. **Review round 2:** persistent host-read failures of language/timezone/hints/visibility are reported once per failure streak (a clean run or `reset()` ends it); emitted stage payloads are copies, so a subscriber cannot mutate retained readings; the WebView launch now passes `document` + `scheduler` to the environment source; `resetEnvironmentTracker` is NOT re-exported from `@bugsee/browser` (reach teardown via `environmentTrackerFor(env).reset()`). **Round 3:** a host read that THROWS keeps that field's retained value (language, languages, time zone id, offset, each hint), so a transient failure never yields a fake `language_changed`/`timezone_changed`; `reset()` now drops all subscribers (`removeAllListeners`, as ApplicationTracker does) so the tracker re-activates for the next subscriber; a throwing `PermissionStatus.state` getter is reported once per streak. **Round 4:** per-permission-name streaks; a throwing state read, or a name whose re-query is rejected with a non-TypeError, keeps that name's retained state (a TypeError still omits it). **Round 5:** the browser system-events source subscribes to the tracker with ONE `onAny` (the activation read can emit a change made while the SDK was stopped, so per-stage subscriptions lost the later stages: a zone change alongside a language change vanished); the WebView launch passes `detectPrivateMode: false` explicitly (never inherits ON from an earlier launch on the window); stage payloads copy `previous` as well (a kept field shares its array). **PR review:** `privateMode` is no longer re-emitted on every activation: it emits when the answer first arrives and when it changes, a retained yes/no is not re-probed on a restart or a seam-moving rebind (an `unknown` is retried), and turning detection off then on re-detects; the browser events source always passes `detectPrivateMode` explicitly (omitted = false, never inherited); an answered-but-unusable permission state clears the stale entry (a failed/throwing read still retains it); private-probe getter failures (storage/estimate/quota) are reported once per streak; it stays a heuristic (constrained storage can false-positive). **Per-session delivery:** the tracker outlives sessions and never re-probes a retained yes/no, so the browser events source reads `current().privateMode` right after subscribing and re-emits `private_mode_detected` once for a retained `yes` (never for `no`/`unknown`, and never when this source opted out; the sink-side `detectPrivateMode` guard also covers the retained read). - **TR5 (implemented on `feat/process-tracker`, PR #83; multi-agent review rounds still in progress, one owner decision open β€” see "Known limit" below):** domain **`ProcessTracker`** (`packages/trackers/src/browser/process-tracker.ts`), singleton per window via `createTrackerRegistry` (`processTrackerFor(env, onError?)`, `resetProcessTracker`; keyed window -> performance -> env object, `rebind` merge-not-drop: a seam change on a RUNNING tracker first detaches every armed stage with the seams it was armed with, then swaps and restarts). It ABSORBS and replaces the per-signal `MemoryTracker` and `MainThreadLagTracker` (files + tests deleted; `MemoryProducer`/`MainThreadLagProducer` now subscribe to it; trace names and wire shapes unchanged). Five stages, each armed ONLY while it has listeners (via the `listenerCount(name)` / `onListenersChanged()` hooks `MultiKeyEmitterBase` already has on `main` from TR2; this PR does not touch the emitter; `start()`/`stop()` do nothing here): `heap` `{used, limit}` (`performance.memory`, polled; a figure that is not a finite non-negative number omits the reading), `mainThreadLag` `{lagMs}` (TIMER DRIFT, algorithm and visible-only gating unchanged: block >= 1 s always shows, shorter that crosses no due tick reads 0, reported once, fresh baseline each visible start), `idle` `{idleMs}` (NEW, ONE `requestIdleCallback` probe per sampling tick, never a loop and at most one in flight, visible pages only, `timeRemaining()` clamped to <= 50 ms; a tick whose callback never runs yields NO sample, never 0; omitted without rIC, e.g. Safari), `userIdle` `{userState: 'active'|'idle', screenState?: 'locked'|'unlocked'}` (NEW, Idle Detection API), `uptime` `{uptimeMs}` (`performance.now()`, omitted without a clock; no trace consumes it yet). **Idle Detection permission rule (binding): the SDK NEVER prompts.** `IdleDetector.requestPermission()` is never called; the detector starts ONLY when `navigator.permissions.query({name:'idle-detection'})` ALREADY reports `granted` (an engine that does not know the name rejects = stage inert, silent). The permission is re-queried on every activation and watched through its `change` event (granted later -> starts; revoked -> aborts and drops the tracker's retained state). Threshold floored at the spec's 60 s; stop aborts via `AbortController`; every async continuation is guarded by its run. **Retention rule (tested):** the last `userIdle` state survives the last unsubscribe (`currentUserIdle()`; `currentUserIdleFresh()`, which `UserIdleProducer` seeds from, answers only once the ARMED stage's detector has PUBLISHED in this run (permission re-confirmed and its `start()` settled; no age bound, a live detector reports changes only) and is undefined while the async permission re-query or `start()` is pending, or after a refusal/revoke; with NO armed stage it serves the state only while younger than 2 detector thresholds, via a new injectable `now` seam defaulting to `Date.now`, mirroring TR6's `currentFresh()`. A revoke while no stage is armed is therefore only noticed by the next activation's re-query (the plain `currentUserIdle()` read keeps the snapshot until then), but it can never seed a held trace); heap is read live; idle/lag/uptime keep nothing (a stale baseline would be a lie); timers, lifecycle subscription, pending probe and detector are released. New JS-specific traces (`BrowserTraceEnv` gains `requestIdleCallback`/`cancelIdleCallback`/`IdleDetector`/`AbortController`, bound/taken from the injected window by `browserTraceEnvFrom`): `main_thread_idle_ms` (ms, polled/not held; built under the same lifecycle gate as lag/fps) and `user_idle_state` (a STRING like `app_state`: `active` | `idle` | `locked`, where a locked screen wins over `userState`; held, de-duplicated; no trace at all unless the permission was already granted). **`user_idle_state` is OPT-IN (review P2; the maintainer's decision, PENDING OWNER CONFIRMATION): the host page's `idle-detection` grant shows only that the page was given the permission, not consent to record and upload idle/locked state. So `createBrowserSystemTraceProducers` builds `UserIdleProducer` only for `BrowserTraceEnv.captureUserIdle === true`, fed by the new browser + WebView launch option `captureUserIdle` (default false, strict boolean: any other value stays off and is reported; local key `com.bugsee.option.browser.capture-user-idle`, exported as `CAPTURE_USER_IDLE_OPTION_KEY`). Even when on, the tracker starts a detector only if the permission ALREADY reports `granted` (the SDK still never prompts). Without the opt-in the permission is not even queried. This applies ONLY to `user_idle_state`; private-mode detection is opt-out by a separate owner decision.** The viewer has no definition for either name yet (generic value block, design Β§13.3). **Known limit (OWNER DECISION PENDING β€” no retract mechanism invented):** `user_idle_state` is a HELD trace and the tracker emits nothing when the permission is revoked, so a producer that already published a value keeps having it re-recorded every `refreshMs` until the producer stops (the revoke only drops the tracker's retained copy and so stops NEW seeds; the seed is gated as above). Resolving it needs a decision on a retract/clear signal for held traces (same family as TR6's held `storage_estimate`). Other hardening from review: a hostile `performance.now` getter is reported exactly once in total (the factory reads silently, the tracker reports; only a SUCCESSFUL clock read is memoised per env, a failed one is retried on the next activation); `ProcessTracker.reset()` now drops every listener (like `ApplicationTracker`), so a later listener change cannot re-arm a stage for a gone subscriber; `browserTraceEnvFrom` now hands back stable bound closures per (window, function), so a no-op relaunch no longer restarts armed stages; a non-finite lag baseline omits that tick's `main_thread_lag_ms` instead of sending NaN; the gated teardown always closes the run. Launch-level test proves browser launch goes through `processTrackerFor` (the window's singleton can read the heap through launch's seams); the WebView launch shares the producers. `sensors:false` (a `systemMetricsSampler`) still builds only the battery producer. -- **TR8 part 1 (implemented on `feat/node-process-tracker`; Process only, Storage/disk is part 2 below):** the node/bun/deno **`ProcessTracker`** (`packages/trackers/src/node/process-tracker.ts`, `@bugsee/trackers/node`) ABSORBS and REPLACES `@bugsee/node`'s per-signal `ProcessStatsTracker` (files + tests deleted from `packages/node/src/trackers/`); `gc-observer`, `guarded-event-loop` and `runtime-readers` moved (with their tests) to `packages/trackers/src/node/` unchanged apart from `EventLoopSource` now living beside the histogram source. Singleton per process via the registry (`processTrackerFor(env, onError?)`, key `env.key` else the `process` object; `resetProcessTracker(key?)`); `rebind` merges (defined seams replace, undefined never clobber; an UNCHANGED relaunch restarts nothing; a changed seam tears every armed stage down with the OLD seams, the timer is cleared on the scheduler that armed it, then re-arms on the new ones; latest `onError` wins). Ten **per-stage-activated** stages (one shared unref'd timer exists only while some stage has a listener; each stage's machinery only while it is wanted): `memory`, `systemMemory`, `cpu` `{userDelta, systemDelta, processPct}`, `eventLoop` `{meanMs, maxMs, p99Ms}`, `utilization` `{utilization}`, `gc` `{count, pauseMs, maxPauseMs}`, `v8Heap`, `memoryLimit` `{bytes}`, `availableMemory` `{bytes}`, `uptime` `{seconds}`. Trace names and wire values are unchanged. Honesty rules are unchanged and still tracker-owned: a stage that cannot answer EMITS NOTHING (ELU zeros on Bun/Deno, an unsampled histogram, a blind/refusing GC observer, untrue heap/limit/available readings), and the runtime-identity GATES (`measuresEventLoopDelay`/`measuresV8Heap`/`measuresAvailableMemory`/`measuresGc`) are now tracker env flags that the platform composition roots (`@bugsee/{deno,bun}` via `createNodeSystemTraceProducers`) pass through; an injected source/reader wins over its gate. **Retention rule (stated and tested):** only the resolved seams and the "this runtime refused" memory inside the guarded sources survive the last unsubscribe; the CPU baseline, ELU baseline, histogram, GC interval and the last windowed sample all start FRESH on the next subscription. `current(stage)` reads stateless stages LIVE (guarded, copies) and answers the last emitted sample of a windowed stage (`cpu` is seeded with a zero-length window when it arms, so a producer has a baseline). Hardening: reporter indirection that swallows a throwing `onError`, generation-guarded timer callbacks (a timer whose clear failed never emits), each stage read isolated (one throwing reader drops only itself; a failed CPU read never advances the baseline), a failing source start leaves its stage unarmed (never half-armed, retried on the next listener change/rebind), a timer that cannot be armed unwinds the stages armed for it, one failing stop never strands another, emitted payloads are copies. `@bugsee/node`'s `trace-producers.ts` is now composition only (ten producers, each subscribed to ONE stage; `NodeTraceProducerDeps` = tracker env + `onError`), and `@bugsee/node` re-exports `processTrackerFor`/`resetProcessTracker`/`ProcessTracker` (and drops the `ProcessStatsTracker`/`ProcessStats` exports). **Behaviour notes:** (1) the tracker is one per PROCESS now, so a second producer set / relaunch shares it and its seams are rebound (tests that inject fakes must pass a private `key` or call `resetProcessTracker()`); (2) per-stage activation means the GC observer and the delay histogram exist only while their producer is subscribed (before, they ran whenever any producer was); (3) the ELU baseline is taken when its stage arms (before: when the producers were built), so the first sample no longer spans an idle gap; (4) the activation CPU/baseline read and the poll are per stage, so one failing reader no longer fails the whole poll (before: an `uptime` failure dropped the whole row); (5) there is NO CPU start value any more: before, the producer published a microsecond-window noise reading at start (`processPct` 7-43%, never a true share), now the tracker keeps its internal counters but the CPU producer has an empty `baseline()` and `current('cpu')` is undefined until the first tick (as for gc/event-loop-lag/utilization); an unusable core count (`os.cpus()` empty) now omits the cpu sample instead of emitting Infinity/NaN; (6) **seams merge, never drop:** the tracker outlives launches, so a later launch that omits `scheduler`/`onError`/a reader KEEPS the previous launch's (it can replace a seam, never shed one), and merely BUILDING a producer set rebinds the shared tracker (including the Bun/Deno default sets built before `...options` in their `launch.ts`); tests must use a private `key` or `resetProcessTracker()` (added to the afterEach of the node, bun, deno and elysia launch tests). **Tooling:** `@bugsee/trackers` gained `@types/node` (devDependency) and `tsconfig.json` now carries `types: ["node"]` for `src/node`; `tsconfig.portable.json` re-typechecks the portable root + browser entries WITHOUT node types (`pnpm typecheck` runs both) so a node global cannot leak into code shipped to browsers. `@bugsee/node` gained the `@bugsee/trackers` workspace dependency. Launch tests prove the default producers go through the registry accessor (mutating the producer factory to `new ProcessTracker` fails them) and that the Bun/Deno gates reach the shared tracker end to end. +- **TR8 part 1 (implemented on `feat/node-process-tracker`; Process only, Storage/disk is part 2 below):** the node/bun/deno **`ProcessTracker`** (`packages/trackers/src/node/process-tracker.ts`, `@bugsee/trackers/node`) ABSORBS and REPLACES `@bugsee/node`'s per-signal `ProcessStatsTracker` (files + tests deleted from `packages/node/src/trackers/`); `gc-observer`, `guarded-event-loop` and `runtime-readers` moved (with their tests) to `packages/trackers/src/node/` unchanged apart from `EventLoopSource` now living beside the histogram source. Singleton per process via the registry (`processTrackerFor(env, onError?)`, key `env.key` else the `process` object; `resetProcessTracker(key?)`); `rebind` merges (defined seams replace, undefined never clobber; an UNCHANGED relaunch restarts nothing; a changed seam tears every armed stage down with the OLD seams, the timer is cleared on the scheduler that armed it, then re-arms on the new ones; latest `onError` wins). Nine (ten before C6 removed `availableMemory`) **per-stage-activated** stages (one shared unref'd timer exists only while some stage has a listener; each stage's machinery only while it is wanted): `memory`, `systemMemory`, `cpu` `{userDelta, systemDelta, processPct}`, `eventLoop` `{meanMs, maxMs, p99Ms}`, `utilization` `{utilization}`, `gc` `{count, pauseMs, maxPauseMs}`, `v8Heap`, `memoryLimit` `{bytes}`, `uptime` `{seconds}`. Trace names and wire values are unchanged. Honesty rules are unchanged and still tracker-owned: a stage that cannot answer EMITS NOTHING (ELU zeros on Bun/Deno, an unsampled histogram, a blind/refusing GC observer, untrue heap/limit/available readings), and the runtime-identity GATES (`measuresEventLoopDelay`/`measuresV8Heap`/`measuresAvailableMemory`/`measuresGc`) are now tracker env flags that the platform composition roots (`@bugsee/{deno,bun}` via `createNodeSystemTraceProducers`) pass through; an injected source/reader wins over its gate. **Retention rule (stated and tested):** only the resolved seams and the "this runtime refused" memory inside the guarded sources survive the last unsubscribe; the CPU baseline, ELU baseline, histogram, GC interval and the last windowed sample all start FRESH on the next subscription. `current(stage)` reads stateless stages LIVE (guarded, copies) and answers the last emitted sample of a windowed stage (`cpu` is seeded with a zero-length window when it arms, so a producer has a baseline). Hardening: reporter indirection that swallows a throwing `onError`, generation-guarded timer callbacks (a timer whose clear failed never emits), each stage read isolated (one throwing reader drops only itself; a failed CPU read never advances the baseline), a failing source start leaves its stage unarmed (never half-armed, retried on the next listener change/rebind), a timer that cannot be armed unwinds the stages armed for it, one failing stop never strands another, emitted payloads are copies. `@bugsee/node`'s `trace-producers.ts` is now composition only (ten producers, each subscribed to ONE stage; `NodeTraceProducerDeps` = tracker env + `onError`), and `@bugsee/node` re-exports `processTrackerFor`/`resetProcessTracker`/`ProcessTracker` (and drops the `ProcessStatsTracker`/`ProcessStats` exports). **Behaviour notes:** (1) the tracker is one per PROCESS now, so a second producer set / relaunch shares it and its seams are rebound (tests that inject fakes must pass a private `key` or call `resetProcessTracker()`); (2) per-stage activation means the GC observer and the delay histogram exist only while their producer is subscribed (before, they ran whenever any producer was); (3) the ELU baseline is taken when its stage arms (before: when the producers were built), so the first sample no longer spans an idle gap; (4) the activation CPU/baseline read and the poll are per stage, so one failing reader no longer fails the whole poll (before: an `uptime` failure dropped the whole row); (5) there is NO CPU start value any more: before, the producer published a microsecond-window noise reading at start (`processPct` 7-43%, never a true share), now the tracker keeps its internal counters but the CPU producer has an empty `baseline()` and `current('cpu')` is undefined until the first tick (as for gc/event-loop-lag/utilization); an unusable core count (`os.cpus()` empty) now omits the cpu sample instead of emitting Infinity/NaN; (6) **seams merge, never drop:** the tracker outlives launches, so a later launch that omits `scheduler`/`onError`/a reader KEEPS the previous launch's (it can replace a seam, never shed one), and merely BUILDING a producer set rebinds the shared tracker (including the Bun/Deno default sets built before `...options` in their `launch.ts`); tests must use a private `key` or `resetProcessTracker()` (added to the afterEach of the node, bun, deno and elysia launch tests). **Tooling:** `@bugsee/trackers` gained `@types/node` (devDependency) and `tsconfig.json` now carries `types: ["node"]` for `src/node`; `tsconfig.portable.json` re-typechecks the portable root + browser entries WITHOUT node types (`pnpm typecheck` runs both) so a node global cannot leak into code shipped to browsers. `@bugsee/node` gained the `@bugsee/trackers` workspace dependency. Launch tests prove the default producers go through the registry accessor (mutating the producer factory to `new ProcessTracker` fails them) and that the Bun/Deno gates reach the shared tracker end to end. - **TR8 part 2 (implemented on `feat/node-storage-tracker`; Storage/disk):** the node/bun/deno **`StorageTracker`** (`packages/trackers/src/node/storage-tracker.ts`, `@bugsee/trackers/node`) ABSORBS the statfs polling of `@bugsee/node`'s `disk-space-producer.ts`, which is now composition only (one `StorageTracker` stage `disk` -> `disk_mem_free`/`disk_mem_total`; the old timer/streak/generation machinery and its tests were deleted; the producer tests were rewritten over the tracker). Singleton per VOLUME IDENTITY (`storageTrackerFor(env, onError?)`; key = the interned RESOLVED data dir, so launches over the same dir share one tracker and launches over different dirs get different ones; an explicit `env.key` overrides (tests); no data dir -> the shared inert `process`-keyed tracker; `resetStorageTracker(key?: object | dir)` drops one, no argument drops all). ONE stage, `disk` `{freeBytes, totalBytes}` (bytes; the producer converts to integer binary MB with `bytesToMegabytes`, free then total, `hold:false`, so a failing statfs leaves a gap). Activation is by listener: the first listener reads the data dir's volume at once and arms an unref'd 5 s timer (injectable scheduler/`intervalMs`); no listener, no data dir, or `statfs: null`/no `fs.promises.statfs` (Node < 18.15, as the old producer handled it) means no timer and no read. Reads never overlap (in-flight latch), every read and timer callback is guarded by the generation that armed it (a stop, a path change or a seam change abandons it: it can neither emit nor report), failures are reported ONCE per failure streak (a success, an unsane answer, a new run or a new path starts a new one), an unsane answer (non-positive block size/total, negative or non-finite free, overflowing product, non-numbers) is omitted without an error and never zeroed (a full disk is a true 0 free). `rebind` merges seams within one key (defined replaces, undefined never clobbers; `statfs: null` is a defined seam): `onError`/`scheduler`/`statfs`/`intervalMs` are latest-launch-wins per key, while the data dir is part of the key, so a running launch can never be redirected to (or have its failures reported to) another launch's dir/`onError`; a CHANGED seam while a listener is attached tears the poll down on the scheduler that armed it and starts again at once (a changed path is re-read immediately and the old path's reading and failure streak do not leak); an unchanged relaunch restarts nothing; idle rebinds only store. Merely BUILDING the producer rebinds the shared tracker. **Retention rule (stated and tested):** only the merged seams survive the last unsubscribe; the last reading does not (`current()` is undefined with no listener, and is dropped on a failed/unsane read and on a path change); payloads and `current()` are copies. Hardening: reporter indirection that swallows a throwing `onError`, a timer that cannot be armed is reported and leaves the tracker inert, a throwing `clearInterval` is reported. The disk producer is NOT built when the legacy `systemMetricsSampler` replaces the producer list (it would never start, and building it touches the shared tracker). Launch tests wrap `storageTrackerFor` and prove the opt-in launch goes through it (mutating the producer to `new StorageTracker` fails) and that no tracker is requested when the opt-in is off or there is no data dir. `@bugsee/node` also re-exports `storageTrackerFor`/`resetStorageTracker`/`StorageTracker`. **Behaviour notes:** (1) the tracker is one per DATA DIR, so a second launch over the same dir shares it (and hands it its `onError`/seams) while a launch over another dir has its own (tests that inject `diskStatfs` must pass a private `key` or call `resetStorageTracker()`; added to the node launch test afterEach); (2) within one dir, seams merge, so a later launch without `diskStatfs`/`scheduler` keeps an earlier launch's; (3) wire behaviour is unchanged (each producer polls its own dir and reports to its own `onError`, as the pre-tracker code did); a relaunch over the same dir with a changed seam re-reads at once. An earlier revision keyed the singleton on the `process` object and let a later launch's data dir replace a running launch's: fixed in review. - **TR9 part 1 (implemented on `feat/electron-process-tracker`; Electron main-process PROCESS tracker; power/screen/window events are in part 2 below):** the **`ElectronProcessTracker`** (`packages/trackers/src/electron/process-tracker.ts`, `@bugsee/trackers/electron`, previously an empty placeholder) ABSORBS `@bugsee/electron`'s `GpuInfoCache` (file, tests and `mapGpuInfo` moved: `mapGpuInfo` now lives in `packages/trackers/src/electron/gpu-info.ts` and returns a neutral `ElectronGpu`, structurally the `HardwareGpu` of `@bugsee/node`). Singleton per `app` object (`electronProcessTrackerFor({app, scheduler?, intervalMs?, key?}, onError?)`, `resetElectronProcessTracker(key)`; no `app` and no `key` throws, a shared anonymous tracker would have no owner). Electron is INJECTED as the structural `ElectronAppSource` (`getAppMetrics`/`getGPUInfo`/`on`/`removeListener`|`off`); the package depends on neither `electron` nor the DOM. THREE stages: `appMetrics` (one unref'd timer, default 1 s, armed only while it has a listener; `{processes: [{type, pid, cpuPct?, workingSetBytes?, peakWorkingSetBytes?, privateBytes?}]}`, Electron's KiB converted to bytes, a field Electron did not give is omitted never zeroed, a process with no usable metric is dropped, an empty/non-array result emits nothing; it is WINDOWED, so arming makes ONE discarded PRIMING `getAppMetrics` read and the first emission is the first tick; Chromium returns 0 on the FIRST CPU call per process (Electron keeps one metrics object per child process), so the tracker remembers the pids of the previous read and omits `cpuPct` for a pid's first sighting (a renderer or restarted GPU/utility process appearing later, same type new pid), and where Electron reports `cpu.cumulativeCPUUsage` a process without it also has no `cpuPct` (Electron sends 0 "for compatibility"); `cpuPct` is the share of the WHOLE machine, 0-100; `current('appMetrics')` is the last sample of the run), `childProcessGone` (`app.on('child-process-gone')` attached only while a listener exists and removed with the same function when the last leaves; `{type, reason, exitCode?, name?}`, malformed details ignored; not attached at all when the app has neither `removeListener` nor `off`, since it could never be released), and `gpu` (`requestGpuInfo(type = 'basic')` / `cancelGpuInfo()` / `current('gpu')`: a USABLE settled value is kept and not re-requested for the same type; it asks again after a rejection/throw/unmappable result or for a DIFFERENT type, and a failed re-ask keeps the earlier usable value; a rejection or throw is reported and no unhandled rejection results, a late result after `cancelGpuInfo()` is ignored; the `gpu` stage fires on each usable settle). `render-process-gone` is NOT part of the tracker: it is an incident path and `renderer-gone.ts` is unchanged. Seams merge never drop, `rebind` on a changed seam tears the run down with the OLD seams and re-arms (re-primes) on the new, generation-guarded timer callbacks, a throwing/async reporter never escapes. **Retention rule (stated and tested):** only the merged seams and the once-only GPU result survive the last unsubscribe; the priming read is repeated and the last sample dropped; `reset()` drops everything including the GPU. **Producers in `@bugsee/electron` (composition only):** `system-traces.ts` (`createElectronSystemTraceProducers(tracker)` -> one `app_metrics` producer) and `system-events.ts` (`createElectronSystemEventsSource(inner, tracker, onError?)`, a LAZY mux: nothing attached at construction; on the first subscriber it subscribes to the inner node source (its `process_started` and signal/exit handlers) AND the tracker's `childProcessGone`, releasing both, each guarded, on the last unsubscribe; it never emits `process_started` itself). **Wire shapes:** trace `app_metrics` = `{processes: [{type, pid, cpu_percent?, working_set_mb?, peak_working_set_mb?, private_mb?}]}` (Electron's process type verbatim, `cpu_percent` the whole-machine share rounded to 2 decimals, integer binary MB via `bytesToMegabytes`, `hold:false` so a failing read leaves a gap; JS-specific name, neither Android nor the viewer has an entry, so it is an open object like `storage_estimate`; **viewer support is UNCONFIRMED (Q5)** and flat per-type totals are the alternative shape); event `child_process_gone` on `events.system` with params `{type, reason, exitCode?, name?}` (`exitCode` stays camelCase: the existing multi-word event params, e.g. the browser's `previousLanguage`, are camelCase; it also fires with `reason: 'clean-exit'`). **`@bugsee/node`:** new advanced launch option `wrapSystemEventsSource(inner)` (the seam P3 asks for): the provider subscribes to the SOURCE it returns, a throwing factory is reported and the plain node source is used. **`launchMain`:** with an `app` and when this is NOT a repeat call (a repeat is detected up front from the carrier client, exactly `launchCore`'s own test, so it can never rebind the running launch's shared trackers) it builds the tracker THROUGH `electronProcessTrackerFor`, passes `systemTraceProducers = [...(caller's ?? createNodeSystemTraceProducers({scheduler, onError})), ...electron producers]` (not when the legacy `systemMetricsSampler` is set), composes `wrapSystemEventsSource` (a caller wrapper first, ours around it), and serves `hardware.gpu` from `tracker.current('gpu')` (same field-wise `hardwareExtras` precedence and `sanitizeHardwareGpu` as ST6a; `gpuInfoType` still `'basic'|'complete'`); the GPU read is requested once on the FIRST launch and cancelled in `client.stop()`. `@bugsee/electron` gained the `@bugsee/trackers` and `@bugsee/capture` workspace dependencies. **Tests:** tracker unit tests (100% with the mutator loop), producer/mux unit tests, launch-level tests (accessor spy: mutating launchMain to `new ElectronProcessTracker` fails; node + Electron traces both present with no name twice; a throwing `getAppMetrics` leaves the node producers emitting) and a real-launch integration test (`system-telemetry.integration.test.ts`: `app_metrics` next to node traces in the uploaded bundle, `child_process_gone` on `events.system`, `captureSystemEvents:false` -> no node handlers and no `child-process-gone` listener, `client.stop()` releases handlers, listener and timers). **Not verified without a real Electron (source-verified by review, not run):** the real `getAppMetrics` shape and units (KiB), `child-process-gone` details, and `getGPUInfo` output. - **TR9 part 2 (implemented on `feat/electron-power-display-app-trackers`; the remaining Electron-main DOMAIN trackers):** three more per-object singleton trackers in `@bugsee/trackers/electron`, all with Electron INJECTED structurally (no electron/DOM dependency), a shared `stage-tracker.ts` (`ElectronStageTracker` base + `bindAll`: per-STAGE lazy attach on a stage's first listener and release on its last, all-or-nothing attach with rollback, a source with no `removeListener`/`off` is never attached to, every wrapper is liveness-guarded so a listener whose removal failed can never emit, a throwing/async reporter is absorbed; `process-tracker.ts` now shares its `reportTo`). **`ElectronPowerTracker`** (`electronPowerTrackerFor({powerMonitor}, onError?)`, `resetElectronPowerTracker(key)`; keyed on the monitor; stages `suspendResume` `{state:'suspend'|'resume'}`, `lockScreen` `{state:'lock'|'unlock'}` (macOS/Windows; never fires on Linux), `powerSource` `{source:'ac'|'battery'}`; `current('powerSource')` is a LIVE `isOnBatteryPower()` read, undefined without the method / non-boolean / throw (reported), never guessed; `thermal-state-change`/`speed-limit-change` deliberately NOT mapped: macOS-only and the thermal state is not Android's int enum). **`ElectronDisplayTracker`** (`electronDisplayTrackerFor({screen}, onError?)`; stages `displayAdded`/`displayRemoved` -> `DisplayInfo`, `displayMetricsChanged` -> `{display, changed: string[]}`, `displays` -> `{displays: DisplayInfo[]}` re-read from `getAllDisplays()` after any of the three; `current('displays')` is live; `DisplayInfo = {id, width, height, scaleFactor?, rotation?: 0|90|180|270, internal?, refreshRate?}` from Electron's `size` (bounds fallback), `label`/position/`workArea` are NOT kept, a display with no finite id or positive size is dropped, an empty/unreadable list is undefined, never `[]`). **`ElectronApplicationTracker`** (`electronApplicationTrackerFor({app, BrowserWindow?}, onError?)`, keyed on `app`; `rebind` re-arms when the `BrowserWindow` seam changes; stages `windowFocus` `{focused, windowId?}`, `windowVisibility` `{visible, windowId?}`, `rendererResponsiveness` `{responsive, webContentsId?}`; each stage watches the objects that EXIST at arm time (`BrowserWindow.getAllWindows()`, and each window's `webContents`) AND those created later (`app.on('browser-window-created')` / `app.on('web-contents-created')`), binds each object once, forgets it on `closed`/`destroyed` without touching the dead object, skips `isDestroyed()` objects at bind and at release, tolerates a throwing `getAllWindows`/`id`/`isDestroyed`; **the hang pair is on `webContents` ONLY** because `BrowserWindow` re-emits it; ids are Electron's numeric `id`, omitted when absent; titles/URLs are never read). **Wire names (`@bugsee/electron`):** `events.system` `power_suspend`, `power_resume`, `power_lock`, `power_unlock`, `power_ac`, `power_battery` (no params); `display_added`/`display_removed` params `{id, width, height, scaleFactor?, rotation?, internal?, refreshRate?}`, `display_metrics_changed` params the same plus `changed: string[]`; `window_focus`/`window_blur`/`window_show`/`window_hide` params `{windowId?}`; `renderer_unresponsive`/`renderer_responsive` params `{webContentsId?}` (snake_case names like `process_*`/`child_process_gone`, camelCase params like `exitCode`). Trace **`electron_displays`** = `{displays: [{id, width, height, scale_factor?, rotation?, internal?, refresh_rate_hz?}]}`, a HELD step trace (`emitIfChanged`: baseline at start, then the fresh list after each display change), absent when Electron gives no usable list. **Name choice:** `displays` stays RESERVED: nothing in `@bugsee/protocol`/`@bugsee/capture` defines an Android-shaped display list (only a comment that mobile-only `displays` is not sampled) and the viewer shape is unconfirmed (Q5), so the JS-specific `electron_displays` is used. `system-events.ts` mux now takes `{process?, power?, display?, application?}` and forwards all of the above lazily (nothing attached at construction or with `captureSystemEvents:false`; every release guarded); `system-traces.ts` `createElectronSystemTraceProducers({process?, display?})` adds the displays producer. `LaunchMainOptions` gains optional `powerMonitor`, `screen`, `BrowserWindow` (destructured out of `...nodeOptions`); `ElectronAppLike` gains `on('browser-window-created'|'web-contents-created')` and widened `removeListener`/`off`; each tracker is built THROUGH its registry accessor, skipped on a repeat launch (carrier client present) and absent when its object was not injected (a `powerMonitor` alone still gets the mux, a `screen` alone still gets the displays producer; the legacy `systemMetricsSampler` still suppresses producers). **Tests:** per-tracker unit tests with the mutator loop (about 40 mutations over the three trackers/base, 0 survivors after strengthening: forgetting on closed/destroyed, release skipping destroyed objects, rotation mapping), mux/producer unit tests, launch-level accessor spies (mutating any of the three to `new` fails) and real-launch integration tests (events + trace in the uploaded bundle, a window created AFTER launch records focus, `webContents` hang recorded ONCE although the window re-emits it and `win.emit('unresponsive')` alone records nothing, option off -> no listeners, `client.stop()` -> all released, a throwing Electron getter never fails launch, a repeat launch leaves the running trackers' reporter untouched). **NOT verified without a real Electron (source/doc-verified, not run):** the real `powerMonitor` event firing and `isOnBatteryPower()` semantics per OS, the real `Display` object shape (`size`, `displayFrequency`, `rotation`) and `display-metrics-changed` argument order `(event, display, changedMetrics)`, `browser-window-created`/`web-contents-created` ordering, `BrowserWindow` re-emitting `unresponsive` after ~50 ms, and `webContents` `destroyed`/window `closed` timing. **Review fixes (#91):** every host property read in `isReleasable`/`bindAll`/`current()` is guarded (Electron's real `screen` is a Proxy that throws on ANY property read before app ready: a throwing object = that domain off, reported, never a failed launch); `sync()` guards `attachStage`; the mux isolates EVERY subscription in `onActivate` (it never throws, so the provider always gets its unsubscribe and `stop()` releases the inner source's handlers too); display id -1 ('invalid or not yet known') is dropped, -10 (virtual unified display) is kept as reported; `on-ac` (darwin/win32) and `on-battery` (darwin only) are platform dependent and `current('powerSource')` is the live truth; new launch option `captureWindowEvents` (default true, opt-out) for the window domain, which is ON whenever `app` is passed. **OPEN OWNER DECISION (held values), now also covering `electron_displays`:** a refresh that cannot read a usable list emits nothing and a held trace cannot be retracted, so the previous list stays held and is re-recorded every `refreshMs` (absent only before the first emit); same class as `storage_estimate` / `user_idle_state`. Known limits: a `webContents` that existed before `launchMain` and has no `BrowserWindow` (an earlier `BrowserView`/``) is not discovered; `screen` must be injected after `app` is ready (a throwing one turns the display domain off); viewer support for `electron_displays` and the new event names is unconfirmed (Q5). diff --git a/packages/bun/src/launch.test.ts b/packages/bun/src/launch.test.ts index 22ef06482..889cee6f4 100644 --- a/packages/bun/src/launch.test.ts +++ b/packages/bun/src/launch.test.ts @@ -129,7 +129,7 @@ describe('@bugsee/bun launch', () => { expect(names).not.toContain('cpu_usage_process'); // no CPU start value: it begins with the first sampled window }); - it('opts out of the V8 heap, available-memory and gc traces (Bun: JSC heap, not comparable availableMemory, blind GC observer)', () => { + it('opts out of the V8 heap and gc traces and reads MemAvailable first for ram_system_free (Bun: JSC heap, not comparable availableMemory, blind GC observer)', () => { track(launchCore('tok', base()).client); expect(createNodeSystemTraceProducers).toHaveBeenCalledWith( expect.objectContaining({ @@ -436,7 +436,6 @@ describe('@bugsee/bun β€” the runtime gates reach the shared ProcessTracker', () track(launchCore('tok', base({ scheduler, captureSystemTraces: true })).client); const tracker = processTrackerFor(); // the launch went through the registry accessor: same `process` singleton expect(tracker.current('v8Heap')).toBeUndefined(); - expect(tracker.current('availableMemory')).toBeUndefined(); const seen: string[] = []; const off = tracker.onAny((name) => void seen.push(name)); for (const cb of calls) cb(); @@ -444,6 +443,5 @@ describe('@bugsee/bun β€” the runtime gates reach the shared ProcessTracker', () expect(seen).toContain('memory'); expect(seen).not.toContain('v8Heap'); expect(seen).not.toContain('gc'); - expect(seen).not.toContain('availableMemory'); }); }); diff --git a/packages/bun/src/launch.ts b/packages/bun/src/launch.ts index fbd0507a2..8c596f0ed 100644 --- a/packages/bun/src/launch.ts +++ b/packages/bun/src/launch.ts @@ -21,9 +21,10 @@ export function launchCore(appToken: string, options: BugseeLaunchOptions = {}): systemProbe: bunSystemProbe, systemTraceProducers: createNodeSystemTraceProducers({ // JSC's heap statistics are not a V8 ceiling (`limit - used` is meaningless; ~1000x Node's cost per call), - // and on Linux `availableMemory` ignores the container cap (measured under `docker -m 256m`: 11.2 GB vs - // Node's 253 MB), so those traces are omitted here. + // so the V8 heap traces are omitted here. measuresV8Heap: false, + // Bun < 1.3.13's `os.freemem()` is not MemAvailable on Linux, so `ram_system_free` reads /proc/meminfo + // MemAvailable first there, then os.freemem(). `process.availableMemory()` is never used. measuresAvailableMemory: false, // `PerformanceObserver('gc')` is BLIND on Bun (0 entries after heavy churn β€” measured): a quiet-looking // zero would be a lie, so no observer is constructed and the gc traces are omitted. diff --git a/packages/deno/src/launch.test.ts b/packages/deno/src/launch.test.ts index 842c5e329..f4bece19c 100644 --- a/packages/deno/src/launch.test.ts +++ b/packages/deno/src/launch.test.ts @@ -312,7 +312,7 @@ describe('@bugsee/deno β€” the event-loop metrics Deno cannot measure', () => { ); }); - it('opts out of ram_system_available (a different quantity) and gc (blind observer) and keeps the V8 heap (real V8)', () => { + it('reads MemAvailable first for ram_system_free (a different quantity) and gc (blind observer) and keeps the V8 heap (real V8)', () => { track(launchCore('tok', base()).client); const arg = vi.mocked(createNodeSystemTraceProducers).mock.calls[0]?.[0]; expect(arg?.measuresAvailableMemory).toBe(false); @@ -432,7 +432,6 @@ describe('@bugsee/deno β€” the runtime gates reach the shared ProcessTracker', ( }; track(launchCore('tok', base({ scheduler, captureSystemTraces: true })).client); const tracker = processTrackerFor(); // the launch went through the registry accessor: same `process` singleton - expect(tracker.current('availableMemory')).toBeUndefined(); expect(tracker.current('v8Heap')?.limit).toBeGreaterThan(0); const seen: string[] = []; const off = tracker.onAny((name) => void seen.push(name)); @@ -441,6 +440,5 @@ describe('@bugsee/deno β€” the runtime gates reach the shared ProcessTracker', ( expect(seen).toContain('memory'); expect(seen).not.toContain('eventLoop'); expect(seen).not.toContain('gc'); - expect(seen).not.toContain('availableMemory'); }); }); diff --git a/packages/deno/src/launch.ts b/packages/deno/src/launch.ts index f4bda976b..8f52f186d 100644 --- a/packages/deno/src/launch.ts +++ b/packages/deno/src/launch.ts @@ -28,8 +28,8 @@ export function launchCore(appToken: string, options: BugseeLaunchOptions = {}): // its own tell (a zero `idle`), so it needs no flag. systemTraceProducers: createNodeSystemTraceProducers({ measuresEventLoopDelay: false, - // Deno's `process.availableMemory()` is not the Node quantity: 23 GB vs 3.4 GB on one macOS host, and on - // Linux it ignores the container cap (11.2 GB under `docker -m 256m` vs Node's 253 MB). + // Deno's `process.availableMemory()` is not comparable (0 on Windows, includes inactive pages on macOS), so it + // is never used; `ram_system_free` reads /proc/meminfo MemAvailable first on Linux, then os.freemem(). measuresAvailableMemory: false, // `PerformanceObserver('gc')` is BLIND on Deno too (0 entries, also with --v8-flags=--expose-gc): omit. measuresGc: false, diff --git a/packages/node/src/trace-producers.test.ts b/packages/node/src/trace-producers.test.ts index 4cb3f0505..aa9ccbf39 100644 --- a/packages/node/src/trace-producers.test.ts +++ b/packages/node/src/trace-producers.test.ts @@ -47,7 +47,6 @@ const constDeps = (over: NodeTraceProducerDeps = {}): NodeTraceProducerDeps => ( uptime: () => 42.7, v8Heap: () => ({ limit: 1000, used: 300, available: 700, malloced: 11, peakMalloced: 12 }), memoryLimit: () => 500, - availableMemory: () => 250, ...over, }); @@ -134,7 +133,6 @@ describe('createNodeSystemTraceProducers', () => { ['ram_js_heap_free', 700], ['ram_js_heap_total', 1000], ['ram_js_heap_used', 300], - ['ram_system_available', 250], ['ram_system_free', 400], ['ram_system_total', 1000], ['v8_heap_available', 700], @@ -195,10 +193,9 @@ describe('createNodeSystemTraceProducers', () => { expect(h.got.has('process_memory_rss')).toBe(true); }); - it('omits process_memory_limit / ram_system_available when their readers answer undefined', () => { - const h = run({ memoryLimit: () => undefined, availableMemory: () => undefined }); + it('omits process_memory_limit when its reader answers undefined', () => { + const h = run({ memoryLimit: () => undefined }); expect(h.got.has('process_memory_limit')).toBe(false); - expect(h.got.has('ram_system_available')).toBe(false); expect(h.got.get('process_uptime_s')).toBe(42); }); @@ -209,36 +206,36 @@ describe('createNodeSystemTraceProducers', () => { for (const k of h.got.keys()) expect(k).not.toMatch(/^(v8_heap_|ram_js_heap_)/); }); - it('measuresAvailableMemory:false omits ram_system_available even where the runtime answers (Bun/Deno)', () => { - const { availableMemory: _off, ...base } = constDeps({ eventLoop }); - const h = harness({ ...base, measuresAvailableMemory: false }); - h.startAll(); - expect(h.got.has('ram_system_available')).toBe(false); - }); - - it('an injected reader wins over the measures* flag (as for the event-loop source)', () => { - const h = harness({ - ...constDeps({ eventLoop }), - measuresV8Heap: false, - measuresAvailableMemory: false, - }); - h.startAll(); - expect(h.got.get('v8_heap_size_limit')).toBe(1000); - expect(h.got.get('ram_system_available')).toBe(250); + it('ram_system_free is os.freemem() on Node and MemAvailable-first when measuresAvailableMemory is false; total stays total', () => { + const { systemMemory: _s, ...base } = constDeps({ eventLoop }); + const run1 = (over: NodeTraceProducerDeps) => { + const h = harness({ ...base, memoryLimit: () => undefined, ...over }); + h.startAll(); + return h.got; + }; + const meminfo = () => 'MemAvailable: 3 kB\n'; + expect(run1({ meminfo, freeMemory: () => 9 }).get('ram_system_free')).toBe(9); + expect( + run1({ measuresAvailableMemory: false, meminfo, freeMemory: () => 9 }).get( + 'ram_system_free', + ), + ).toBe(3072); + expect( + run1({ measuresAvailableMemory: false, meminfo: () => undefined, freeMemory: () => 9 }).get( + 'ram_system_free', + ), + ).toBe(9); + const none = run1({ freeMemory: () => Number.NaN }); + expect(none.has('ram_system_free')).toBe(false); + expect(Number(none.get('ram_system_total'))).toBeGreaterThan(0); }); it('an explicit undefined reader does not clobber the wired default (measures* true)', () => { - const { - v8Heap: _a, - memoryLimit: _b, - availableMemory: _c, - ...base - } = constDeps({ eventLoop }); + const { v8Heap: _a, memoryLimit: _b, ...base } = constDeps({ eventLoop }); const h = harness({ ...base, v8Heap: undefined, memoryLimit: undefined, - availableMemory: undefined, }); h.startAll(); expect(Number(h.got.get('v8_heap_size_limit'))).toBeGreaterThan(0); // the real node default, not absent @@ -429,7 +426,7 @@ describe('createNodeSystemTraceProducers', () => { it('gate: creating the producers constructs no histogram and starts no timer until start', () => { const { perfHooks, state } = fakePerfHooks(); const h = harness({ ...constDeps(), perfHooks }); - expect(h.producers).toHaveLength(10); + expect(h.producers).toHaveLength(9); expect(state.monitor).toBe(0); expect(h.spy.set).toBe(0); h.producers[0]?.start({ emit: () => {} }); // memory: arms the shared timer only @@ -543,9 +540,8 @@ describe('createNodeSystemTraceProducers', () => { await new Promise((r) => setTimeout(r, 120)); tick?.(); for (const p of ps) p.stop(); - // `process_memory_limit` exists only inside a real cgroup cap and `ram_system_available` only on - // Node >= 20.13, so each is checked for what the host can answer rather than demanded. - const optional = ['process_memory_limit', 'ram_system_available']; + // `process_memory_limit` exists only inside a real cgroup cap, so it is checked for what the host can answer. + const optional = ['process_memory_limit']; expect([...got.keys()].filter((k) => !optional.includes(k)).sort()).toEqual([ 'cpu_usage_process', 'cpu_usage_system', @@ -573,8 +569,9 @@ describe('createNodeSystemTraceProducers', () => { 'v8_heap_peak_malloced', 'v8_heap_size_limit', ]); - expect(got.has('ram_system_available')).toBe( - typeof (process as { availableMemory?: unknown }).availableMemory === 'function', + expect(got.has('ram_system_available')).toBe(false); // retired + expect(Number(got.get('ram_system_free'))).toBeLessThanOrEqual( + Number(got.get('ram_system_total')), ); expect(Number(got.get('v8_heap_size_limit'))).toBeGreaterThan(0); for (const v of got.values()) expect(Number.isFinite(v)).toBe(true); diff --git a/packages/node/src/trace-producers.ts b/packages/node/src/trace-producers.ts index b4ff7de89..15f1325c6 100644 --- a/packages/node/src/trace-producers.ts +++ b/packages/node/src/trace-producers.ts @@ -6,7 +6,7 @@ import { processTrackerFor, } from '@bugsee/trackers/node'; -// Node `traces.system` producers (mirrors the mobile tracker/producer split): ten producers, each subscribed to ONE +// Node `traces.system` producers (mirrors the mobile tracker/producer split): nine producers, each subscribed to ONE // stage of the shared per-process ProcessTracker (`@bugsee/trackers/node`, the abstraction layer over the runtime's // process APIs). This file is COMPOSITION only: which stage feeds which trace names, plus the runtime-identity gates // the platform packages pass through (`measures*`). The tracker owns every runtime read, its lifetime and its @@ -59,7 +59,8 @@ class SystemMemoryProducer extends StageProducer<'systemMemory'> { } protected publish(m: ProcessEvents['systemMemory']): void { this.emit('ram_system_total', m.total); - this.emit('ram_system_free', m.free); + // memory available to new work (Android parity), absent when no source answers + if (m.free !== undefined) this.emit('ram_system_free', m.free); } } @@ -133,16 +134,6 @@ class MemoryLimitProducer extends StageProducer<'memoryLimit'> { } } -class AvailableMemoryProducer extends StageProducer<'availableMemory'> { - readonly name = 'system-memory-available'; - constructor(tracker: ProcessTracker) { - super(tracker, 'availableMemory'); - } - protected publish(m: ProcessEvents['availableMemory']): void { - this.emit('ram_system_available', m.bytes); - } -} - // Emitted every tick, never held: a quiet interval is a TRUE zero (the observer is running), and a source that // stops answering must be omitted rather than re-recorded from a held value. No baseline: the interval opens at // activation, so nothing has been observed yet (a zero would be invented). @@ -172,7 +163,7 @@ class UptimeProducer extends StageProducer<'uptime'> { /** * The tracker seams plus the platform GATES (`measuresEventLoopDelay`, `measuresV8Heap`, `measuresAvailableMemory`, * `measuresGc`; see {@link ProcessTrackerEnv}) β€” runtime-identity facts the platform packages pass in: Deno gates the - * event-loop histogram, Bun the V8 heap, both the available-memory and GC readers. + * event-loop histogram, Bun the V8 heap, both the os.freemem()-is-available assumption and the GC reader. */ export interface NodeTraceProducerDeps extends ProcessTrackerEnv { onError?: (error: unknown) => void; @@ -190,7 +181,6 @@ export function createNodeSystemTraceProducers(deps: NodeTraceProducerDeps = {}) new EventLoopUtilizationProducer(tracker), new V8HeapProducer(tracker), new MemoryLimitProducer(tracker), - new AvailableMemoryProducer(tracker), new GcProducer(tracker), new UptimeProducer(tracker), ]; diff --git a/packages/trackers/README.md b/packages/trackers/README.md index 4ac53c410..b1c89a2e7 100644 --- a/packages/trackers/README.md +++ b/packages/trackers/README.md @@ -24,7 +24,7 @@ Trackers are the abstraction over system and runtime APIs. The package root is r The `./browser` entry exports the `ApplicationTracker` (`applicationTrackerFor`, `resetApplicationTracker`; stages `pagehide`, `visibility`, `state`, `freeze`, `resume`; `online`/`offline` belong to the `ConnectivityTracker` and `orientationchange` to the `UiTracker`), the `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`), the `ConnectivityTracker` (`connectivityTrackerFor`, `resetConnectivityTracker`; stages `online`, `networkInfo`, `state` and `transition`, one per DOM online/offline event with its kind from the event type), the `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; stages `heap`, `mainThreadLag` (timer drift), `idle` (`requestIdleCallback`), `userIdle` (Idle Detection) and `uptime`, each armed only while it has listeners; the SDK never prompts, so `userIdle` runs only when the `idle-detection` permission is already granted; the SDK's `user_idle_state` trace additionally needs the browser/WebView launch option `captureUserIdle: true`, because a page's own grant is not consent to record and upload idle/locked state), the UI/display `UiTracker` (`uiTrackerFor`, `resetUiTracker`: orientation, screenSize, viewport, visualViewport (pinch zoom and pan), colorScheme, reducedMotion, displayMode, frameRate), the `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; an approximate origin quota estimate, not device free space: browsers may pad `usage`, and `quota` can roughly reveal the device's disk size, so treat it as potentially identifying), the `EnvironmentTracker` (`environmentTrackerFor`, `resetEnvironmentTracker`; language, time zone, and, only when a consumer sets `observeHints` / `queryPermissions`, environment hints and Permissions API states queried without ever prompting; the private-browsing heuristic runs when `detectPrivateMode` is set (the browser launch sets it by default; opt out with `captureEnvironmentHints: false`) and is never reported as a certainty) and `hostRead`; the `./electron` entry exports the Electron main-process domain trackers, with every Electron object injected structurally and never imported: the `ElectronProcessTracker` (`electronProcessTrackerFor`, `resetElectronProcessTracker`; stages `appMetrics`, `childProcessGone` and a once-only GPU read), the `ElectronPowerTracker` (`electronPowerTrackerFor`, keyed on `powerMonitor`; stages `suspendResume`, `lockScreen`, `powerSource` and a live `current('powerSource')`), the `ElectronDisplayTracker` (`electronDisplayTrackerFor`, keyed on `screen`; stages `displayAdded`, `displayRemoved`, `displayMetricsChanged`, `displays` and a live `current('displays')`) and the `ElectronApplicationTracker` (`electronApplicationTrackerFor`, keyed on `app`; stages `windowFocus`, `windowVisibility` and `rendererResponsiveness`, which listens on `webContents` only), plus `mapGpuInfo` and `mapDisplay`. Each stage attaches its Electron listeners only while it has a subscriber and removes them when the last leaves. Its API is internal and may change between releases. -The `./node` entry is shared by Node, Bun and Deno and exports the process `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; a per-process singleton, keyed on the `process` object by default). Its ten stages (`memory`, `systemMemory`, `cpu`, `eventLoop`, `utilization`, `gc`, `v8Heap`, `memoryLimit`, `availableMemory`, `uptime`) are each armed only while they have listeners, behind one shared sampling timer. A stage the runtime cannot honestly measure emits nothing rather than zero (event-loop utilization on Bun/Deno is dropped by its own tell, idle and active both zero; the event-loop delay histogram on Deno, the GC observer on Bun/Deno, the V8 heap on Bun and available memory on Bun/Deno are gated by the `measures*` flags the platform packages pass in). The CPU stage has no start value: it reports from the first tick. Seams merge and are never dropped: a later launch that omits `scheduler` or `onError` keeps the previous launch's, and building a producer set already rebinds the shared tracker, so tests that inject fakes need a private `key` or `resetProcessTracker()`. It also exports the guarded runtime sources it is built from (`createGuardedEventLoopSource`, `createGuardedElu`, `createGcSource`, `createV8HeapReader`, `createMemoryLimitReader`, `createAvailableMemoryReader`). +The `./node` entry is shared by Node, Bun and Deno and exports the process `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; a per-process singleton, keyed on the `process` object by default). Its nine stages (`memory`, `systemMemory`, `cpu`, `eventLoop`, `utilization`, `gc`, `v8Heap`, `memoryLimit`, `uptime`) are each armed only while they have listeners, behind one shared sampling timer. A stage the runtime cannot honestly measure emits nothing rather than zero (event-loop utilization on Bun/Deno is dropped by its own tell, idle and active both zero; the event-loop delay histogram on Deno, the GC observer on Bun/Deno, and the V8 heap on Bun are gated by the `measures*` flags; `systemMemory.free` is memory available to new work: `os.freemem()` on Node, `/proc/meminfo` MemAvailable first on Linux where `measuresAvailableMemory` is false (Bun/Deno), omitted when no source is plausible the platform packages pass in). The CPU stage has no start value: it reports from the first tick. Seams merge and are never dropped: a later launch that omits `scheduler` or `onError` keeps the previous launch's, and building a producer set already rebinds the shared tracker, so tests that inject fakes need a private `key` or `resetProcessTracker()`. It also exports the guarded runtime sources it is built from (`createGuardedEventLoopSource`, `createGuardedElu`, `createGcSource`, `createV8HeapReader`, `createMemoryLimitReader`, `createSystemFreeReader`, `createProcMeminfoReader`, `parseMemAvailable`). The `./node` entry also exports the disk `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; one singleton per resolved data directory, so launches over the same directory share a tracker and launches over different directories never affect each other; a launch without a data directory gets the shared inert `process`-keyed tracker, and an explicit `key` overrides, for tests) behind the opt-in `disk_mem_free` / `disk_mem_total` traces. Its one stage, `disk` (`{freeBytes, totalBytes}`), reads the volume of the launch's data directory with `fs.promises.statfs` (not `/` or the working directory) at once when a listener arrives and then on its own unref'd 5 s timer, and does nothing while no one listens, when there is no data directory, or when the runtime has no `statfs`. An unreadable or unsane reading emits nothing (a full disk is a true 0 free), and failures are reported once per failure streak. Within one directory's tracker, `onError`, `scheduler` and `statfs` are latest-launch-wins, an omitted seam keeps the earlier one, and a changed seam is applied (and re-read) immediately. Only the merged seams survive the last unsubscribe; the last reading does not. diff --git a/packages/trackers/src/node/index.test.ts b/packages/trackers/src/node/index.test.ts index c303ed27c..08db9dd72 100644 --- a/packages/trackers/src/node/index.test.ts +++ b/packages/trackers/src/node/index.test.ts @@ -7,13 +7,15 @@ describe('@bugsee/trackers/node public surface', () => { expect(Object.keys(nodeEntry).sort()).toEqual([ 'ProcessTracker', 'StorageTracker', - 'createAvailableMemoryReader', 'createGcSource', 'createGuardedElu', 'createGuardedEventLoopSource', 'createMemoryLimitReader', + 'createProcMeminfoReader', + 'createSystemFreeReader', 'createV8HeapReader', 'eluUnavailable', + 'parseMemAvailable', 'processTrackerFor', 'realPerfHooks', 'resetProcessTracker', diff --git a/packages/trackers/src/node/index.ts b/packages/trackers/src/node/index.ts index 9f4f8d34f..6f1ca18c1 100644 --- a/packages/trackers/src/node/index.ts +++ b/packages/trackers/src/node/index.ts @@ -29,9 +29,11 @@ export { resetProcessTracker, } from './process-tracker'; export { - createAvailableMemoryReader, createMemoryLimitReader, + createProcMeminfoReader, + createSystemFreeReader, createV8HeapReader, + parseMemAvailable, type V8HeapStats, } from './runtime-readers'; export { diff --git a/packages/trackers/src/node/process-tracker.test.ts b/packages/trackers/src/node/process-tracker.test.ts index c47f53c21..22f56a6c0 100644 --- a/packages/trackers/src/node/process-tracker.test.ts +++ b/packages/trackers/src/node/process-tracker.test.ts @@ -65,7 +65,7 @@ function mk(over: ProcessEnv = {}, onError?: (e: unknown) => void) { measuresEventLoopDelay: false, measuresGc: false, measuresV8Heap: false, - measuresAvailableMemory: false, + meminfo: () => undefined, eventLoopUtilization: () => undefined, memoryLimit: () => undefined, scheduler: fs.scheduler, @@ -181,7 +181,6 @@ describe('ProcessTracker', () => { eventLoopUtilization: () => 0.5, v8Heap: () => ({ limit: 10, used: 4, available: 6, malloced: 1, peakMalloced: 2 }), memoryLimit: () => 500, - availableMemory: () => 250, }); const { got } = collect(tracker); advance({ user: 100_000, system: 50_000 }, 1000); @@ -195,7 +194,6 @@ describe('ProcessTracker', () => { ['utilization', { utilization: 0.5 }], ['v8Heap', { limit: 10, used: 4, available: 6, malloced: 1, peakMalloced: 2 }], ['memoryLimit', { bytes: 500 }], - ['availableMemory', { bytes: 250 }], ['uptime', { seconds: 12 }], ['gc', { count: 3, pauseMs: 12.5, maxPauseMs: 8 }], ]); @@ -232,7 +230,6 @@ describe('ProcessTracker', () => { eventLoop: source('loop', [], () => undefined), gc: source('gc', [], () => undefined), v8Heap: () => undefined, - availableMemory: () => undefined, }); const { got } = collect(tracker); fs.tick(); @@ -373,7 +370,6 @@ describe('ProcessTracker', () => { const { tracker } = mk({ v8Heap: () => undefined }); expect(tracker.current('v8Heap')).toBeUndefined(); expect(tracker.current('memoryLimit')).toBeUndefined(); - expect(tracker.current('availableMemory')).toBeUndefined(); // gated off, nothing wired }); it('a throwing live read is reported and answers undefined', () => { @@ -402,8 +398,9 @@ describe('ProcessTracker', () => { // a real cap only: undefined on an unconstrained host, a positive number inside a cgroup const cap = tracker.current('memoryLimit'); if (cap !== undefined) expect(cap.bytes).toBeGreaterThan(0); - const avail = tracker.current('availableMemory'); - if (avail !== undefined) expect(avail.bytes).toBeGreaterThanOrEqual(0); + const sys = tracker.current('systemMemory'); + expect(sys?.free).toBeGreaterThanOrEqual(0); + expect(sys?.free).toBeLessThanOrEqual(sys?.total ?? 0); }); it('real cpu defaults: the first tick reports finite deltas and a percentage', () => { @@ -513,15 +510,37 @@ describe('ProcessTracker', () => { expect(injected.tracker.current('v8Heap')?.limit).toBe(1); }); - it('measuresAvailableMemory:false wires no reader; an injected reader wins', () => { - expect( - mk({ measuresAvailableMemory: false }).tracker.current('availableMemory'), - ).toBeUndefined(); - expect( - mk({ measuresAvailableMemory: false, availableMemory: () => 5 }).tracker.current( - 'availableMemory', - ), - ).toEqual({ bytes: 5 }); + describe('systemMemory.free: memory available to new work', () => { + const free = (over: Partial) => + mk({ systemMemory: undefined, ...over }).tracker.current('systemMemory'); + const meminfo = () => 'MemAvailable: 2 kB\n'; + + it('Node default: os.freemem() (via the injected seam), never /proc/meminfo', () => { + expect(free({ freeMemory: () => 7, meminfo })?.free).toBe(7); + }); + + it('measuresAvailableMemory:false (Bun/Deno): MemAvailable first, then os.freemem()', () => { + expect(free({ measuresAvailableMemory: false, freeMemory: () => 7, meminfo })?.free).toBe( + 2048, + ); + expect( + free({ measuresAvailableMemory: false, freeMemory: () => 7, meminfo: () => undefined }) + ?.free, + ).toBe(7); + }); + + it('omits free (keeps total) when no source answers a plausible value', () => { + const got = free({ freeMemory: () => Number.NaN }); + expect(got?.total).toBeGreaterThan(0); + expect(got).not.toHaveProperty('free'); + }); + + it('an injected systemMemory replaces every free source', () => { + expect(mk({ freeMemory: () => 5 }).tracker.current('systemMemory')).toEqual({ + total: 100, + free: 40, + }); + }); }); it('guarded ELU: a fresh baseline per arming, and Bun/Deno-style flat zeros are omitted, never reported as 0%', () => { diff --git a/packages/trackers/src/node/process-tracker.ts b/packages/trackers/src/node/process-tracker.ts index 4326e0a94..a5e04bd8d 100644 --- a/packages/trackers/src/node/process-tracker.ts +++ b/packages/trackers/src/node/process-tracker.ts @@ -1,3 +1,4 @@ +import { readFileSync } from 'node:fs'; import { cpus, freemem, totalmem } from 'node:os'; import { performance } from 'node:perf_hooks'; import nodeProcess from 'node:process'; @@ -13,24 +14,24 @@ import { realPerfHooks, } from './guarded-event-loop'; import { - createAvailableMemoryReader, createMemoryLimitReader, + createProcMeminfoReader, + createSystemFreeReader, createV8HeapReader, type V8HeapStats, } from './runtime-readers'; // Node/Bun/Deno PROCESS tracker (domain tracker, design Β§15.2/Β§15.3; Android reference: BugseeTrackerProcess). It -// owns everything the runtime can say about its own process, as TEN independent stages: +// owns everything the runtime can say about its own process, as NINE independent stages: // // memory process.memoryUsage() -> { rss, heapTotal, heapUsed, external, arrayBuffers } -// systemMemory os.totalmem()/freemem() -> { total, free } +// systemMemory os.totalmem() + memory AVAILABLE to new work -> { total, free? } (see createSystemFreeReader) // cpu process.cpuUsage() deltas over the wall window -> { userDelta, systemDelta, processPct } // eventLoop monitorEventLoopDelay histogram (guarded) -> { meanMs, maxMs, p99Ms } // utilization performance.eventLoopUtilization() (guarded) -> { utilization } // gc PerformanceObserver('gc') interval -> { count, pauseMs, maxPauseMs } // v8Heap v8.getHeapStatistics() -> { limit, used, available, malloced, peakMalloced } // memoryLimit process.constrainedMemory() (a real cap only) -> { bytes } -// availableMemory process.availableMemory() -> { bytes } // uptime process.uptime(), whole seconds -> { seconds } // // PER-STAGE ACTIVATION. Nothing runs at construction. ONE shared sampling timer exists only while some stage has a @@ -72,7 +73,8 @@ export interface ProcessMemory { } export interface ProcessEvents { memory: ProcessMemory; - systemMemory: { total: number; free: number }; + /** `free` is memory available to new work (Android parity); absent when no source answers. */ + systemMemory: { total: number; free?: number }; /** Deltas since the previous tick (Β΅s), and the process's share of all cores (%) over that window. */ cpu: { userDelta: number; systemDelta: number; processPct: number }; eventLoop: { meanMs: number; maxMs: number; p99Ms: number }; @@ -82,7 +84,6 @@ export interface ProcessEvents { gc: GcInterval; v8Heap: V8HeapStats; memoryLimit: { bytes: number }; - availableMemory: { bytes: number }; /** Whole seconds since process start. */ uptime: { seconds: number }; } @@ -96,7 +97,6 @@ const STAGES: readonly Stage[] = [ 'utilization', 'v8Heap', 'memoryLimit', - 'availableMemory', 'uptime', 'gc', ]; @@ -112,7 +112,8 @@ export interface ProcessTimers { export interface ProcessEnv { memoryUsage?: () => ProcessMemory; cpuUsage?: () => { user: number; system: number }; - systemMemory?: () => { total: number; free: number }; + /** Overrides the whole system-memory read (and every free-memory source below). */ + systemMemory?: () => { total: number; free?: number }; cpuCount?: () => number; monotonicNowMs?: () => number; /** Seconds since process start (fractions floored). Default `process.uptime()`. */ @@ -126,7 +127,10 @@ export interface ProcessEnv { /** Each reader answers undefined when the runtime cannot give a true value. Override their defaults and gates. */ v8Heap?: () => V8HeapStats | undefined; memoryLimit?: () => number | undefined; - availableMemory?: () => number | undefined; + /** Raw `/proc/meminfo` text (Linux), consulted first only when `measuresAvailableMemory` is false. Default reads the file on Linux only. */ + meminfo?: () => string | undefined; + /** `os.freemem()` bytes, the primary source of system free memory (see `createSystemFreeReader`). */ + freeMemory?: () => number; /** perf_hooks primitives for the event-loop metrics (partial on Bun/Deno). Default node:perf_hooks. */ perfHooks?: PerfHooks; /** Test seam for the GC observer constructor. Default `node:perf_hooks`. */ @@ -141,7 +145,11 @@ export interface ProcessEnv { * and ~1000x Node's cost per call), so `@bugsee/bun` passes `false`. */ measuresV8Heap?: boolean; - /** Is `process.availableMemory()` comparable to the Node figure? Default `true`; not on Bun/Deno. */ + /** + * Is `os.freemem()` known to be memory AVAILABLE to new work (libuv MemAvailable / ullAvailPhys)? Default `true` + * (Node). Bun and Deno pass `false`: they read `/proc/meminfo` MemAvailable first on Linux, then `os.freemem()`. + * `process.availableMemory()` is never used (not comparable on Bun/Deno; lower than truth in a cgroup on Node). + */ measuresAvailableMemory?: boolean; /** Does `PerformanceObserver({entryTypes:['gc']})` see collections? Default `true`; blind on Bun/Deno. */ measuresGc?: boolean; @@ -174,7 +182,8 @@ const SEAM_KEYS = [ 'eventLoopUtilization', 'v8Heap', 'memoryLimit', - 'availableMemory', + 'meminfo', + 'freeMemory', 'perfHooks', 'performanceObserver', 'measuresEventLoopDelay', @@ -197,7 +206,7 @@ interface Resolved { gc: GcSource | undefined; v8Heap: (() => V8HeapStats | undefined) | undefined; memoryLimit: () => number | undefined; - availableMemory: (() => number | undefined) | undefined; + systemFree: () => number | undefined; } const NOOP_RUN: StageRun = { read: () => undefined, stop: () => {} }; @@ -401,11 +410,12 @@ export class ProcessTracker extends InterceptorBase { env.v8Heap ?? (env.measuresV8Heap !== false ? createV8HeapReader(getHeapStatistics) : undefined), memoryLimit: env.memoryLimit ?? createMemoryLimitReader(nodeProcess, totalmem), - availableMemory: - env.availableMemory ?? - (env.measuresAvailableMemory !== false - ? createAvailableMemoryReader(nodeProcess) - : undefined), + systemFree: createSystemFreeReader({ + preferMeminfo: env.measuresAvailableMemory === false, + meminfo: env.meminfo ?? createProcMeminfoReader(nodeProcess.platform, readProcFile), + freemem: env.freeMemory ?? freemem, + total: totalmem, + }), }; this.#resolved = resolved; return resolved; @@ -421,7 +431,13 @@ export class ProcessTracker extends InterceptorBase { return { read, stop: () => {} }; } case 'systemMemory': { - const read = env.systemMemory ?? (() => ({ total: totalmem(), free: freemem() })); + const read = + env.systemMemory ?? + (() => { + const total = totalmem(); + const free = res.systemFree(); + return free === undefined ? { total } : { total, free }; + }); return { read, stop: () => {} }; } case 'uptime': { @@ -432,8 +448,6 @@ export class ProcessTracker extends InterceptorBase { return optionalRun(res.v8Heap); case 'memoryLimit': return optionalRun(res.memoryLimit, (bytes) => ({ bytes })); - case 'availableMemory': - return optionalRun(res.availableMemory, (bytes) => ({ bytes })); case 'cpu': return this.#cpuRun(); case 'eventLoop': { @@ -509,6 +523,9 @@ function optionalRun( }; } +/* v8 ignore next -- only invoked on Linux (createProcMeminfoReader gates on platform); the gating and parsing are unit-tested with injected readers */ +const readProcFile = (file: string): string => readFileSync(file, 'utf8'); + const registry = createTrackerRegistry(); /** A {@link ProcessEnv} plus the object the singleton is keyed on (default: the `process` object). */ diff --git a/packages/trackers/src/node/runtime-readers.test.ts b/packages/trackers/src/node/runtime-readers.test.ts index 5bfbda40e..958af31b8 100644 --- a/packages/trackers/src/node/runtime-readers.test.ts +++ b/packages/trackers/src/node/runtime-readers.test.ts @@ -1,8 +1,10 @@ import { describe, expect, it } from 'vitest'; import { - createAvailableMemoryReader, createMemoryLimitReader, + createProcMeminfoReader, + createSystemFreeReader, createV8HeapReader, + parseMemAvailable, } from './runtime-readers'; const GiB = 1024 ** 3; @@ -90,16 +92,97 @@ describe('createMemoryLimitReader', () => { }); }); -describe('createAvailableMemoryReader', () => { - it('reports process.availableMemory()', () => { - expect(createAvailableMemoryReader({ availableMemory: () => 123 })()).toBe(123); - expect(createAvailableMemoryReader({ availableMemory: () => 0 })()).toBe(0); +describe('parseMemAvailable', () => { + const text = + 'MemTotal: 16384000 kB\nMemFree: 100000 kB\nMemAvailable: 8192000 kB\nBuffers: 1 kB\n'; + it('returns MemAvailable in BYTES (kB is KiB), not MemFree', () => { + expect(parseMemAvailable(text)).toBe(8192000 * 1024); }); + it('is undefined when the field is absent, malformed or has no kB unit', () => { + expect(parseMemAvailable('MemFree: 5 kB\n')).toBeUndefined(); + expect(parseMemAvailable('MemAvailable: lots kB\n')).toBeUndefined(); + expect(parseMemAvailable('MemAvailable: 5 MB\n')).toBeUndefined(); + expect(parseMemAvailable('')).toBeUndefined(); + }); + it('does not match a field that merely ends in MemAvailable', () => { + expect(parseMemAvailable('XMemAvailable: 5 kB\n')).toBeUndefined(); + }); + it('is undefined for a value too large to be finite', () => { + expect(parseMemAvailable(`MemAvailable: ${'9'.repeat(400)} kB\n`)).toBeUndefined(); + }); +}); - it('is undefined (feature-detected) where it does not exist, and for non-finite or negative answers', () => { - expect(createAvailableMemoryReader({})()).toBeUndefined(); - for (const v of [Number.NaN, Number.POSITIVE_INFINITY, -1, '1', undefined]) { - expect(createAvailableMemoryReader({ availableMemory: () => v as number })()).toBeUndefined(); +describe('createProcMeminfoReader', () => { + it('reads /proc/meminfo on linux only', () => { + const files: string[] = []; + const read = (f: string) => (files.push(f), 'TEXT'); + expect(createProcMeminfoReader('linux', read)()).toBe('TEXT'); + expect(files).toEqual(['/proc/meminfo']); + for (const p of ['darwin', 'win32']) { + expect(createProcMeminfoReader(p, read)()).toBeUndefined(); } + expect(files).toHaveLength(1); // no read attempted off linux + }); + it('is undefined when the read throws', () => { + expect( + createProcMeminfoReader('linux', () => { + throw new Error('EACCES'); + })(), + ).toBeUndefined(); + }); +}); + +describe('createSystemFreeReader', () => { + const meminfo = 'MemAvailable: 10 kB\n'; // 10240 bytes + const make = (over: Partial[0]> = {}) => + createSystemFreeReader({ + preferMeminfo: false, + meminfo: () => meminfo, + freemem: () => 111, + total: () => 1_000_000, + ...over, + }); + const boom = () => { + throw new Error('boom'); + }; + + it('Node: os.freemem() alone, /proc/meminfo is never read', () => { + let reads = 0; + expect(make({ meminfo: () => (reads++, meminfo) })()).toBe(111); + expect(reads).toBe(0); + }); + + it('preferMeminfo (Bun/Deno): MemAvailable first, then os.freemem()', () => { + expect(make({ preferMeminfo: true })()).toBe(10240); + expect(make({ preferMeminfo: true, meminfo: () => undefined })()).toBe(111); + expect(make({ preferMeminfo: true, meminfo: () => 'nothing here' })()).toBe(111); + expect(make({ preferMeminfo: true, meminfo: boom })()).toBe(111); + }); + + it('skips a source that answers an implausible value (NaN, Infinity, negative, > total)', () => { + for (const bad of [Number.NaN, Number.POSITIVE_INFINITY, -1, 1_000_001]) { + expect(make({ freemem: () => bad })()).toBeUndefined(); + expect( + make({ preferMeminfo: true, freemem: () => bad, meminfo: () => undefined })(), + ).toBeUndefined(); + } + expect(make({ preferMeminfo: true, meminfo: () => 'MemAvailable: 999999999 kB\n' })()).toBe( + 111, + ); + expect(make({ freemem: boom })()).toBeUndefined(); + }); + + it('accepts zero and a value equal to total, rejects total + 1 (boundaries)', () => { + expect(make({ freemem: () => 0 })()).toBe(0); + expect(make({ freemem: () => 1_000_000 })()).toBe(1_000_000); + expect(make({ freemem: () => 1_000_001 })()).toBeUndefined(); + }); + + it('re-reads total on every call (it may change)', () => { + let total = 1000; + const read = make({ total: () => total }); + expect(read()).toBe(111); + total = 10; + expect(read()).toBeUndefined(); }); }); diff --git a/packages/trackers/src/node/runtime-readers.ts b/packages/trackers/src/node/runtime-readers.ts index 87290bef4..302cf5fff 100644 --- a/packages/trackers/src/node/runtime-readers.ts +++ b/packages/trackers/src/node/runtime-readers.ts @@ -1,4 +1,4 @@ -// Readers for the node runtime-depth traces (V8 heap, cgroup memory cap, available memory). Each answers +// Readers for the node runtime-depth traces (V8 heap, cgroup memory cap, system free memory). Each answers // `undefined` when this runtime cannot give a TRUE reading, so its trace is omitted rather than invented. // The process/os/v8 sources are injected: the defaults are wired in process-tracker.ts. @@ -64,13 +64,81 @@ export function createMemoryLimitReader( }; } -/** `process.availableMemory()` (Node β‰₯20.13, feature-detected). */ -export function createAvailableMemoryReader(proc: { - availableMemory?: () => number; -}): () => number | undefined { +/** + * `MemAvailable` of a `/proc/meminfo` text, in BYTES (the file reports kB, i.e. KiB). This is the kernel's own + * estimate of memory available to start new work without swapping (free + reclaimable cache), which is the + * quantity Android's `ram_system_free` carries. Undefined when the field is absent or not a number. + */ +export function parseMemAvailable(text: string): number | undefined { + const match = /^MemAvailable:\s+(\d+)\s+kB\s*$/m.exec(text); + if (match === null) return undefined; + const kib = Number(match[1]); + return Number.isFinite(kib) ? kib * 1024 : undefined; +} + +/** The raw `/proc/meminfo` text, on Linux only (every other platform has no such file: undefined, no read attempted). */ +export function createProcMeminfoReader( + platform: string, + readFile: (file: string) => string, +): () => string | undefined { + return () => { + if (platform !== 'linux') return undefined; + try { + return readFile('/proc/meminfo'); + } catch { + return undefined; + } + }; +} + +export interface SystemFreeSources { + /** + * Prefer `/proc/meminfo` MemAvailable over `os.freemem()`? Only for runtimes whose `os.freemem()` is not known to + * be MemAvailable-equivalent (Bun < 1.3.13 on Linux). + */ + preferMeminfo: boolean; + /** Raw `/proc/meminfo` text (Linux), or undefined. */ + meminfo: () => string | undefined; + /** `os.freemem()`, the primary source on Node: see {@link createSystemFreeReader}. */ + freemem: () => number; + total: () => number; +} + +/** + * `ram_system_free`: memory available to new work, as Android reports it (not merely "free" pages). + * + * Node: `os.freemem()`. It already is that quantity where the OS can say it: libuv reads `MemAvailable` on Linux + * since 1.43 (Node >= 16.14) and uses `ullAvailPhys` (standby cache included) on Windows. `process.availableMemory()` + * is deliberately NOT used: it equals `os.freemem()` without a cgroup limit (measured identical on macOS), and + * inside a cgroup it counts page cache as used, so it reads LOWER than what is truly available. + * Known limit: on macOS `os.freemem()` counts only free pages, so it undercounts reclaimable memory. + * + * Bun/Deno (`preferMeminfo`): `MemAvailable` from `/proc/meminfo` first (Linux), then `os.freemem()`. Their + * `process.availableMemory()` is not comparable (Deno: 0 on Windows, includes inactive pages on macOS), so it is + * never consulted. + * + * A source that throws or answers an implausible value (non-finite, negative, > total) is skipped; when none + * answers, undefined, so the trace is omitted rather than invented. + */ +export function createSystemFreeReader(src: SystemFreeSources): () => number | undefined { + const meminfo = (): number | undefined => { + const text = src.meminfo(); + return text === undefined ? undefined : parseMemAvailable(text); + }; + const sources: (() => number | undefined)[] = src.preferMeminfo + ? [meminfo, src.freemem] + : [src.freemem]; return () => { - if (typeof proc.availableMemory !== 'function') return undefined; - const value: unknown = proc.availableMemory(); - return isCount(value) && value >= 0 ? value : undefined; + const total = src.total(); + for (const source of sources) { + let value: unknown; + try { + value = source(); + } catch { + continue; + } + if (isCount(value) && value >= 0 && value <= total) return value; + } + return undefined; }; } From 9a0cd850c4d4eef790ab99b5b6a2bc8569134098 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 20:50:10 +0500 Subject: [PATCH 2/3] fix(node,trackers): ram_system_free native sources (Electron, Deno macOS), omit on macOS Node/Bun, Bun-only /proc read (C6 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit πŸ€– Generated with [Claude Code](https://claude.com/claude-code) --- .changeset/ram-system-free-semantics.md | 4 +- docs/PROGRESS.md | 4 +- packages/bun/src/launch.test.ts | 4 +- packages/bun/src/launch.ts | 5 +- packages/deno/src/launch.test.ts | 4 +- packages/deno/src/launch.ts | 6 +- packages/node/src/trace-producers.test.ts | 36 +++-- packages/node/src/trace-producers.ts | 4 +- packages/trackers/README.md | 2 +- packages/trackers/src/node/index.test.ts | 3 + packages/trackers/src/node/index.ts | 3 + .../trackers/src/node/process-tracker.test.ts | 86 +++++++++-- packages/trackers/src/node/process-tracker.ts | 42 ++++-- .../trackers/src/node/runtime-readers.test.ts | 101 ++++++++++--- packages/trackers/src/node/runtime-readers.ts | 140 ++++++++++++++---- 15 files changed, 349 insertions(+), 95 deletions(-) diff --git a/.changeset/ram-system-free-semantics.md b/.changeset/ram-system-free-semantics.md index 00013a107..3004a3ccc 100644 --- a/.changeset/ram-system-free-semantics.md +++ b/.changeset/ram-system-free-semantics.md @@ -6,6 +6,6 @@ '@bugsee/trackers': minor --- -`ram_system_free` now means memory available to new work, as on Android, instead of raw free pages. On Node it is `os.freemem()` (libuv reads `MemAvailable` on Linux and `ullAvailPhys` on Windows); on Bun and Deno it is `MemAvailable` from `/proc/meminfo` on Linux, then `os.freemem()`. On macOS `os.freemem()` still counts only free pages and undercounts reclaimable memory. The value is omitted when no source gives a finite, non-negative number not above total RAM. +`ram_system_free` now means memory available to new work, in bytes as on Android (`availMem`), instead of raw free pages. Sources: Electron `process.getSystemMemoryInfo()` (macOS free + fileBacked + purgeable, Linux `available`, Windows `free`), Deno `systemMemoryInfo().available` on macOS, `/proc/meminfo` `MemAvailable` on Bun, then `os.freemem()` (libuv `MemAvailable` on Linux, `ullAvailPhys` on Windows). Node and Bun on macOS omit the trace, because `os.freemem()` there is free pages only and no native available figure exists. The value is omitted when no source gives a finite, non-negative number not above total RAM. Inside a container it is the host's figure; the cap is `process_memory_limit`. -The `ram_system_available` trace is removed (it was Node-only and never released in a stable version): `process.availableMemory()` equals `os.freemem()` without a cgroup limit and reads lower inside one, and it is not comparable on Bun and Deno. `@bugsee/trackers/node` drops the `availableMemory` stage and `createAvailableMemoryReader`, and gains `createSystemFreeReader`, `createProcMeminfoReader` and `parseMemAvailable`. `measuresAvailableMemory` now means "`os.freemem()` is memory available to new work" (default `true`; Bun and Deno pass `false`). +The `ram_system_available` trace is removed (it was Node-only and never released): `process.availableMemory()` equals `os.freemem()` without a cgroup limit and reads lower inside one, and it is not comparable on Bun and Deno. `@bugsee/trackers/node` drops the `availableMemory` stage and `createAvailableMemoryReader`, and gains `createProcMeminfoReader` and `parseMemAvailable`. The `measuresAvailableMemory` option is replaced by `readsProcMeminfo` (default `false`; only Bun sets it), and `createSystemFreeReader`, `createElectronMemoryReader`, `createDenoMemoryReader` and `firstAnswer` are exported. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 50adb6777..105b287b8 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -64,7 +64,7 @@ Read this first; then `docs/design/sdk-design.md` (Draft v3) for the full archit - `buildNodeEnvironment(input, probe)` β€” Β§8.6 envelope via injectable `SystemProbe`. Applies `optionsToWire` to `sdk.options` (dots β†’ colons; server treats dots as nested-document paths). - `createUncaughtExceptionProvider` / `createUnhandledRejectionProvider` β€” process-event detection, V8 stack parsed + scrubbed. - `createNodeHttpInterceptor` β€” wraps `node:http(s)` `request` + `get` (mechanism `'http'`), captures axios/got/node-fetch that bypass global fetch. **Transparent error handling**: re-raises the original error when it is the sole `'error'` listener so an otherwise-uncaught request error still crashes the app. -- `createNodeSystemTraceProducers` (the only built-in node trace source; the legacy `createNodeSystemMetricsSampler` / `createGuardedSystemMetricsSampler` were deleted in ST0β€²-D, `systemMetricsSampler` remains as a caller-supplied override) β€” process memory (rss/heapTotal/heapUsed/external/**arrayBuffers**), **system memory (`ram_system_total`/`ram_system_free` β€” Android parity; C6: `free` is memory AVAILABLE to new work: `os.freemem()` on Node (libuv MemAvailable on Linux, ullAvailPhys on Windows), `/proc/meminfo` MemAvailable first on Bun/Deno Linux via `measuresAvailableMemory:false`; omitted if no source is plausible; macOS `freemem` undercounts reclaimable memory)**, CPU user/system per-sample deltas + **normalized `cpu_usage_process` %** (over wall-time/cores), event-loop lag **mean/max/p99** + **utilization** (perf_hooks `monitorEventLoopDelay` + `eventLoopUtilization`). All readers injectable. **ST1 added** (measured on real node/bun/deno + a Linux cgroup container, 2026-10-17): `v8_heap_{size_limit,available,malloced,peak_malloced}` + ceiling-based `ram_js_heap_{total,used,free}` (Node/Deno; `measuresV8Heap:false` on Bun), `process_memory_limit` (only a real cap: `0`, the 2^64 sentinel and `>= totalmem` β€” which Bun answers when unconstrained β€” are omitted), `process_uptime_s`, `ram_system_available` (RETIRED by C6: `process.availableMemory()` equals `os.freemem()` without a cgroup limit, reads lower inside one, and is not comparable on Bun/Deno where under `docker -m 256m` it answered ~11 GB vs Node's 253 MB). Linux probes: Bun's unconstrained `constrainedMemory()` equals `totalmem` exactly, Deno's is `0`, both report a real cap under `-m`. **ST2 added:** `gc_count` / `gc_pause_ms` / `gc_pause_max_ms` per interval from a lazy `PerformanceObserver({entryTypes:['gc']})` (`trackers/gc-observer.ts`, started/stopped by the tracker with the other sources); a quiet interval is a true zero. The observer is BLIND on Bun and Deno (measured), so both launches pass `measuresGc:false` and never construct it. **ST3 added:** opt-in `captureDiskSpace` β†’ `disk_mem_free`/`disk_mem_total` (integer binary MB via `bytesToMegabytes`) for the volume of the launch's `effectiveDataDir` (`disk-space-producer.ts`, async `fs.promises.statfs` every 5 s, polled and NOT held so a failing statfs leaves a gap, generation-guarded against stale reads, one `onError` per failure streak). Appended by `nodeLaunchCore` (also to caller-supplied/Bun/Deno producer lists); absent with no data dir, never `/` or cwd. +- `createNodeSystemTraceProducers` (the only built-in node trace source; the legacy `createNodeSystemMetricsSampler` / `createGuardedSystemMetricsSampler` were deleted in ST0β€²-D, `systemMetricsSampler` remains as a caller-supplied override) β€” process memory (rss/heapTotal/heapUsed/external/**arrayBuffers**), **system memory (`ram_system_total`/`ram_system_free` β€” Android parity; C6: `free` is memory AVAILABLE to new work, bytes like `ram_system_total` (Android `availMem`). Sources in order: a runtime-native figure (Electron `process.getSystemMemoryInfo()` in KiB: macOS free+fileBacked+purgeable, Linux `available`, Windows `free`; Deno `systemMemoryInfo().available` on macOS only), `/proc/meminfo` MemAvailable (Bun only, `readsProcMeminfo`; Deno must not: a scoped `--allow-read` makes it an interactive prompt), then `os.freemem()` (libuv MemAvailable on Linux, ullAvailPhys on Windows; NOT a source on macOS). Node and Bun on macOS therefore OMIT the trace (os.freemem there is free pages only: 0.2% of RAM on a busy 64 GB Mac while the OS reports ~half available); a rare async sysctl/vm_stat read or bun:ffi could fill it later (owner may veto the omission). Omitted whenever no source gives a finite, non-negative value <= total. Inside a container it is the HOST's figure; the cap is `process_memory_limit`. `platform.memory_free` in the environment envelope still uses `os.freemem()` (FOLLOW-UP: route it through the same source function and omit it on macOS Node/Bun))**, CPU user/system per-sample deltas + **normalized `cpu_usage_process` %** (over wall-time/cores), event-loop lag **mean/max/p99** + **utilization** (perf_hooks `monitorEventLoopDelay` + `eventLoopUtilization`). All readers injectable. **ST1 added** (measured on real node/bun/deno + a Linux cgroup container, 2026-10-17): `v8_heap_{size_limit,available,malloced,peak_malloced}` + ceiling-based `ram_js_heap_{total,used,free}` (Node/Deno; `measuresV8Heap:false` on Bun), `process_memory_limit` (only a real cap: `0`, the 2^64 sentinel and `>= totalmem` β€” which Bun answers when unconstrained β€” are omitted), `process_uptime_s`, `ram_system_available` (RETIRED by C6: `process.availableMemory()` equals `os.freemem()` without a cgroup limit, reads lower inside one, and is not comparable on Bun/Deno: under `docker -m 256m` they answered ~11 GB vs Node's 253 MB). Linux probes: Bun's unconstrained `constrainedMemory()` equals `totalmem` exactly, Deno's is `0`, both report a real cap under `-m`. **ST2 added:** `gc_count` / `gc_pause_ms` / `gc_pause_max_ms` per interval from a lazy `PerformanceObserver({entryTypes:['gc']})` (`trackers/gc-observer.ts`, started/stopped by the tracker with the other sources); a quiet interval is a true zero. The observer is BLIND on Bun and Deno (measured), so both launches pass `measuresGc:false` and never construct it. **ST3 added:** opt-in `captureDiskSpace` β†’ `disk_mem_free`/`disk_mem_total` (integer binary MB via `bytesToMegabytes`) for the volume of the launch's `effectiveDataDir` (`disk-space-producer.ts`, async `fs.promises.statfs` every 5 s, polled and NOT held so a failing statfs leaves a gap, generation-guarded against stale reads, one `onError` per failure streak). Appended by `nodeLaunchCore` (also to caller-supplied/Bun/Deno producer lists); absent with no data dir, never `/` or cwd. - `createNodeSystemEventsSource` β€” process lifecycle (`process_started` on activate, `process_exiting`, **`process_before_exit`** clean-drain, `process_warning`, and **`process_signal`** for SIGTERM/SIGINT). Signal capture is PASSIVE: it emits the event, and only when the SDK is the sole handler does it remove itself and **re-raise** (`process.kill`) to restore Node's default termination β€” so it never hangs a process or hijacks an app's own signal handler. - **`launch(appToken, options)`** β€” the composition root: builds the transport (internal-tagged), api/uploader/upload pipeline, durable wrapper (when `dataDir`/`bundleStore` present), env builder, store (in-memory / file-backed), resolves the friendly options once via `NODE_OPTION_DEFINITIONS`, registers gated capture providers (consoleβ†’log; network umbrella with `node:http` folded in; system traces/events) + detection providers, calls `client.launch()`, runs durable `recover()` on start, installs the uncaughtException β†’ `flush(timeout)` β†’ `proc.exit(1)` policy (opt-out `exitOnUncaught`, default `shutdownTimeoutMs: 3000`), and augments `client.stop()` to remove its process listener. Returns the started `BugseeClient`. @@ -413,7 +413,7 @@ solid), in slices: - **TR6 (DONE, `feat/storage-tracker`):** domain **`StorageTracker`** (`packages/trackers/src/browser/storage-tracker.ts`), singleton per window via `createTrackerRegistry` (`storageTrackerFor(env, onError?)`, `resetStorageTracker`; keyed window -> navigator -> env object, `rebind` as PowerTracker). Wraps `navigator.storage.estimate()` + `persisted()`; ONE stage `storageEstimate` `{usageBytes?, quotaBytes?, persisted?}`. This is an ORIGIN quota ESTIMATE (browsers fuzz/pad it), NOT device free space. No change event, so it polls sparsely: on activation, on `visibilitychange` -> visible, then a slow timer (default 5 min via an injectable scheduler; ticks while the page is hidden are skipped). A field that is non-finite/negative/non-number is omitted (never 0); `persisted` only when boolean; an estimate with no usable field emits nothing. A rejected/throwing `estimate()`/`persisted()` is reported via `onError` and costs only its own field (host getters through `hostRead`); launch is never failed. **Retention rule (tested):** the LAST estimate survives the last unsubscribe (`current()` answers at once; a failed poll never erases it); timer and visibility listener do not (released, re-armed on the next subscriber, which also polls afresh). A single epoch counter is bumped by every poll/stop/reset, so a stale in-flight promise (after stop/reset, or superseded by a newer poll) is inert. `rebind` keeps every defined seam (undefined never clobbers) and applies it from the NEXT activation; a tracker that is attached keeps the navigator/document/scheduler it armed (only `onError` changes at once). Visibility-triggered polls are throttled to one per 60 s (`VISIBILITY_MIN_GAP_MS`, injectable `now`); the slow timer is not. Poll failures are reported ONCE per failure streak (reset by a poll without failures, and by `reset()`), not on every tick. A PARTIAL poll (one of `estimate()`/`persisted()` failed) merges: the failed call's retained fields are kept, answered fields replace, and the estimate's age advances only when usage/quota were refreshed. `currentFresh()` returns the retained estimate only while younger than 2x the poll interval (`current()` still returns it regardless). `StorageProducer` (browser `trace-producers.ts`, built after the `sensors:false` gate like the other sensor producers, so a `systemMetricsSampler` replaces it) emits the NEW JS-specific trace `storage_estimate` `{usage, quota}` in integer MB (`bytesToMegabytes`, floored; a missing key is omitted, `persisted` is not a trace) - NOT the Android `disk_mem_*` group. It is held/de-duplicated (`emitIfChanged`) because the poll period (5 min) far exceeds the default 60 s recording window; a non-held value would almost never appear in a report. `StorageProducer.onStart` seeds only from `currentFresh()` (never a snapshot older than 2x the interval). **OWNER DECISION PENDING:** a held polled value cannot be retracted, so after failed polls the last known estimate keeps being re-recorded every `refreshMs`. Alternatives: plain `emit` (the value would rarely land in a 60 s window) or a provider retract/release mechanism (same open question as the TR4 time traces). Usage under 1 MiB floors to 0 MB (an honest floor, not a measurement of zero). Shared by the WebView launch via the browser producers. Launch-level test proves launch goes through `storageTrackerFor` (the window's singleton holds the estimate). - **TR7 (DONE, `feat/environment-tracker`):** domain **`EnvironmentTracker`** (`packages/trackers/src/browser/environment-tracker.ts`), singleton per window via `createTrackerRegistry` (`environmentTrackerFor(env, onError?)`, `resetEnvironmentTracker`; keyed window -> navigator -> env object; `rebind` merges seams, never drops a defined one; a RUNNING tracker whose window/navigator/document/scheduler/interval changed detaches with the OLD seams, swaps in place, then re-attaches; `detectPrivateMode` turned on while running probes at once, turned off drops the result and any in-flight probe). Five stages: `language` `{language?, languages?, previous}` (`navigator.language(s)` + `languagechange`), `timezone` `{timeZone?, utcOffsetMinutes?, previous}` (no browser event, so re-read on a slow injectable timer, default 60 s with hidden-page ticks skipped, and on visibility -> visible; a DST shift is an offset change), `hints` `{cookiesEnabled?, secureContext?, crossOriginIsolated?, serviceWorkerControlled?, automation?, doNotTrack?, globalPrivacyControl?}`, `permissions` `{camera?, microphone?, geolocation?, notifications?, 'idle-detection'?: 'granted'|'denied'|'prompt'}` and `privateMode` `{private: 'yes'|'no'|'unknown', method?}`. `language`/`timezone` are CHANGE-ONLY (the first reading is a silent baseline held in `current()`, because they back `*_changed` events); `hints`/`permissions` are SNAPSHOT stages (first reading + every change); `privateMode` emits when its answer first arrives and when it changes. **Never prompts:** only `navigator.permissions.query()` is called (never requestPermission/getUserMedia/...), only the state STRING is kept, a PermissionStatus `change` refreshes it; a name the browser rejects with TypeError is omitted silently (Firefox does not know `camera`), other rejections are reported once per failure streak. **Private mode** is a HEURISTIC, never a certainty: one method `storage-quota` (`estimate().quota` under 120 MiB -> `yes`, at/over 1 GiB -> `no`, between or unreadable -> `unknown`; Chromium gives incognito a small fixed quota, Safari fuzzes). Omit-never-fabricate everywhere (empty/non-string language, NaN offset, non-boolean hints, unusable permission states are omitted; unknown DNT values omitted). Every host read goes through `hostRead` (a hostile getter costs only its field and is reported), a throwing `onError` never escapes. **Retention rule (tested):** the last language/time zone/hints/permissions/private-mode readings survive the last unsubscribe (and the change-only stages compare a restart against them); DOM listeners (languagechange, visibilitychange, PermissionStatus change), the timer and async work in flight do not (epoch tokens make a stale query/probe inert). **Events (`events.system`, `createBrowserSystemEventsSource`; the WebView launch shares the same source):** `language_changed` `{language?, languages?, previousLanguage?}`, `timezone_changed` `{timezone?, utcOffsetMinutes?, previousTimezone?, previousUtcOffsetMinutes?}`, `private_mode_detected` `{method?}` (ONLY for a `yes`; `no`/`unknown` never produce an event). Event names are free-form in `SystemEvent` (no registry/schema list exists to extend). **Launch option `captureEnvironmentHints`** (canonical `com.bugsee.option.capture.environment-hints`, browser launch only, default TRUE (opt-out), fail-closed boolean: anything but a boolean is OFF and reported) -> tracker `detectPrivateMode`; the WebView launch never enables it. **OWNER DECISION (2026-10-20, binding): private/incognito detection is OPT-OUT, ON by default** (the launch option keeps its name `captureEnvironmentHints`, default TRUE, `false` opts out, an invalid value is OFF and reported); still a tri-state heuristic (`yes`/`no`/`unknown`, method `storage-quota`), never a certainty. The decision covers private mode only, not other sensitive signals. The WebView launch still passes `detectPrivateMode: false` (no launch option there; a WebView's storage quota is not a private-window signal). **Not done / scope notes:** no `displayMode` stage (the UiTracker owns display-mode; `display_mode_changed` will be derived from it later); `hints` and `permissions` are tracker-level only, they have no wire consumer (the environment envelope schema is closed and has no field for them, so language/timezone were NOT added to `environment` either: `platform.locale`/`utc_offset` are still read once at launch by `buildBrowserEnvironment`, and the new events carry the later changes); **hints and permissions are NOT read by default (PR #84 review):** tracker env flags `observeHints` / `queryPermissions` (default false; a change while running re-attaches, turning one off drops its reading and, for permissions, the status listeners and in-flight queries); the browser system-events source passes both `false` explicitly (never inherited from the window's shared tracker), so a launch issues no `permissions.query()` and reads no hints until a real consumer sets them. Launch tests prove launch goes through `environmentTrackerFor` (the window's singleton holds the readings; mutating the source to `new EnvironmentTracker` fails them) and that private mode is ON by default and off with `captureEnvironmentHints: false`; the WebView launch has the same singleton test. **Review round 2:** persistent host-read failures of language/timezone/hints/visibility are reported once per failure streak (a clean run or `reset()` ends it); emitted stage payloads are copies, so a subscriber cannot mutate retained readings; the WebView launch now passes `document` + `scheduler` to the environment source; `resetEnvironmentTracker` is NOT re-exported from `@bugsee/browser` (reach teardown via `environmentTrackerFor(env).reset()`). **Round 3:** a host read that THROWS keeps that field's retained value (language, languages, time zone id, offset, each hint), so a transient failure never yields a fake `language_changed`/`timezone_changed`; `reset()` now drops all subscribers (`removeAllListeners`, as ApplicationTracker does) so the tracker re-activates for the next subscriber; a throwing `PermissionStatus.state` getter is reported once per streak. **Round 4:** per-permission-name streaks; a throwing state read, or a name whose re-query is rejected with a non-TypeError, keeps that name's retained state (a TypeError still omits it). **Round 5:** the browser system-events source subscribes to the tracker with ONE `onAny` (the activation read can emit a change made while the SDK was stopped, so per-stage subscriptions lost the later stages: a zone change alongside a language change vanished); the WebView launch passes `detectPrivateMode: false` explicitly (never inherits ON from an earlier launch on the window); stage payloads copy `previous` as well (a kept field shares its array). **PR review:** `privateMode` is no longer re-emitted on every activation: it emits when the answer first arrives and when it changes, a retained yes/no is not re-probed on a restart or a seam-moving rebind (an `unknown` is retried), and turning detection off then on re-detects; the browser events source always passes `detectPrivateMode` explicitly (omitted = false, never inherited); an answered-but-unusable permission state clears the stale entry (a failed/throwing read still retains it); private-probe getter failures (storage/estimate/quota) are reported once per streak; it stays a heuristic (constrained storage can false-positive). **Per-session delivery:** the tracker outlives sessions and never re-probes a retained yes/no, so the browser events source reads `current().privateMode` right after subscribing and re-emits `private_mode_detected` once for a retained `yes` (never for `no`/`unknown`, and never when this source opted out; the sink-side `detectPrivateMode` guard also covers the retained read). - **TR5 (implemented on `feat/process-tracker`, PR #83; multi-agent review rounds still in progress, one owner decision open β€” see "Known limit" below):** domain **`ProcessTracker`** (`packages/trackers/src/browser/process-tracker.ts`), singleton per window via `createTrackerRegistry` (`processTrackerFor(env, onError?)`, `resetProcessTracker`; keyed window -> performance -> env object, `rebind` merge-not-drop: a seam change on a RUNNING tracker first detaches every armed stage with the seams it was armed with, then swaps and restarts). It ABSORBS and replaces the per-signal `MemoryTracker` and `MainThreadLagTracker` (files + tests deleted; `MemoryProducer`/`MainThreadLagProducer` now subscribe to it; trace names and wire shapes unchanged). Five stages, each armed ONLY while it has listeners (via the `listenerCount(name)` / `onListenersChanged()` hooks `MultiKeyEmitterBase` already has on `main` from TR2; this PR does not touch the emitter; `start()`/`stop()` do nothing here): `heap` `{used, limit}` (`performance.memory`, polled; a figure that is not a finite non-negative number omits the reading), `mainThreadLag` `{lagMs}` (TIMER DRIFT, algorithm and visible-only gating unchanged: block >= 1 s always shows, shorter that crosses no due tick reads 0, reported once, fresh baseline each visible start), `idle` `{idleMs}` (NEW, ONE `requestIdleCallback` probe per sampling tick, never a loop and at most one in flight, visible pages only, `timeRemaining()` clamped to <= 50 ms; a tick whose callback never runs yields NO sample, never 0; omitted without rIC, e.g. Safari), `userIdle` `{userState: 'active'|'idle', screenState?: 'locked'|'unlocked'}` (NEW, Idle Detection API), `uptime` `{uptimeMs}` (`performance.now()`, omitted without a clock; no trace consumes it yet). **Idle Detection permission rule (binding): the SDK NEVER prompts.** `IdleDetector.requestPermission()` is never called; the detector starts ONLY when `navigator.permissions.query({name:'idle-detection'})` ALREADY reports `granted` (an engine that does not know the name rejects = stage inert, silent). The permission is re-queried on every activation and watched through its `change` event (granted later -> starts; revoked -> aborts and drops the tracker's retained state). Threshold floored at the spec's 60 s; stop aborts via `AbortController`; every async continuation is guarded by its run. **Retention rule (tested):** the last `userIdle` state survives the last unsubscribe (`currentUserIdle()`; `currentUserIdleFresh()`, which `UserIdleProducer` seeds from, answers only once the ARMED stage's detector has PUBLISHED in this run (permission re-confirmed and its `start()` settled; no age bound, a live detector reports changes only) and is undefined while the async permission re-query or `start()` is pending, or after a refusal/revoke; with NO armed stage it serves the state only while younger than 2 detector thresholds, via a new injectable `now` seam defaulting to `Date.now`, mirroring TR6's `currentFresh()`. A revoke while no stage is armed is therefore only noticed by the next activation's re-query (the plain `currentUserIdle()` read keeps the snapshot until then), but it can never seed a held trace); heap is read live; idle/lag/uptime keep nothing (a stale baseline would be a lie); timers, lifecycle subscription, pending probe and detector are released. New JS-specific traces (`BrowserTraceEnv` gains `requestIdleCallback`/`cancelIdleCallback`/`IdleDetector`/`AbortController`, bound/taken from the injected window by `browserTraceEnvFrom`): `main_thread_idle_ms` (ms, polled/not held; built under the same lifecycle gate as lag/fps) and `user_idle_state` (a STRING like `app_state`: `active` | `idle` | `locked`, where a locked screen wins over `userState`; held, de-duplicated; no trace at all unless the permission was already granted). **`user_idle_state` is OPT-IN (review P2; the maintainer's decision, PENDING OWNER CONFIRMATION): the host page's `idle-detection` grant shows only that the page was given the permission, not consent to record and upload idle/locked state. So `createBrowserSystemTraceProducers` builds `UserIdleProducer` only for `BrowserTraceEnv.captureUserIdle === true`, fed by the new browser + WebView launch option `captureUserIdle` (default false, strict boolean: any other value stays off and is reported; local key `com.bugsee.option.browser.capture-user-idle`, exported as `CAPTURE_USER_IDLE_OPTION_KEY`). Even when on, the tracker starts a detector only if the permission ALREADY reports `granted` (the SDK still never prompts). Without the opt-in the permission is not even queried. This applies ONLY to `user_idle_state`; private-mode detection is opt-out by a separate owner decision.** The viewer has no definition for either name yet (generic value block, design Β§13.3). **Known limit (OWNER DECISION PENDING β€” no retract mechanism invented):** `user_idle_state` is a HELD trace and the tracker emits nothing when the permission is revoked, so a producer that already published a value keeps having it re-recorded every `refreshMs` until the producer stops (the revoke only drops the tracker's retained copy and so stops NEW seeds; the seed is gated as above). Resolving it needs a decision on a retract/clear signal for held traces (same family as TR6's held `storage_estimate`). Other hardening from review: a hostile `performance.now` getter is reported exactly once in total (the factory reads silently, the tracker reports; only a SUCCESSFUL clock read is memoised per env, a failed one is retried on the next activation); `ProcessTracker.reset()` now drops every listener (like `ApplicationTracker`), so a later listener change cannot re-arm a stage for a gone subscriber; `browserTraceEnvFrom` now hands back stable bound closures per (window, function), so a no-op relaunch no longer restarts armed stages; a non-finite lag baseline omits that tick's `main_thread_lag_ms` instead of sending NaN; the gated teardown always closes the run. Launch-level test proves browser launch goes through `processTrackerFor` (the window's singleton can read the heap through launch's seams); the WebView launch shares the producers. `sensors:false` (a `systemMetricsSampler`) still builds only the battery producer. -- **TR8 part 1 (implemented on `feat/node-process-tracker`; Process only, Storage/disk is part 2 below):** the node/bun/deno **`ProcessTracker`** (`packages/trackers/src/node/process-tracker.ts`, `@bugsee/trackers/node`) ABSORBS and REPLACES `@bugsee/node`'s per-signal `ProcessStatsTracker` (files + tests deleted from `packages/node/src/trackers/`); `gc-observer`, `guarded-event-loop` and `runtime-readers` moved (with their tests) to `packages/trackers/src/node/` unchanged apart from `EventLoopSource` now living beside the histogram source. Singleton per process via the registry (`processTrackerFor(env, onError?)`, key `env.key` else the `process` object; `resetProcessTracker(key?)`); `rebind` merges (defined seams replace, undefined never clobber; an UNCHANGED relaunch restarts nothing; a changed seam tears every armed stage down with the OLD seams, the timer is cleared on the scheduler that armed it, then re-arms on the new ones; latest `onError` wins). Nine (ten before C6 removed `availableMemory`) **per-stage-activated** stages (one shared unref'd timer exists only while some stage has a listener; each stage's machinery only while it is wanted): `memory`, `systemMemory`, `cpu` `{userDelta, systemDelta, processPct}`, `eventLoop` `{meanMs, maxMs, p99Ms}`, `utilization` `{utilization}`, `gc` `{count, pauseMs, maxPauseMs}`, `v8Heap`, `memoryLimit` `{bytes}`, `uptime` `{seconds}`. Trace names and wire values are unchanged. Honesty rules are unchanged and still tracker-owned: a stage that cannot answer EMITS NOTHING (ELU zeros on Bun/Deno, an unsampled histogram, a blind/refusing GC observer, untrue heap/limit/available readings), and the runtime-identity GATES (`measuresEventLoopDelay`/`measuresV8Heap`/`measuresAvailableMemory`/`measuresGc`) are now tracker env flags that the platform composition roots (`@bugsee/{deno,bun}` via `createNodeSystemTraceProducers`) pass through; an injected source/reader wins over its gate. **Retention rule (stated and tested):** only the resolved seams and the "this runtime refused" memory inside the guarded sources survive the last unsubscribe; the CPU baseline, ELU baseline, histogram, GC interval and the last windowed sample all start FRESH on the next subscription. `current(stage)` reads stateless stages LIVE (guarded, copies) and answers the last emitted sample of a windowed stage (`cpu` is seeded with a zero-length window when it arms, so a producer has a baseline). Hardening: reporter indirection that swallows a throwing `onError`, generation-guarded timer callbacks (a timer whose clear failed never emits), each stage read isolated (one throwing reader drops only itself; a failed CPU read never advances the baseline), a failing source start leaves its stage unarmed (never half-armed, retried on the next listener change/rebind), a timer that cannot be armed unwinds the stages armed for it, one failing stop never strands another, emitted payloads are copies. `@bugsee/node`'s `trace-producers.ts` is now composition only (ten producers, each subscribed to ONE stage; `NodeTraceProducerDeps` = tracker env + `onError`), and `@bugsee/node` re-exports `processTrackerFor`/`resetProcessTracker`/`ProcessTracker` (and drops the `ProcessStatsTracker`/`ProcessStats` exports). **Behaviour notes:** (1) the tracker is one per PROCESS now, so a second producer set / relaunch shares it and its seams are rebound (tests that inject fakes must pass a private `key` or call `resetProcessTracker()`); (2) per-stage activation means the GC observer and the delay histogram exist only while their producer is subscribed (before, they ran whenever any producer was); (3) the ELU baseline is taken when its stage arms (before: when the producers were built), so the first sample no longer spans an idle gap; (4) the activation CPU/baseline read and the poll are per stage, so one failing reader no longer fails the whole poll (before: an `uptime` failure dropped the whole row); (5) there is NO CPU start value any more: before, the producer published a microsecond-window noise reading at start (`processPct` 7-43%, never a true share), now the tracker keeps its internal counters but the CPU producer has an empty `baseline()` and `current('cpu')` is undefined until the first tick (as for gc/event-loop-lag/utilization); an unusable core count (`os.cpus()` empty) now omits the cpu sample instead of emitting Infinity/NaN; (6) **seams merge, never drop:** the tracker outlives launches, so a later launch that omits `scheduler`/`onError`/a reader KEEPS the previous launch's (it can replace a seam, never shed one), and merely BUILDING a producer set rebinds the shared tracker (including the Bun/Deno default sets built before `...options` in their `launch.ts`); tests must use a private `key` or `resetProcessTracker()` (added to the afterEach of the node, bun, deno and elysia launch tests). **Tooling:** `@bugsee/trackers` gained `@types/node` (devDependency) and `tsconfig.json` now carries `types: ["node"]` for `src/node`; `tsconfig.portable.json` re-typechecks the portable root + browser entries WITHOUT node types (`pnpm typecheck` runs both) so a node global cannot leak into code shipped to browsers. `@bugsee/node` gained the `@bugsee/trackers` workspace dependency. Launch tests prove the default producers go through the registry accessor (mutating the producer factory to `new ProcessTracker` fails them) and that the Bun/Deno gates reach the shared tracker end to end. +- **TR8 part 1 (implemented on `feat/node-process-tracker`; Process only, Storage/disk is part 2 below):** the node/bun/deno **`ProcessTracker`** (`packages/trackers/src/node/process-tracker.ts`, `@bugsee/trackers/node`) ABSORBS and REPLACES `@bugsee/node`'s per-signal `ProcessStatsTracker` (files + tests deleted from `packages/node/src/trackers/`); `gc-observer`, `guarded-event-loop` and `runtime-readers` moved (with their tests) to `packages/trackers/src/node/` unchanged apart from `EventLoopSource` now living beside the histogram source. Singleton per process via the registry (`processTrackerFor(env, onError?)`, key `env.key` else the `process` object; `resetProcessTracker(key?)`); `rebind` merges (defined seams replace, undefined never clobber; an UNCHANGED relaunch restarts nothing; a changed seam tears every armed stage down with the OLD seams, the timer is cleared on the scheduler that armed it, then re-arms on the new ones; latest `onError` wins). Nine (ten before C6 removed `availableMemory`) **per-stage-activated** stages (one shared unref'd timer exists only while some stage has a listener; each stage's machinery only while it is wanted): `memory`, `systemMemory`, `cpu` `{userDelta, systemDelta, processPct}`, `eventLoop` `{meanMs, maxMs, p99Ms}`, `utilization` `{utilization}`, `gc` `{count, pauseMs, maxPauseMs}`, `v8Heap`, `memoryLimit` `{bytes}`, `uptime` `{seconds}`. Trace names and wire values were unchanged by TR8 (C6 later retired `ram_system_available` and changed what `ram_system_free` means). Honesty rules are unchanged and still tracker-owned: a stage that cannot answer EMITS NOTHING (ELU zeros on Bun/Deno, an unsampled histogram, a blind/refusing GC observer, untrue heap/limit/available readings), and the runtime-identity GATES (`measuresEventLoopDelay`/`measuresV8Heap`/`measuresGc`; C6 replaced `measuresAvailableMemory` with `readsProcMeminfo`, set by Bun only) are now tracker env flags that the platform composition roots (`@bugsee/{deno,bun}` via `createNodeSystemTraceProducers`) pass through; an injected source/reader wins over its gate. **Retention rule (stated and tested):** only the resolved seams and the "this runtime refused" memory inside the guarded sources survive the last unsubscribe; the CPU baseline, ELU baseline, histogram, GC interval and the last windowed sample all start FRESH on the next subscription. `current(stage)` reads stateless stages LIVE (guarded, copies) and answers the last emitted sample of a windowed stage (`cpu` is seeded with a zero-length window when it arms, so a producer has a baseline). Hardening: reporter indirection that swallows a throwing `onError`, generation-guarded timer callbacks (a timer whose clear failed never emits), each stage read isolated (one throwing reader drops only itself; a failed CPU read never advances the baseline), a failing source start leaves its stage unarmed (never half-armed, retried on the next listener change/rebind), a timer that cannot be armed unwinds the stages armed for it, one failing stop never strands another, emitted payloads are copies. `@bugsee/node`'s `trace-producers.ts` is now composition only (nine producers after C6, each subscribed to ONE stage; `NodeTraceProducerDeps` = tracker env + `onError`), and `@bugsee/node` re-exports `processTrackerFor`/`resetProcessTracker`/`ProcessTracker` (and drops the `ProcessStatsTracker`/`ProcessStats` exports). **Behaviour notes:** (1) the tracker is one per PROCESS now, so a second producer set / relaunch shares it and its seams are rebound (tests that inject fakes must pass a private `key` or call `resetProcessTracker()`); (2) per-stage activation means the GC observer and the delay histogram exist only while their producer is subscribed (before, they ran whenever any producer was); (3) the ELU baseline is taken when its stage arms (before: when the producers were built), so the first sample no longer spans an idle gap; (4) the activation CPU/baseline read and the poll are per stage, so one failing reader no longer fails the whole poll (before: an `uptime` failure dropped the whole row); (5) there is NO CPU start value any more: before, the producer published a microsecond-window noise reading at start (`processPct` 7-43%, never a true share), now the tracker keeps its internal counters but the CPU producer has an empty `baseline()` and `current('cpu')` is undefined until the first tick (as for gc/event-loop-lag/utilization); an unusable core count (`os.cpus()` empty) now omits the cpu sample instead of emitting Infinity/NaN; (6) **seams merge, never drop:** the tracker outlives launches, so a later launch that omits `scheduler`/`onError`/a reader KEEPS the previous launch's (it can replace a seam, never shed one), and merely BUILDING a producer set rebinds the shared tracker (including the Bun/Deno default sets built before `...options` in their `launch.ts`); tests must use a private `key` or `resetProcessTracker()` (added to the afterEach of the node, bun, deno and elysia launch tests). **Tooling:** `@bugsee/trackers` gained `@types/node` (devDependency) and `tsconfig.json` now carries `types: ["node"]` for `src/node`; `tsconfig.portable.json` re-typechecks the portable root + browser entries WITHOUT node types (`pnpm typecheck` runs both) so a node global cannot leak into code shipped to browsers. `@bugsee/node` gained the `@bugsee/trackers` workspace dependency. Launch tests prove the default producers go through the registry accessor (mutating the producer factory to `new ProcessTracker` fails them) and that the Bun/Deno gates reach the shared tracker end to end. - **TR8 part 2 (implemented on `feat/node-storage-tracker`; Storage/disk):** the node/bun/deno **`StorageTracker`** (`packages/trackers/src/node/storage-tracker.ts`, `@bugsee/trackers/node`) ABSORBS the statfs polling of `@bugsee/node`'s `disk-space-producer.ts`, which is now composition only (one `StorageTracker` stage `disk` -> `disk_mem_free`/`disk_mem_total`; the old timer/streak/generation machinery and its tests were deleted; the producer tests were rewritten over the tracker). Singleton per VOLUME IDENTITY (`storageTrackerFor(env, onError?)`; key = the interned RESOLVED data dir, so launches over the same dir share one tracker and launches over different dirs get different ones; an explicit `env.key` overrides (tests); no data dir -> the shared inert `process`-keyed tracker; `resetStorageTracker(key?: object | dir)` drops one, no argument drops all). ONE stage, `disk` `{freeBytes, totalBytes}` (bytes; the producer converts to integer binary MB with `bytesToMegabytes`, free then total, `hold:false`, so a failing statfs leaves a gap). Activation is by listener: the first listener reads the data dir's volume at once and arms an unref'd 5 s timer (injectable scheduler/`intervalMs`); no listener, no data dir, or `statfs: null`/no `fs.promises.statfs` (Node < 18.15, as the old producer handled it) means no timer and no read. Reads never overlap (in-flight latch), every read and timer callback is guarded by the generation that armed it (a stop, a path change or a seam change abandons it: it can neither emit nor report), failures are reported ONCE per failure streak (a success, an unsane answer, a new run or a new path starts a new one), an unsane answer (non-positive block size/total, negative or non-finite free, overflowing product, non-numbers) is omitted without an error and never zeroed (a full disk is a true 0 free). `rebind` merges seams within one key (defined replaces, undefined never clobbers; `statfs: null` is a defined seam): `onError`/`scheduler`/`statfs`/`intervalMs` are latest-launch-wins per key, while the data dir is part of the key, so a running launch can never be redirected to (or have its failures reported to) another launch's dir/`onError`; a CHANGED seam while a listener is attached tears the poll down on the scheduler that armed it and starts again at once (a changed path is re-read immediately and the old path's reading and failure streak do not leak); an unchanged relaunch restarts nothing; idle rebinds only store. Merely BUILDING the producer rebinds the shared tracker. **Retention rule (stated and tested):** only the merged seams survive the last unsubscribe; the last reading does not (`current()` is undefined with no listener, and is dropped on a failed/unsane read and on a path change); payloads and `current()` are copies. Hardening: reporter indirection that swallows a throwing `onError`, a timer that cannot be armed is reported and leaves the tracker inert, a throwing `clearInterval` is reported. The disk producer is NOT built when the legacy `systemMetricsSampler` replaces the producer list (it would never start, and building it touches the shared tracker). Launch tests wrap `storageTrackerFor` and prove the opt-in launch goes through it (mutating the producer to `new StorageTracker` fails) and that no tracker is requested when the opt-in is off or there is no data dir. `@bugsee/node` also re-exports `storageTrackerFor`/`resetStorageTracker`/`StorageTracker`. **Behaviour notes:** (1) the tracker is one per DATA DIR, so a second launch over the same dir shares it (and hands it its `onError`/seams) while a launch over another dir has its own (tests that inject `diskStatfs` must pass a private `key` or call `resetStorageTracker()`; added to the node launch test afterEach); (2) within one dir, seams merge, so a later launch without `diskStatfs`/`scheduler` keeps an earlier launch's; (3) wire behaviour is unchanged (each producer polls its own dir and reports to its own `onError`, as the pre-tracker code did); a relaunch over the same dir with a changed seam re-reads at once. An earlier revision keyed the singleton on the `process` object and let a later launch's data dir replace a running launch's: fixed in review. - **TR9 part 1 (implemented on `feat/electron-process-tracker`; Electron main-process PROCESS tracker; power/screen/window events are in part 2 below):** the **`ElectronProcessTracker`** (`packages/trackers/src/electron/process-tracker.ts`, `@bugsee/trackers/electron`, previously an empty placeholder) ABSORBS `@bugsee/electron`'s `GpuInfoCache` (file, tests and `mapGpuInfo` moved: `mapGpuInfo` now lives in `packages/trackers/src/electron/gpu-info.ts` and returns a neutral `ElectronGpu`, structurally the `HardwareGpu` of `@bugsee/node`). Singleton per `app` object (`electronProcessTrackerFor({app, scheduler?, intervalMs?, key?}, onError?)`, `resetElectronProcessTracker(key)`; no `app` and no `key` throws, a shared anonymous tracker would have no owner). Electron is INJECTED as the structural `ElectronAppSource` (`getAppMetrics`/`getGPUInfo`/`on`/`removeListener`|`off`); the package depends on neither `electron` nor the DOM. THREE stages: `appMetrics` (one unref'd timer, default 1 s, armed only while it has a listener; `{processes: [{type, pid, cpuPct?, workingSetBytes?, peakWorkingSetBytes?, privateBytes?}]}`, Electron's KiB converted to bytes, a field Electron did not give is omitted never zeroed, a process with no usable metric is dropped, an empty/non-array result emits nothing; it is WINDOWED, so arming makes ONE discarded PRIMING `getAppMetrics` read and the first emission is the first tick; Chromium returns 0 on the FIRST CPU call per process (Electron keeps one metrics object per child process), so the tracker remembers the pids of the previous read and omits `cpuPct` for a pid's first sighting (a renderer or restarted GPU/utility process appearing later, same type new pid), and where Electron reports `cpu.cumulativeCPUUsage` a process without it also has no `cpuPct` (Electron sends 0 "for compatibility"); `cpuPct` is the share of the WHOLE machine, 0-100; `current('appMetrics')` is the last sample of the run), `childProcessGone` (`app.on('child-process-gone')` attached only while a listener exists and removed with the same function when the last leaves; `{type, reason, exitCode?, name?}`, malformed details ignored; not attached at all when the app has neither `removeListener` nor `off`, since it could never be released), and `gpu` (`requestGpuInfo(type = 'basic')` / `cancelGpuInfo()` / `current('gpu')`: a USABLE settled value is kept and not re-requested for the same type; it asks again after a rejection/throw/unmappable result or for a DIFFERENT type, and a failed re-ask keeps the earlier usable value; a rejection or throw is reported and no unhandled rejection results, a late result after `cancelGpuInfo()` is ignored; the `gpu` stage fires on each usable settle). `render-process-gone` is NOT part of the tracker: it is an incident path and `renderer-gone.ts` is unchanged. Seams merge never drop, `rebind` on a changed seam tears the run down with the OLD seams and re-arms (re-primes) on the new, generation-guarded timer callbacks, a throwing/async reporter never escapes. **Retention rule (stated and tested):** only the merged seams and the once-only GPU result survive the last unsubscribe; the priming read is repeated and the last sample dropped; `reset()` drops everything including the GPU. **Producers in `@bugsee/electron` (composition only):** `system-traces.ts` (`createElectronSystemTraceProducers(tracker)` -> one `app_metrics` producer) and `system-events.ts` (`createElectronSystemEventsSource(inner, tracker, onError?)`, a LAZY mux: nothing attached at construction; on the first subscriber it subscribes to the inner node source (its `process_started` and signal/exit handlers) AND the tracker's `childProcessGone`, releasing both, each guarded, on the last unsubscribe; it never emits `process_started` itself). **Wire shapes:** trace `app_metrics` = `{processes: [{type, pid, cpu_percent?, working_set_mb?, peak_working_set_mb?, private_mb?}]}` (Electron's process type verbatim, `cpu_percent` the whole-machine share rounded to 2 decimals, integer binary MB via `bytesToMegabytes`, `hold:false` so a failing read leaves a gap; JS-specific name, neither Android nor the viewer has an entry, so it is an open object like `storage_estimate`; **viewer support is UNCONFIRMED (Q5)** and flat per-type totals are the alternative shape); event `child_process_gone` on `events.system` with params `{type, reason, exitCode?, name?}` (`exitCode` stays camelCase: the existing multi-word event params, e.g. the browser's `previousLanguage`, are camelCase; it also fires with `reason: 'clean-exit'`). **`@bugsee/node`:** new advanced launch option `wrapSystemEventsSource(inner)` (the seam P3 asks for): the provider subscribes to the SOURCE it returns, a throwing factory is reported and the plain node source is used. **`launchMain`:** with an `app` and when this is NOT a repeat call (a repeat is detected up front from the carrier client, exactly `launchCore`'s own test, so it can never rebind the running launch's shared trackers) it builds the tracker THROUGH `electronProcessTrackerFor`, passes `systemTraceProducers = [...(caller's ?? createNodeSystemTraceProducers({scheduler, onError})), ...electron producers]` (not when the legacy `systemMetricsSampler` is set), composes `wrapSystemEventsSource` (a caller wrapper first, ours around it), and serves `hardware.gpu` from `tracker.current('gpu')` (same field-wise `hardwareExtras` precedence and `sanitizeHardwareGpu` as ST6a; `gpuInfoType` still `'basic'|'complete'`); the GPU read is requested once on the FIRST launch and cancelled in `client.stop()`. `@bugsee/electron` gained the `@bugsee/trackers` and `@bugsee/capture` workspace dependencies. **Tests:** tracker unit tests (100% with the mutator loop), producer/mux unit tests, launch-level tests (accessor spy: mutating launchMain to `new ElectronProcessTracker` fails; node + Electron traces both present with no name twice; a throwing `getAppMetrics` leaves the node producers emitting) and a real-launch integration test (`system-telemetry.integration.test.ts`: `app_metrics` next to node traces in the uploaded bundle, `child_process_gone` on `events.system`, `captureSystemEvents:false` -> no node handlers and no `child-process-gone` listener, `client.stop()` releases handlers, listener and timers). **Not verified without a real Electron (source-verified by review, not run):** the real `getAppMetrics` shape and units (KiB), `child-process-gone` details, and `getGPUInfo` output. - **TR9 part 2 (implemented on `feat/electron-power-display-app-trackers`; the remaining Electron-main DOMAIN trackers):** three more per-object singleton trackers in `@bugsee/trackers/electron`, all with Electron INJECTED structurally (no electron/DOM dependency), a shared `stage-tracker.ts` (`ElectronStageTracker` base + `bindAll`: per-STAGE lazy attach on a stage's first listener and release on its last, all-or-nothing attach with rollback, a source with no `removeListener`/`off` is never attached to, every wrapper is liveness-guarded so a listener whose removal failed can never emit, a throwing/async reporter is absorbed; `process-tracker.ts` now shares its `reportTo`). **`ElectronPowerTracker`** (`electronPowerTrackerFor({powerMonitor}, onError?)`, `resetElectronPowerTracker(key)`; keyed on the monitor; stages `suspendResume` `{state:'suspend'|'resume'}`, `lockScreen` `{state:'lock'|'unlock'}` (macOS/Windows; never fires on Linux), `powerSource` `{source:'ac'|'battery'}`; `current('powerSource')` is a LIVE `isOnBatteryPower()` read, undefined without the method / non-boolean / throw (reported), never guessed; `thermal-state-change`/`speed-limit-change` deliberately NOT mapped: macOS-only and the thermal state is not Android's int enum). **`ElectronDisplayTracker`** (`electronDisplayTrackerFor({screen}, onError?)`; stages `displayAdded`/`displayRemoved` -> `DisplayInfo`, `displayMetricsChanged` -> `{display, changed: string[]}`, `displays` -> `{displays: DisplayInfo[]}` re-read from `getAllDisplays()` after any of the three; `current('displays')` is live; `DisplayInfo = {id, width, height, scaleFactor?, rotation?: 0|90|180|270, internal?, refreshRate?}` from Electron's `size` (bounds fallback), `label`/position/`workArea` are NOT kept, a display with no finite id or positive size is dropped, an empty/unreadable list is undefined, never `[]`). **`ElectronApplicationTracker`** (`electronApplicationTrackerFor({app, BrowserWindow?}, onError?)`, keyed on `app`; `rebind` re-arms when the `BrowserWindow` seam changes; stages `windowFocus` `{focused, windowId?}`, `windowVisibility` `{visible, windowId?}`, `rendererResponsiveness` `{responsive, webContentsId?}`; each stage watches the objects that EXIST at arm time (`BrowserWindow.getAllWindows()`, and each window's `webContents`) AND those created later (`app.on('browser-window-created')` / `app.on('web-contents-created')`), binds each object once, forgets it on `closed`/`destroyed` without touching the dead object, skips `isDestroyed()` objects at bind and at release, tolerates a throwing `getAllWindows`/`id`/`isDestroyed`; **the hang pair is on `webContents` ONLY** because `BrowserWindow` re-emits it; ids are Electron's numeric `id`, omitted when absent; titles/URLs are never read). **Wire names (`@bugsee/electron`):** `events.system` `power_suspend`, `power_resume`, `power_lock`, `power_unlock`, `power_ac`, `power_battery` (no params); `display_added`/`display_removed` params `{id, width, height, scaleFactor?, rotation?, internal?, refreshRate?}`, `display_metrics_changed` params the same plus `changed: string[]`; `window_focus`/`window_blur`/`window_show`/`window_hide` params `{windowId?}`; `renderer_unresponsive`/`renderer_responsive` params `{webContentsId?}` (snake_case names like `process_*`/`child_process_gone`, camelCase params like `exitCode`). Trace **`electron_displays`** = `{displays: [{id, width, height, scale_factor?, rotation?, internal?, refresh_rate_hz?}]}`, a HELD step trace (`emitIfChanged`: baseline at start, then the fresh list after each display change), absent when Electron gives no usable list. **Name choice:** `displays` stays RESERVED: nothing in `@bugsee/protocol`/`@bugsee/capture` defines an Android-shaped display list (only a comment that mobile-only `displays` is not sampled) and the viewer shape is unconfirmed (Q5), so the JS-specific `electron_displays` is used. `system-events.ts` mux now takes `{process?, power?, display?, application?}` and forwards all of the above lazily (nothing attached at construction or with `captureSystemEvents:false`; every release guarded); `system-traces.ts` `createElectronSystemTraceProducers({process?, display?})` adds the displays producer. `LaunchMainOptions` gains optional `powerMonitor`, `screen`, `BrowserWindow` (destructured out of `...nodeOptions`); `ElectronAppLike` gains `on('browser-window-created'|'web-contents-created')` and widened `removeListener`/`off`; each tracker is built THROUGH its registry accessor, skipped on a repeat launch (carrier client present) and absent when its object was not injected (a `powerMonitor` alone still gets the mux, a `screen` alone still gets the displays producer; the legacy `systemMetricsSampler` still suppresses producers). **Tests:** per-tracker unit tests with the mutator loop (about 40 mutations over the three trackers/base, 0 survivors after strengthening: forgetting on closed/destroyed, release skipping destroyed objects, rotation mapping), mux/producer unit tests, launch-level accessor spies (mutating any of the three to `new` fails) and real-launch integration tests (events + trace in the uploaded bundle, a window created AFTER launch records focus, `webContents` hang recorded ONCE although the window re-emits it and `win.emit('unresponsive')` alone records nothing, option off -> no listeners, `client.stop()` -> all released, a throwing Electron getter never fails launch, a repeat launch leaves the running trackers' reporter untouched). **NOT verified without a real Electron (source/doc-verified, not run):** the real `powerMonitor` event firing and `isOnBatteryPower()` semantics per OS, the real `Display` object shape (`size`, `displayFrequency`, `rotation`) and `display-metrics-changed` argument order `(event, display, changedMetrics)`, `browser-window-created`/`web-contents-created` ordering, `BrowserWindow` re-emitting `unresponsive` after ~50 ms, and `webContents` `destroyed`/window `closed` timing. **Review fixes (#91):** every host property read in `isReleasable`/`bindAll`/`current()` is guarded (Electron's real `screen` is a Proxy that throws on ANY property read before app ready: a throwing object = that domain off, reported, never a failed launch); `sync()` guards `attachStage`; the mux isolates EVERY subscription in `onActivate` (it never throws, so the provider always gets its unsubscribe and `stop()` releases the inner source's handlers too); display id -1 ('invalid or not yet known') is dropped, -10 (virtual unified display) is kept as reported; `on-ac` (darwin/win32) and `on-battery` (darwin only) are platform dependent and `current('powerSource')` is the live truth; new launch option `captureWindowEvents` (default true, opt-out) for the window domain, which is ON whenever `app` is passed. **OPEN OWNER DECISION (held values), now also covering `electron_displays`:** a refresh that cannot read a usable list emits nothing and a held trace cannot be retracted, so the previous list stays held and is re-recorded every `refreshMs` (absent only before the first emit); same class as `storage_estimate` / `user_idle_state`. Known limits: a `webContents` that existed before `launchMain` and has no `BrowserWindow` (an earlier `BrowserView`/``) is not discovered; `screen` must be injected after `app` is ready (a throwing one turns the display domain off); viewer support for `electron_displays` and the new event names is unconfirmed (Q5). diff --git a/packages/bun/src/launch.test.ts b/packages/bun/src/launch.test.ts index 889cee6f4..97a960c95 100644 --- a/packages/bun/src/launch.test.ts +++ b/packages/bun/src/launch.test.ts @@ -129,12 +129,12 @@ describe('@bugsee/bun launch', () => { expect(names).not.toContain('cpu_usage_process'); // no CPU start value: it begins with the first sampled window }); - it('opts out of the V8 heap and gc traces and reads MemAvailable first for ram_system_free (Bun: JSC heap, not comparable availableMemory, blind GC observer)', () => { + it('opts out of the V8 heap and gc traces (Bun: JSC heap, blind GC observer) and reads /proc/meminfo MemAvailable for ram_system_free', () => { track(launchCore('tok', base()).client); expect(createNodeSystemTraceProducers).toHaveBeenCalledWith( expect.objectContaining({ measuresV8Heap: false, - measuresAvailableMemory: false, + readsProcMeminfo: true, measuresGc: false, }), ); diff --git a/packages/bun/src/launch.ts b/packages/bun/src/launch.ts index 8c596f0ed..fd55128d1 100644 --- a/packages/bun/src/launch.ts +++ b/packages/bun/src/launch.ts @@ -24,8 +24,9 @@ export function launchCore(appToken: string, options: BugseeLaunchOptions = {}): // so the V8 heap traces are omitted here. measuresV8Heap: false, // Bun < 1.3.13's `os.freemem()` is not MemAvailable on Linux, so `ram_system_free` reads /proc/meminfo - // MemAvailable first there, then os.freemem(). `process.availableMemory()` is never used. - measuresAvailableMemory: false, + // MemAvailable first there, then os.freemem() (omitted on macOS: Bun has no native available figure). + // `process.availableMemory()` is never used. + readsProcMeminfo: true, // `PerformanceObserver('gc')` is BLIND on Bun (0 entries after heavy churn β€” measured): a quiet-looking // zero would be a lie, so no observer is constructed and the gc traces are omitted. measuresGc: false, diff --git a/packages/deno/src/launch.test.ts b/packages/deno/src/launch.test.ts index f4bece19c..c38dc49bf 100644 --- a/packages/deno/src/launch.test.ts +++ b/packages/deno/src/launch.test.ts @@ -312,10 +312,10 @@ describe('@bugsee/deno β€” the event-loop metrics Deno cannot measure', () => { ); }); - it('reads MemAvailable first for ram_system_free (a different quantity) and gc (blind observer) and keeps the V8 heap (real V8)', () => { + it('never reads /proc/meminfo for ram_system_free (a scoped --allow-read would prompt), opts out of gc (blind observer) and keeps the V8 heap (real V8)', () => { track(launchCore('tok', base()).client); const arg = vi.mocked(createNodeSystemTraceProducers).mock.calls[0]?.[0]; - expect(arg?.measuresAvailableMemory).toBe(false); + expect(arg).not.toHaveProperty('readsProcMeminfo'); // only Bun reads /proc/meminfo expect(arg?.measuresGc).toBe(false); expect(arg).not.toHaveProperty('measuresV8Heap'); // the node default (true) applies }); diff --git a/packages/deno/src/launch.ts b/packages/deno/src/launch.ts index 8f52f186d..a53563ca7 100644 --- a/packages/deno/src/launch.ts +++ b/packages/deno/src/launch.ts @@ -28,9 +28,9 @@ export function launchCore(appToken: string, options: BugseeLaunchOptions = {}): // its own tell (a zero `idle`), so it needs no flag. systemTraceProducers: createNodeSystemTraceProducers({ measuresEventLoopDelay: false, - // Deno's `process.availableMemory()` is not comparable (0 on Windows, includes inactive pages on macOS), so it - // is never used; `ram_system_free` reads /proc/meminfo MemAvailable first on Linux, then os.freemem(). - measuresAvailableMemory: false, + // `ram_system_free` on Deno: `os.freemem()` (MemAvailable on Linux since 2023, avail_phys on Windows) and + // `Deno.systemMemoryInfo().available` on macOS. It must NOT read /proc/meminfo (no `readsProcMeminfo`): the + // read triggers an interactive permission prompt under a scoped `--allow-read`. // `PerformanceObserver('gc')` is BLIND on Deno too (0 entries, also with --v8-flags=--expose-gc): omit. measuresGc: false, // the shared tracker's sampling timer honors an injected scheduler, and its poll errors are reported diff --git a/packages/node/src/trace-producers.test.ts b/packages/node/src/trace-producers.test.ts index aa9ccbf39..319f4411a 100644 --- a/packages/node/src/trace-producers.test.ts +++ b/packages/node/src/trace-producers.test.ts @@ -206,7 +206,7 @@ describe('createNodeSystemTraceProducers', () => { for (const k of h.got.keys()) expect(k).not.toMatch(/^(v8_heap_|ram_js_heap_)/); }); - it('ram_system_free is os.freemem() on Node and MemAvailable-first when measuresAvailableMemory is false; total stays total', () => { + it('ram_system_free: os.freemem() (not on macOS), MemAvailable first for readsProcMeminfo, native first of all; total stays total', () => { const { systemMemory: _s, ...base } = constDeps({ eventLoop }); const run1 = (over: NodeTraceProducerDeps) => { const h = harness({ ...base, memoryLimit: () => undefined, ...over }); @@ -214,18 +214,27 @@ describe('createNodeSystemTraceProducers', () => { return h.got; }; const meminfo = () => 'MemAvailable: 3 kB\n'; - expect(run1({ meminfo, freeMemory: () => 9 }).get('ram_system_free')).toBe(9); + expect(run1({ platform: 'linux', meminfo, freeMemory: () => 9 }).get('ram_system_free')).toBe( + 9, + ); + expect(run1({ platform: 'darwin', freeMemory: () => 9 }).has('ram_system_free')).toBe(false); expect( - run1({ measuresAvailableMemory: false, meminfo, freeMemory: () => 9 }).get( + run1({ platform: 'darwin', nativeAvailableMemory: () => 5 }).get('ram_system_free'), + ).toBe(5); + expect( + run1({ platform: 'linux', readsProcMeminfo: true, meminfo, freeMemory: () => 9 }).get( 'ram_system_free', ), ).toBe(3072); expect( - run1({ measuresAvailableMemory: false, meminfo: () => undefined, freeMemory: () => 9 }).get( - 'ram_system_free', - ), + run1({ + platform: 'linux', + readsProcMeminfo: true, + meminfo: () => undefined, + freeMemory: () => 9, + }).get('ram_system_free'), ).toBe(9); - const none = run1({ freeMemory: () => Number.NaN }); + const none = run1({ platform: 'linux', freeMemory: () => Number.NaN }); expect(none.has('ram_system_free')).toBe(false); expect(Number(none.get('ram_system_total'))).toBeGreaterThan(0); }); @@ -541,7 +550,8 @@ describe('createNodeSystemTraceProducers', () => { tick?.(); for (const p of ps) p.stop(); // `process_memory_limit` exists only inside a real cgroup cap, so it is checked for what the host can answer. - const optional = ['process_memory_limit']; + // `ram_system_free` is omitted on macOS (os.freemem() there is not memory available to new work). + const optional = ['process_memory_limit', 'ram_system_free']; expect([...got.keys()].filter((k) => !optional.includes(k)).sort()).toEqual([ 'cpu_usage_process', 'cpu_usage_system', @@ -562,7 +572,6 @@ describe('createNodeSystemTraceProducers', () => { 'ram_js_heap_free', 'ram_js_heap_total', 'ram_js_heap_used', - 'ram_system_free', 'ram_system_total', 'v8_heap_available', 'v8_heap_malloced', @@ -570,9 +579,12 @@ describe('createNodeSystemTraceProducers', () => { 'v8_heap_size_limit', ]); expect(got.has('ram_system_available')).toBe(false); // retired - expect(Number(got.get('ram_system_free'))).toBeLessThanOrEqual( - Number(got.get('ram_system_total')), - ); + if (process.platform === 'darwin') expect(got.has('ram_system_free')).toBe(false); + else { + expect(Number(got.get('ram_system_free'))).toBeLessThanOrEqual( + Number(got.get('ram_system_total')), + ); + } expect(Number(got.get('v8_heap_size_limit'))).toBeGreaterThan(0); for (const v of got.values()) expect(Number.isFinite(v)).toBe(true); }); diff --git a/packages/node/src/trace-producers.ts b/packages/node/src/trace-producers.ts index 15f1325c6..3fc3e8432 100644 --- a/packages/node/src/trace-producers.ts +++ b/packages/node/src/trace-producers.ts @@ -161,9 +161,9 @@ class UptimeProducer extends StageProducer<'uptime'> { } /** - * The tracker seams plus the platform GATES (`measuresEventLoopDelay`, `measuresV8Heap`, `measuresAvailableMemory`, + * The tracker seams plus the platform GATES (`measuresEventLoopDelay`, `measuresV8Heap`, * `measuresGc`; see {@link ProcessTrackerEnv}) β€” runtime-identity facts the platform packages pass in: Deno gates the - * event-loop histogram, Bun the V8 heap, both the os.freemem()-is-available assumption and the GC reader. + * event-loop histogram, Bun the V8 heap, both the GC reader (Bun also sets `readsProcMeminfo`). */ export interface NodeTraceProducerDeps extends ProcessTrackerEnv { onError?: (error: unknown) => void; diff --git a/packages/trackers/README.md b/packages/trackers/README.md index b1c89a2e7..4d32f8c02 100644 --- a/packages/trackers/README.md +++ b/packages/trackers/README.md @@ -24,7 +24,7 @@ Trackers are the abstraction over system and runtime APIs. The package root is r The `./browser` entry exports the `ApplicationTracker` (`applicationTrackerFor`, `resetApplicationTracker`; stages `pagehide`, `visibility`, `state`, `freeze`, `resume`; `online`/`offline` belong to the `ConnectivityTracker` and `orientationchange` to the `UiTracker`), the `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`), the `ConnectivityTracker` (`connectivityTrackerFor`, `resetConnectivityTracker`; stages `online`, `networkInfo`, `state` and `transition`, one per DOM online/offline event with its kind from the event type), the `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; stages `heap`, `mainThreadLag` (timer drift), `idle` (`requestIdleCallback`), `userIdle` (Idle Detection) and `uptime`, each armed only while it has listeners; the SDK never prompts, so `userIdle` runs only when the `idle-detection` permission is already granted; the SDK's `user_idle_state` trace additionally needs the browser/WebView launch option `captureUserIdle: true`, because a page's own grant is not consent to record and upload idle/locked state), the UI/display `UiTracker` (`uiTrackerFor`, `resetUiTracker`: orientation, screenSize, viewport, visualViewport (pinch zoom and pan), colorScheme, reducedMotion, displayMode, frameRate), the `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; an approximate origin quota estimate, not device free space: browsers may pad `usage`, and `quota` can roughly reveal the device's disk size, so treat it as potentially identifying), the `EnvironmentTracker` (`environmentTrackerFor`, `resetEnvironmentTracker`; language, time zone, and, only when a consumer sets `observeHints` / `queryPermissions`, environment hints and Permissions API states queried without ever prompting; the private-browsing heuristic runs when `detectPrivateMode` is set (the browser launch sets it by default; opt out with `captureEnvironmentHints: false`) and is never reported as a certainty) and `hostRead`; the `./electron` entry exports the Electron main-process domain trackers, with every Electron object injected structurally and never imported: the `ElectronProcessTracker` (`electronProcessTrackerFor`, `resetElectronProcessTracker`; stages `appMetrics`, `childProcessGone` and a once-only GPU read), the `ElectronPowerTracker` (`electronPowerTrackerFor`, keyed on `powerMonitor`; stages `suspendResume`, `lockScreen`, `powerSource` and a live `current('powerSource')`), the `ElectronDisplayTracker` (`electronDisplayTrackerFor`, keyed on `screen`; stages `displayAdded`, `displayRemoved`, `displayMetricsChanged`, `displays` and a live `current('displays')`) and the `ElectronApplicationTracker` (`electronApplicationTrackerFor`, keyed on `app`; stages `windowFocus`, `windowVisibility` and `rendererResponsiveness`, which listens on `webContents` only), plus `mapGpuInfo` and `mapDisplay`. Each stage attaches its Electron listeners only while it has a subscriber and removes them when the last leaves. Its API is internal and may change between releases. -The `./node` entry is shared by Node, Bun and Deno and exports the process `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; a per-process singleton, keyed on the `process` object by default). Its nine stages (`memory`, `systemMemory`, `cpu`, `eventLoop`, `utilization`, `gc`, `v8Heap`, `memoryLimit`, `uptime`) are each armed only while they have listeners, behind one shared sampling timer. A stage the runtime cannot honestly measure emits nothing rather than zero (event-loop utilization on Bun/Deno is dropped by its own tell, idle and active both zero; the event-loop delay histogram on Deno, the GC observer on Bun/Deno, and the V8 heap on Bun are gated by the `measures*` flags; `systemMemory.free` is memory available to new work: `os.freemem()` on Node, `/proc/meminfo` MemAvailable first on Linux where `measuresAvailableMemory` is false (Bun/Deno), omitted when no source is plausible the platform packages pass in). The CPU stage has no start value: it reports from the first tick. Seams merge and are never dropped: a later launch that omits `scheduler` or `onError` keeps the previous launch's, and building a producer set already rebinds the shared tracker, so tests that inject fakes need a private `key` or `resetProcessTracker()`. It also exports the guarded runtime sources it is built from (`createGuardedEventLoopSource`, `createGuardedElu`, `createGcSource`, `createV8HeapReader`, `createMemoryLimitReader`, `createSystemFreeReader`, `createProcMeminfoReader`, `parseMemAvailable`). +The `./node` entry is shared by Node, Bun and Deno and exports the process `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; a per-process singleton, keyed on the `process` object by default). Its nine stages (`memory`, `systemMemory`, `cpu`, `eventLoop`, `utilization`, `gc`, `v8Heap`, `memoryLimit`, `uptime`) are each armed only while they have listeners, behind one shared sampling timer. A stage the runtime cannot honestly measure emits nothing rather than zero (event-loop utilization on Bun/Deno is dropped by its own tell, idle and active both zero; the event-loop delay histogram on Deno, the GC observer on Bun/Deno, and the V8 heap on Bun are gated by the `measures*` flags the platform packages pass in). `systemMemory.free` is memory available to new work in bytes (Android `availMem`): Electron `process.getSystemMemoryInfo()` or Deno `systemMemoryInfo().available` on macOS first, then `/proc/meminfo` MemAvailable where `readsProcMeminfo` is true (Bun only), then `os.freemem()` (not on macOS). Node and Bun on macOS omit it, and it is omitted whenever no source is plausible. Inside a container it is the host's figure; the cap is `process_memory_limit`. The CPU stage has no start value: it reports from the first tick. Seams merge and are never dropped: a later launch that omits `scheduler` or `onError` keeps the previous launch's, and building a producer set already rebinds the shared tracker, so tests that inject fakes need a private `key` or `resetProcessTracker()`. It also exports the guarded runtime sources it is built from (`createGuardedEventLoopSource`, `createGuardedElu`, `createGcSource`, `createV8HeapReader`, `createMemoryLimitReader`, `createSystemFreeReader`, `createElectronMemoryReader`, `createDenoMemoryReader`, `createProcMeminfoReader`, `parseMemAvailable`). The `./node` entry also exports the disk `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; one singleton per resolved data directory, so launches over the same directory share a tracker and launches over different directories never affect each other; a launch without a data directory gets the shared inert `process`-keyed tracker, and an explicit `key` overrides, for tests) behind the opt-in `disk_mem_free` / `disk_mem_total` traces. Its one stage, `disk` (`{freeBytes, totalBytes}`), reads the volume of the launch's data directory with `fs.promises.statfs` (not `/` or the working directory) at once when a listener arrives and then on its own unref'd 5 s timer, and does nothing while no one listens, when there is no data directory, or when the runtime has no `statfs`. An unreadable or unsane reading emits nothing (a full disk is a true 0 free), and failures are reported once per failure streak. Within one directory's tracker, `onError`, `scheduler` and `statfs` are latest-launch-wins, an omitted seam keeps the earlier one, and a changed seam is applied (and re-read) immediately. Only the merged seams survive the last unsubscribe; the last reading does not. diff --git a/packages/trackers/src/node/index.test.ts b/packages/trackers/src/node/index.test.ts index 08db9dd72..1b8f2784f 100644 --- a/packages/trackers/src/node/index.test.ts +++ b/packages/trackers/src/node/index.test.ts @@ -7,6 +7,8 @@ describe('@bugsee/trackers/node public surface', () => { expect(Object.keys(nodeEntry).sort()).toEqual([ 'ProcessTracker', 'StorageTracker', + 'createDenoMemoryReader', + 'createElectronMemoryReader', 'createGcSource', 'createGuardedElu', 'createGuardedEventLoopSource', @@ -15,6 +17,7 @@ describe('@bugsee/trackers/node public surface', () => { 'createSystemFreeReader', 'createV8HeapReader', 'eluUnavailable', + 'firstAnswer', 'parseMemAvailable', 'processTrackerFor', 'realPerfHooks', diff --git a/packages/trackers/src/node/index.ts b/packages/trackers/src/node/index.ts index 6f1ca18c1..e9973665c 100644 --- a/packages/trackers/src/node/index.ts +++ b/packages/trackers/src/node/index.ts @@ -29,10 +29,13 @@ export { resetProcessTracker, } from './process-tracker'; export { + createDenoMemoryReader, + createElectronMemoryReader, createMemoryLimitReader, createProcMeminfoReader, createSystemFreeReader, createV8HeapReader, + firstAnswer, parseMemAvailable, type V8HeapStats, } from './runtime-readers'; diff --git a/packages/trackers/src/node/process-tracker.test.ts b/packages/trackers/src/node/process-tracker.test.ts index 22f56a6c0..877a4f731 100644 --- a/packages/trackers/src/node/process-tracker.test.ts +++ b/packages/trackers/src/node/process-tracker.test.ts @@ -1,3 +1,4 @@ +import nodeProcessForTest from 'node:process'; import { describe, expect, it, vi } from 'vitest'; import { type EventLoopSource, @@ -399,8 +400,12 @@ describe('ProcessTracker', () => { const cap = tracker.current('memoryLimit'); if (cap !== undefined) expect(cap.bytes).toBeGreaterThan(0); const sys = tracker.current('systemMemory'); - expect(sys?.free).toBeGreaterThanOrEqual(0); - expect(sys?.free).toBeLessThanOrEqual(sys?.total ?? 0); + if (process.platform === 'darwin') { + expect(sys).not.toHaveProperty('free'); // os.freemem() is not memory available to new work there + } else { + expect(sys?.free).toBeGreaterThanOrEqual(0); + expect(sys?.free).toBeLessThanOrEqual(sys?.total ?? 0); + } }); it('real cpu defaults: the first tick reports finite deltas and a percentage', () => { @@ -512,23 +517,58 @@ describe('ProcessTracker', () => { describe('systemMemory.free: memory available to new work', () => { const free = (over: Partial) => - mk({ systemMemory: undefined, ...over }).tracker.current('systemMemory'); + mk({ systemMemory: undefined, platform: 'linux', ...over }).tracker.current('systemMemory'); const meminfo = () => 'MemAvailable: 2 kB\n'; - it('Node default: os.freemem() (via the injected seam), never /proc/meminfo', () => { - expect(free({ freeMemory: () => 7, meminfo })?.free).toBe(7); + it('default: os.freemem(), and /proc/meminfo is never read (Deno must not trigger a permission prompt)', () => { + let reads = 0; + const got = free({ freeMemory: () => 7, meminfo: () => (reads++, 'MemAvailable: 2 kB\n') }); + expect(got?.free).toBe(7); + expect(reads).toBe(0); }); - it('measuresAvailableMemory:false (Bun/Deno): MemAvailable first, then os.freemem()', () => { - expect(free({ measuresAvailableMemory: false, freeMemory: () => 7, meminfo })?.free).toBe( - 2048, - ); + it('readsProcMeminfo (Bun): MemAvailable first, then os.freemem()', () => { + expect(free({ readsProcMeminfo: true, freeMemory: () => 7, meminfo })?.free).toBe(2048); expect( - free({ measuresAvailableMemory: false, freeMemory: () => 7, meminfo: () => undefined }) - ?.free, + free({ readsProcMeminfo: true, freeMemory: () => 7, meminfo: () => undefined })?.free, ).toBe(7); }); + it('a native source (Electron/Deno) wins over every other; it falls through when it has no answer', () => { + const base = { freeMemory: () => 7, readsProcMeminfo: true, meminfo }; + expect(free({ ...base, nativeAvailableMemory: () => 5 })?.free).toBe(5); + expect(free({ ...base, nativeAvailableMemory: () => undefined })?.free).toBe(2048); + }); + + it('macOS: os.freemem() (free pages only) is NOT a source, so Node/Bun omit free and keep total', () => { + const got = free({ platform: 'darwin', freeMemory: () => 7 }); + expect(got?.total).toBeGreaterThan(0); + expect(got).not.toHaveProperty('free'); + expect( + free({ platform: 'darwin', freeMemory: () => 7, nativeAvailableMemory: () => 9 })?.free, + ).toBe(9); + expect(free({ platform: 'win32', freeMemory: () => 7 })?.free).toBe(7); + }); + + it('default native sources: Electron process.getSystemMemoryInfo() on this process object, Deno systemMemoryInfo on macOS', () => { + const proc = nodeProcessForTest as { getSystemMemoryInfo?: unknown }; + const g = globalThis as { Deno?: unknown }; + const hadDeno = 'Deno' in g; + const prevDeno = g.Deno; + try { + proc.getSystemMemoryInfo = () => ({ available: 3 }); // KiB, linux + expect(free({ platform: 'linux', freeMemory: () => 7 })?.free).toBe(3072); + delete proc.getSystemMemoryInfo; + g.Deno = { systemMemoryInfo: () => ({ available: 4096 }) }; + expect(free({ platform: 'darwin' })?.free).toBe(4096); + expect(free({ platform: 'linux', freeMemory: () => 7 })?.free).toBe(7); // Deno source is macOS-only + } finally { + delete proc.getSystemMemoryInfo; + if (hadDeno) g.Deno = prevDeno; + else delete g.Deno; + } + }); + it('omits free (keeps total) when no source answers a plausible value', () => { const got = free({ freeMemory: () => Number.NaN }); expect(got?.total).toBeGreaterThan(0); @@ -541,6 +581,30 @@ describe('ProcessTracker', () => { free: 40, }); }); + + it('every free-memory seam survives processTrackerFor (a dropped SEAM_KEYS entry would silently ignore it)', () => { + const at = (env: Partial) => { + const key = {}; + try { + return processTrackerFor({ + key, + scheduler: fakeScheduler().scheduler, + platform: 'linux', + freeMemory: () => 11, + ...env, + }).current('systemMemory'); + } finally { + resetProcessTracker(key); + } + }; + expect(at({})?.free).toBe(11); // freeMemory + platform(linux: freemem is a source) + expect(at({ platform: 'darwin' })).not.toHaveProperty('free'); // platform + expect(at({ readsProcMeminfo: true, meminfo: () => 'MemAvailable: 1 kB\n' })?.free).toBe( + 1024, + ); // readsProcMeminfo + meminfo + expect(at({ meminfo: () => 'MemAvailable: 1 kB\n' })?.free).toBe(11); // meminfo ignored without readsProcMeminfo + expect(at({ nativeAvailableMemory: () => 77 })?.free).toBe(77); // nativeAvailableMemory + }); }); it('guarded ELU: a fresh baseline per arming, and Bun/Deno-style flat zeros are omitted, never reported as 0%', () => { diff --git a/packages/trackers/src/node/process-tracker.ts b/packages/trackers/src/node/process-tracker.ts index a5e04bd8d..479470d7c 100644 --- a/packages/trackers/src/node/process-tracker.ts +++ b/packages/trackers/src/node/process-tracker.ts @@ -14,10 +14,15 @@ import { realPerfHooks, } from './guarded-event-loop'; import { + createDenoMemoryReader, + createElectronMemoryReader, createMemoryLimitReader, createProcMeminfoReader, createSystemFreeReader, createV8HeapReader, + type DenoMemoryInfoLike, + type ElectronMemoryInfoLike, + firstAnswer, type V8HeapStats, } from './runtime-readers'; @@ -127,10 +132,18 @@ export interface ProcessEnv { /** Each reader answers undefined when the runtime cannot give a true value. Override their defaults and gates. */ v8Heap?: () => V8HeapStats | undefined; memoryLimit?: () => number | undefined; - /** Raw `/proc/meminfo` text (Linux), consulted first only when `measuresAvailableMemory` is false. Default reads the file on Linux only. */ + /** Raw `/proc/meminfo` text (Linux), consulted only when `readsProcMeminfo` is true. Default reads the file on Linux only. */ meminfo?: () => string | undefined; - /** `os.freemem()` bytes, the primary source of system free memory (see `createSystemFreeReader`). */ + /** `os.freemem()` bytes (not a source on macOS; see `createSystemFreeReader`). */ freeMemory?: () => number; + /** + * A runtime-native memory-available-to-new-work reader (bytes), tried before every other free-memory source. Default: + * Electron's `process.getSystemMemoryInfo()` when the `process` object has it, else `Deno.systemMemoryInfo()` + * on macOS (feature-detected; absent on plain Node/Bun). + */ + nativeAvailableMemory?: () => number | undefined; + /** `process.platform` for the free-memory source choice. Default the real one. */ + platform?: string; /** perf_hooks primitives for the event-loop metrics (partial on Bun/Deno). Default node:perf_hooks. */ perfHooks?: PerfHooks; /** Test seam for the GC observer constructor. Default `node:perf_hooks`. */ @@ -146,11 +159,11 @@ export interface ProcessEnv { */ measuresV8Heap?: boolean; /** - * Is `os.freemem()` known to be memory AVAILABLE to new work (libuv MemAvailable / ullAvailPhys)? Default `true` - * (Node). Bun and Deno pass `false`: they read `/proc/meminfo` MemAvailable first on Linux, then `os.freemem()`. - * `process.availableMemory()` is never used (not comparable on Bun/Deno; lower than truth in a cgroup on Node). + * Read `/proc/meminfo` MemAvailable before `os.freemem()` on Linux? Default `false`. Only `@bugsee/bun` sets it + * (Bun < 1.3.13's `os.freemem()` is not MemAvailable). Deno must NOT: its `os.freemem()` already is, and the extra + * read triggers an interactive permission prompt under a scoped `--allow-read`. */ - measuresAvailableMemory?: boolean; + readsProcMeminfo?: boolean; /** Does `PerformanceObserver({entryTypes:['gc']})` see collections? Default `true`; blind on Bun/Deno. */ measuresGc?: boolean; /** Drives the shared sampling timer; default the global timers, unref'd so the tracker never holds a process alive. */ @@ -184,11 +197,13 @@ const SEAM_KEYS = [ 'memoryLimit', 'meminfo', 'freeMemory', + 'nativeAvailableMemory', + 'platform', 'perfHooks', 'performanceObserver', 'measuresEventLoopDelay', 'measuresV8Heap', - 'measuresAvailableMemory', + 'readsProcMeminfo', 'measuresGc', 'scheduler', 'intervalMs', @@ -398,6 +413,7 @@ export class ProcessTracker extends InterceptorBase { const perf = env.perfHooks ?? realPerfHooks; // `??` / explicit gates (never a spread over defaults): an injected source wins; otherwise the default is wired // only where the runtime can give a true value, and an unwired source means the stage is ABSENT. + const platform = env.platform ?? nodeProcess.platform; const resolved: Resolved = { eventLoop: env.eventLoop ?? @@ -411,8 +427,16 @@ export class ProcessTracker extends InterceptorBase { (env.measuresV8Heap !== false ? createV8HeapReader(getHeapStatistics) : undefined), memoryLimit: env.memoryLimit ?? createMemoryLimitReader(nodeProcess, totalmem), systemFree: createSystemFreeReader({ - preferMeminfo: env.measuresAvailableMemory === false, - meminfo: env.meminfo ?? createProcMeminfoReader(nodeProcess.platform, readProcFile), + platform, + native: + env.nativeAvailableMemory ?? + firstAnswer([ + createElectronMemoryReader(nodeProcess as ElectronMemoryInfoLike, platform), + createDenoMemoryReader((globalThis as { Deno?: DenoMemoryInfoLike }).Deno, platform), + ]), + ...(env.readsProcMeminfo === true + ? { meminfo: env.meminfo ?? createProcMeminfoReader(platform, readProcFile) } + : {}), freemem: env.freeMemory ?? freemem, total: totalmem, }), diff --git a/packages/trackers/src/node/runtime-readers.test.ts b/packages/trackers/src/node/runtime-readers.test.ts index 958af31b8..73911760f 100644 --- a/packages/trackers/src/node/runtime-readers.test.ts +++ b/packages/trackers/src/node/runtime-readers.test.ts @@ -1,9 +1,12 @@ import { describe, expect, it } from 'vitest'; import { + createDenoMemoryReader, + createElectronMemoryReader, createMemoryLimitReader, createProcMeminfoReader, createSystemFreeReader, createV8HeapReader, + firstAnswer, parseMemAvailable, } from './runtime-readers'; @@ -133,11 +136,10 @@ describe('createProcMeminfoReader', () => { }); describe('createSystemFreeReader', () => { - const meminfo = 'MemAvailable: 10 kB\n'; // 10240 bytes + const meminfo = () => 'MemAvailable: 10 kB\n'; // 10240 bytes const make = (over: Partial[0]> = {}) => createSystemFreeReader({ - preferMeminfo: false, - meminfo: () => meminfo, + platform: 'linux', freemem: () => 111, total: () => 1_000_000, ...over, @@ -146,29 +148,32 @@ describe('createSystemFreeReader', () => { throw new Error('boom'); }; - it('Node: os.freemem() alone, /proc/meminfo is never read', () => { - let reads = 0; - expect(make({ meminfo: () => (reads++, meminfo) })()).toBe(111); - expect(reads).toBe(0); + it('default: os.freemem() alone', () => { + expect(make()()).toBe(111); + expect(make({ platform: 'win32' })()).toBe(111); }); - it('preferMeminfo (Bun/Deno): MemAvailable first, then os.freemem()', () => { - expect(make({ preferMeminfo: true })()).toBe(10240); - expect(make({ preferMeminfo: true, meminfo: () => undefined })()).toBe(111); - expect(make({ preferMeminfo: true, meminfo: () => 'nothing here' })()).toBe(111); - expect(make({ preferMeminfo: true, meminfo: boom })()).toBe(111); + it('order: native, then meminfo (when supplied), then os.freemem()', () => { + expect(make({ native: () => 5, meminfo })()).toBe(5); + expect(make({ native: () => undefined, meminfo })()).toBe(10240); + expect(make({ meminfo })()).toBe(10240); + expect(make({ meminfo: () => undefined })()).toBe(111); + expect(make({ meminfo: () => 'nothing here' })()).toBe(111); + expect(make({ meminfo: boom, native: boom })()).toBe(111); + }); + + it('macOS: os.freemem() is never a source (free pages only), native and meminfo still are', () => { + expect(make({ platform: 'darwin' })()).toBeUndefined(); + expect(make({ platform: 'darwin', native: () => 7 })()).toBe(7); + expect(make({ platform: 'darwin', meminfo })()).toBe(10240); }); it('skips a source that answers an implausible value (NaN, Infinity, negative, > total)', () => { for (const bad of [Number.NaN, Number.POSITIVE_INFINITY, -1, 1_000_001]) { expect(make({ freemem: () => bad })()).toBeUndefined(); - expect( - make({ preferMeminfo: true, freemem: () => bad, meminfo: () => undefined })(), - ).toBeUndefined(); + expect(make({ native: () => bad, freemem: () => 111 })()).toBe(111); } - expect(make({ preferMeminfo: true, meminfo: () => 'MemAvailable: 999999999 kB\n' })()).toBe( - 111, - ); + expect(make({ meminfo: () => 'MemAvailable: 999999999 kB\n' })()).toBe(111); expect(make({ freemem: boom })()).toBeUndefined(); }); @@ -186,3 +191,63 @@ describe('createSystemFreeReader', () => { expect(read()).toBeUndefined(); }); }); + +describe('createElectronMemoryReader (KiB -> bytes)', () => { + const read = (platform: string, info: object | undefined) => + createElectronMemoryReader( + info === undefined ? {} : { getSystemMemoryInfo: () => info }, + platform, + )(); + + it('macOS: free + fileBacked + purgeable', () => { + expect(read('darwin', { free: 1, fileBacked: 10, purgeable: 100, available: 9999 })).toBe( + 111 * 1024, + ); + expect(read('darwin', { free: 1, fileBacked: 10 })).toBeUndefined(); + expect(read('darwin', { free: 1, fileBacked: 'x', purgeable: 3 })).toBeUndefined(); + }); + + it('Linux: available (not free). Windows: free', () => { + expect(read('linux', { free: 1, available: 7 })).toBe(7 * 1024); + expect(read('linux', { free: 1 })).toBeUndefined(); + expect(read('win32', { free: 5, available: 9 })).toBe(5 * 1024); + expect(read('win32', { available: 9 })).toBeUndefined(); + }); + + it('is undefined on another platform, without the API, or for non-finite/negative values', () => { + expect(read('freebsd', { free: 1, available: 1 })).toBeUndefined(); + expect(read('linux', undefined)).toBeUndefined(); + for (const bad of [Number.NaN, Number.POSITIVE_INFINITY, -1]) { + expect(read('linux', { available: bad })).toBeUndefined(); + } + }); +}); + +describe('createDenoMemoryReader (bytes)', () => { + const deno = { systemMemoryInfo: () => ({ available: 4096 }) }; + it('reports available on macOS only', () => { + expect(createDenoMemoryReader(deno, 'darwin')()).toBe(4096); + expect(createDenoMemoryReader(deno, 'linux')()).toBeUndefined(); + expect(createDenoMemoryReader(deno, 'win32')()).toBeUndefined(); + }); + it('is undefined without Deno/the API or for implausible values', () => { + expect(createDenoMemoryReader(undefined, 'darwin')()).toBeUndefined(); + expect(createDenoMemoryReader({}, 'darwin')()).toBeUndefined(); + for (const bad of [Number.NaN, -1, '5']) { + expect( + createDenoMemoryReader({ systemMemoryInfo: () => ({ available: bad }) }, 'darwin')(), + ).toBeUndefined(); + } + }); +}); + +describe('firstAnswer', () => { + it('returns the first defined answer, skipping undefined and throwing readers', () => { + const boom = () => { + throw new Error('x'); + }; + expect(firstAnswer([() => undefined, boom, () => 0, () => 5])()).toBe(0); + expect(firstAnswer([boom, () => undefined])()).toBeUndefined(); + expect(firstAnswer([])()).toBeUndefined(); + }); +}); diff --git a/packages/trackers/src/node/runtime-readers.ts b/packages/trackers/src/node/runtime-readers.ts index 302cf5fff..155867b85 100644 --- a/packages/trackers/src/node/runtime-readers.ts +++ b/packages/trackers/src/node/runtime-readers.ts @@ -91,43 +91,125 @@ export function createProcMeminfoReader( }; } +/** The slice of Electron's `process.getSystemMemoryInfo()` we read. Sizes are KILOBYTES (KiB). */ +export interface ElectronMemoryInfoLike { + getSystemMemoryInfo?: () => { + free?: unknown; + fileBacked?: unknown; + purgeable?: unknown; + available?: unknown; + }; +} + +const KIB = 1024; + +/** + * Memory available to new work from Electron's `process.getSystemMemoryInfo()` (KiB -> bytes), per platform: + * - macOS: `free + fileBacked + purgeable` (free pages plus memory the OS can take back without paging out: the + * closest native analogue of Android's `availMem`; Electron's `free` alone is only never-used pages); + * - Linux: `available` (the kernel's MemAvailable); + * - Windows: `free` (Electron fills it from `avail_phys`, standby cache included). + * Undefined on any other platform, when the API is absent, or when a needed field is not a finite non-negative number. + * The caller still bounds the result by total RAM. + */ +export function createElectronMemoryReader( + proc: ElectronMemoryInfoLike, + platform: string, +): () => number | undefined { + return () => { + if (typeof proc.getSystemMemoryInfo !== 'function') return undefined; + const info = proc.getSystemMemoryInfo(); + let kib: number | undefined; + if (platform === 'darwin') { + const { free, fileBacked, purgeable } = info; + kib = + isCount(free) && isCount(fileBacked) && isCount(purgeable) + ? free + fileBacked + purgeable + : undefined; + } else if (platform === 'linux') { + kib = isCount(info.available) ? info.available : undefined; + } else if (platform === 'win32') { + kib = isCount(info.free) ? info.free : undefined; + } + return kib === undefined || kib < 0 ? undefined : kib * KIB; + }; +} + +/** The slice of Deno's namespace we read. `systemMemoryInfo()` reports BYTES. */ +export interface DenoMemoryInfoLike { + systemMemoryInfo?: () => { available?: unknown }; +} + +/** + * `Deno.systemMemoryInfo().available`, on macOS ONLY (free + inactive pages: the quantity `os.freemem()` lacks there). + * On Linux and Windows Deno's `os.freemem()` is already the available figure, so this source is not consulted. + */ +export function createDenoMemoryReader( + deno: DenoMemoryInfoLike | undefined, + platform: string, +): () => number | undefined { + return () => { + if (platform !== 'darwin' || typeof deno?.systemMemoryInfo !== 'function') return undefined; + const value = deno.systemMemoryInfo().available; + return isCount(value) && value >= 0 ? value : undefined; + }; +} + +/** The first of several optional readers that answers; a reader that throws is skipped. */ +export function firstAnswer( + readers: readonly (() => number | undefined)[], +): () => number | undefined { + return () => { + for (const read of readers) { + try { + const value = read(); + if (value !== undefined) return value; + } catch { + // an unusable runtime API is the same as no answer + } + } + return undefined; + }; +} + export interface SystemFreeSources { - /** - * Prefer `/proc/meminfo` MemAvailable over `os.freemem()`? Only for runtimes whose `os.freemem()` is not known to - * be MemAvailable-equivalent (Bun < 1.3.13 on Linux). - */ - preferMeminfo: boolean; - /** Raw `/proc/meminfo` text (Linux), or undefined. */ - meminfo: () => string | undefined; - /** `os.freemem()`, the primary source on Node: see {@link createSystemFreeReader}. */ + /** `process.platform`. On `darwin` `os.freemem()` is NOT a source (see {@link createSystemFreeReader}). */ + platform: string; + /** A runtime-native "available to new work" figure in BYTES (Electron, Deno on macOS), tried first. */ + native?: () => number | undefined; + /** Raw `/proc/meminfo` text, only supplied for a runtime whose `os.freemem()` is not MemAvailable (Bun < 1.3.13). */ + meminfo?: () => string | undefined; + /** `os.freemem()`. */ freemem: () => number; total: () => number; } /** - * `ram_system_free`: memory available to new work, as Android reports it (not merely "free" pages). - * - * Node: `os.freemem()`. It already is that quantity where the OS can say it: libuv reads `MemAvailable` on Linux - * since 1.43 (Node >= 16.14) and uses `ullAvailPhys` (standby cache included) on Windows. `process.availableMemory()` - * is deliberately NOT used: it equals `os.freemem()` without a cgroup limit (measured identical on macOS), and - * inside a cgroup it counts page cache as used, so it reads LOWER than what is truly available. - * Known limit: on macOS `os.freemem()` counts only free pages, so it undercounts reclaimable memory. - * - * Bun/Deno (`preferMeminfo`): `MemAvailable` from `/proc/meminfo` first (Linux), then `os.freemem()`. Their - * `process.availableMemory()` is not comparable (Deno: 0 on Windows, includes inactive pages on macOS), so it is - * never consulted. - * - * A source that throws or answers an implausible value (non-finite, negative, > total) is skipped; when none - * answers, undefined, so the trace is omitted rather than invented. + * `ram_system_free`: memory available to new work, as Android reports it (`availMem`), never merely free pages. + * Sources in order, first plausible value (finite, >= 0, <= total) wins: + * 1. `native`: Electron `process.getSystemMemoryInfo()`; Deno `systemMemoryInfo().available` on macOS. + * 2. `meminfo`: `MemAvailable` from `/proc/meminfo` (Bun only). + * 3. `os.freemem()`, except on macOS. libuv reads `MemAvailable` on Linux (since 1.43, Node >= 16.14; Deno since + * 2023) and `ullAvailPhys` on Windows. On macOS it is only free pages (about 0.2% of RAM on a busy 64 GB Mac + * while the OS reports about half available), and Node/Bun have no native available figure, so on macOS Node + * and Bun OMIT the trace rather than report a number that is not the mobile quantity. (A rare async + * `sysctl`/`vm_stat` read or `bun:ffi` could fill that gap later.) + * `process.availableMemory()` is never used: it equals `os.freemem()` without a cgroup limit, reads lower inside one, + * is 0 on Windows Deno and includes inactive pages on macOS Deno. Inside a container the value is the HOST's + * figure; the cgroup cap is carried by `process_memory_limit`. + * A source that throws or answers an implausible value is skipped; none answering means undefined (omitted). */ export function createSystemFreeReader(src: SystemFreeSources): () => number | undefined { - const meminfo = (): number | undefined => { - const text = src.meminfo(); - return text === undefined ? undefined : parseMemAvailable(text); - }; - const sources: (() => number | undefined)[] = src.preferMeminfo - ? [meminfo, src.freemem] - : [src.freemem]; + const sources: (() => number | undefined)[] = []; + if (src.native !== undefined) sources.push(src.native); + const { meminfo } = src; + if (meminfo !== undefined) { + sources.push(() => { + const text = meminfo(); + return text === undefined ? undefined : parseMemAvailable(text); + }); + } + if (src.platform !== 'darwin') sources.push(src.freemem); return () => { const total = src.total(); for (const source of sources) { From 761590815b10232740bb8e5755d2c059778e3a83 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 21 Oct 2026 21:14:57 +0500 Subject: [PATCH 3/3] docs(trackers): cite Electron 44.9.3 SystemMemoryInfo typings and the live macOS run MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit πŸ€– Generated with [Claude Code](https://claude.com/claude-code) --- docs/PROGRESS.md | 2 +- packages/trackers/src/node/runtime-readers.ts | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 105b287b8..430185d9d 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -64,7 +64,7 @@ Read this first; then `docs/design/sdk-design.md` (Draft v3) for the full archit - `buildNodeEnvironment(input, probe)` β€” Β§8.6 envelope via injectable `SystemProbe`. Applies `optionsToWire` to `sdk.options` (dots β†’ colons; server treats dots as nested-document paths). - `createUncaughtExceptionProvider` / `createUnhandledRejectionProvider` β€” process-event detection, V8 stack parsed + scrubbed. - `createNodeHttpInterceptor` β€” wraps `node:http(s)` `request` + `get` (mechanism `'http'`), captures axios/got/node-fetch that bypass global fetch. **Transparent error handling**: re-raises the original error when it is the sole `'error'` listener so an otherwise-uncaught request error still crashes the app. -- `createNodeSystemTraceProducers` (the only built-in node trace source; the legacy `createNodeSystemMetricsSampler` / `createGuardedSystemMetricsSampler` were deleted in ST0β€²-D, `systemMetricsSampler` remains as a caller-supplied override) β€” process memory (rss/heapTotal/heapUsed/external/**arrayBuffers**), **system memory (`ram_system_total`/`ram_system_free` β€” Android parity; C6: `free` is memory AVAILABLE to new work, bytes like `ram_system_total` (Android `availMem`). Sources in order: a runtime-native figure (Electron `process.getSystemMemoryInfo()` in KiB: macOS free+fileBacked+purgeable, Linux `available`, Windows `free`; Deno `systemMemoryInfo().available` on macOS only), `/proc/meminfo` MemAvailable (Bun only, `readsProcMeminfo`; Deno must not: a scoped `--allow-read` makes it an interactive prompt), then `os.freemem()` (libuv MemAvailable on Linux, ullAvailPhys on Windows; NOT a source on macOS). Node and Bun on macOS therefore OMIT the trace (os.freemem there is free pages only: 0.2% of RAM on a busy 64 GB Mac while the OS reports ~half available); a rare async sysctl/vm_stat read or bun:ffi could fill it later (owner may veto the omission). Omitted whenever no source gives a finite, non-negative value <= total. Inside a container it is the HOST's figure; the cap is `process_memory_limit`. `platform.memory_free` in the environment envelope still uses `os.freemem()` (FOLLOW-UP: route it through the same source function and omit it on macOS Node/Bun))**, CPU user/system per-sample deltas + **normalized `cpu_usage_process` %** (over wall-time/cores), event-loop lag **mean/max/p99** + **utilization** (perf_hooks `monitorEventLoopDelay` + `eventLoopUtilization`). All readers injectable. **ST1 added** (measured on real node/bun/deno + a Linux cgroup container, 2026-10-17): `v8_heap_{size_limit,available,malloced,peak_malloced}` + ceiling-based `ram_js_heap_{total,used,free}` (Node/Deno; `measuresV8Heap:false` on Bun), `process_memory_limit` (only a real cap: `0`, the 2^64 sentinel and `>= totalmem` β€” which Bun answers when unconstrained β€” are omitted), `process_uptime_s`, `ram_system_available` (RETIRED by C6: `process.availableMemory()` equals `os.freemem()` without a cgroup limit, reads lower inside one, and is not comparable on Bun/Deno: under `docker -m 256m` they answered ~11 GB vs Node's 253 MB). Linux probes: Bun's unconstrained `constrainedMemory()` equals `totalmem` exactly, Deno's is `0`, both report a real cap under `-m`. **ST2 added:** `gc_count` / `gc_pause_ms` / `gc_pause_max_ms` per interval from a lazy `PerformanceObserver({entryTypes:['gc']})` (`trackers/gc-observer.ts`, started/stopped by the tracker with the other sources); a quiet interval is a true zero. The observer is BLIND on Bun and Deno (measured), so both launches pass `measuresGc:false` and never construct it. **ST3 added:** opt-in `captureDiskSpace` β†’ `disk_mem_free`/`disk_mem_total` (integer binary MB via `bytesToMegabytes`) for the volume of the launch's `effectiveDataDir` (`disk-space-producer.ts`, async `fs.promises.statfs` every 5 s, polled and NOT held so a failing statfs leaves a gap, generation-guarded against stale reads, one `onError` per failure streak). Appended by `nodeLaunchCore` (also to caller-supplied/Bun/Deno producer lists); absent with no data dir, never `/` or cwd. +- `createNodeSystemTraceProducers` (the only built-in node trace source; the legacy `createNodeSystemMetricsSampler` / `createGuardedSystemMetricsSampler` were deleted in ST0β€²-D, `systemMetricsSampler` remains as a caller-supplied override) β€” process memory (rss/heapTotal/heapUsed/external/**arrayBuffers**), **system memory (`ram_system_total`/`ram_system_free` β€” Android parity; C6: `free` is memory AVAILABLE to new work, bytes like `ram_system_total` (Android `availMem`). Sources in order: a runtime-native figure (Electron `process.getSystemMemoryInfo()` in KiB: macOS free+fileBacked+purgeable, Linux `available`, Windows `free` (field semantics from the Electron 44.9.3 typings' `SystemMemoryInfo` platform tags; verified live on macOS only: {free 1236912, fileBacked 10428768, purgeable 388784} KB = ~11.5 GB vs 1.2 GB free; Linux/Windows from typings only); Deno `systemMemoryInfo().available` on macOS only), `/proc/meminfo` MemAvailable (Bun only, `readsProcMeminfo`; Deno must not: a scoped `--allow-read` makes it an interactive prompt), then `os.freemem()` (libuv MemAvailable on Linux, ullAvailPhys on Windows; NOT a source on macOS). Node and Bun on macOS therefore OMIT the trace (os.freemem there is free pages only: 0.2% of RAM on a busy 64 GB Mac while the OS reports ~half available); a rare async sysctl/vm_stat read or bun:ffi could fill it later (owner may veto the omission). Omitted whenever no source gives a finite, non-negative value <= total. Inside a container it is the HOST's figure; the cap is `process_memory_limit`. `platform.memory_free` in the environment envelope still uses `os.freemem()` (FOLLOW-UP: route it through the same source function and omit it on macOS Node/Bun))**, CPU user/system per-sample deltas + **normalized `cpu_usage_process` %** (over wall-time/cores), event-loop lag **mean/max/p99** + **utilization** (perf_hooks `monitorEventLoopDelay` + `eventLoopUtilization`). All readers injectable. **ST1 added** (measured on real node/bun/deno + a Linux cgroup container, 2026-10-17): `v8_heap_{size_limit,available,malloced,peak_malloced}` + ceiling-based `ram_js_heap_{total,used,free}` (Node/Deno; `measuresV8Heap:false` on Bun), `process_memory_limit` (only a real cap: `0`, the 2^64 sentinel and `>= totalmem` β€” which Bun answers when unconstrained β€” are omitted), `process_uptime_s`, `ram_system_available` (RETIRED by C6: `process.availableMemory()` equals `os.freemem()` without a cgroup limit, reads lower inside one, and is not comparable on Bun/Deno: under `docker -m 256m` they answered ~11 GB vs Node's 253 MB). Linux probes: Bun's unconstrained `constrainedMemory()` equals `totalmem` exactly, Deno's is `0`, both report a real cap under `-m`. **ST2 added:** `gc_count` / `gc_pause_ms` / `gc_pause_max_ms` per interval from a lazy `PerformanceObserver({entryTypes:['gc']})` (`trackers/gc-observer.ts`, started/stopped by the tracker with the other sources); a quiet interval is a true zero. The observer is BLIND on Bun and Deno (measured), so both launches pass `measuresGc:false` and never construct it. **ST3 added:** opt-in `captureDiskSpace` β†’ `disk_mem_free`/`disk_mem_total` (integer binary MB via `bytesToMegabytes`) for the volume of the launch's `effectiveDataDir` (`disk-space-producer.ts`, async `fs.promises.statfs` every 5 s, polled and NOT held so a failing statfs leaves a gap, generation-guarded against stale reads, one `onError` per failure streak). Appended by `nodeLaunchCore` (also to caller-supplied/Bun/Deno producer lists); absent with no data dir, never `/` or cwd. - `createNodeSystemEventsSource` β€” process lifecycle (`process_started` on activate, `process_exiting`, **`process_before_exit`** clean-drain, `process_warning`, and **`process_signal`** for SIGTERM/SIGINT). Signal capture is PASSIVE: it emits the event, and only when the SDK is the sole handler does it remove itself and **re-raise** (`process.kill`) to restore Node's default termination β€” so it never hangs a process or hijacks an app's own signal handler. - **`launch(appToken, options)`** β€” the composition root: builds the transport (internal-tagged), api/uploader/upload pipeline, durable wrapper (when `dataDir`/`bundleStore` present), env builder, store (in-memory / file-backed), resolves the friendly options once via `NODE_OPTION_DEFINITIONS`, registers gated capture providers (consoleβ†’log; network umbrella with `node:http` folded in; system traces/events) + detection providers, calls `client.launch()`, runs durable `recover()` on start, installs the uncaughtException β†’ `flush(timeout)` β†’ `proc.exit(1)` policy (opt-out `exitOnUncaught`, default `shutdownTimeoutMs: 3000`), and augments `client.stop()` to remove its process listener. Returns the started `BugseeClient`. diff --git a/packages/trackers/src/node/runtime-readers.ts b/packages/trackers/src/node/runtime-readers.ts index 155867b85..102459cf4 100644 --- a/packages/trackers/src/node/runtime-readers.ts +++ b/packages/trackers/src/node/runtime-readers.ts @@ -109,6 +109,10 @@ const KIB = 1024; * closest native analogue of Android's `availMem`; Electron's `free` alone is only never-used pages); * - Linux: `available` (the kernel's MemAvailable); * - Windows: `free` (Electron fills it from `avail_phys`, standby cache included). + * Field semantics are from Electron 44.9.3's `SystemMemoryInfo` typings (platform tags: `fileBacked` and `purgeable` + * are macOS, `available` is Linux, `free` on Windows is avail_phys). Verified live on macOS only: a real run gave + * {total: 67108864, free: 1236912, fileBacked: 10428768, purgeable: 388784} KB, i.e. about 11.5 GB by this formula + * against 1.2 GB for `free` alone. Linux and Windows semantics are from the typings, not a live run. * Undefined on any other platform, when the API is absent, or when a needed field is not a finite non-negative number. * The caller still bounds the result by total RAM. */