@zakkster/lite-signal 1.3.0-rc.0 → 1.5.0-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,7 +4,210 @@ All notable changes to `@zakkster/lite-signal` are documented here.
4
4
  Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
  This project follows [Semantic Versioning](https://semver.org/).
6
6
 
7
- ## [1.3.0] -- 2026-06-XX
7
+ ## [1.5.0] -- 2026-06-XX
8
+
9
+ The API-surface minor: two new **non-callable, allocation-light** reactive
10
+ primitives, `signalBox` and `computedBox`, land alongside the existing callable
11
+ `signal` / `computed`; and **`createRoot`** lands as the ownership escape hatch
12
+ the owner tree was designed for. They wrap the same `ReactiveNode` machinery and
13
+ interoperate freely in one graph -- a box can depend on a callable and vice
14
+ versa -- so this is an additive surface, not a second engine. Drop-in over 1.4.0:
15
+ the callable API, hot paths, and `stats()` shape are unchanged; the boxes are new
16
+ exports and the `24-signalbox` suite (staged `{skip:true}` since 1.3.0) now runs
17
+ and passes. The 1.3.0 eager pool default carries forward (`prealloc: "eager"`).
18
+
19
+ ### Added -- `signalBox(initial, opts?)` and `computedBox(fn, opts?)`
20
+
21
+ Non-callable variants that return a plain object on a shared prototype instead of
22
+ a callable function:
23
+
24
+ - **`signalBox`** returns `{ get, set, peek, update, subscribe }`.
25
+ - **`computedBox`** returns `{ get, peek, subscribe }` (no `set` / `update` --
26
+ it is derived).
27
+
28
+ Both are exported as registry methods *and* as top-level helpers bound to the
29
+ default registry, mirroring `signal` / `computed`. The `opts.equals` custom
30
+ equality option is supported on both, same default (`Object.is`).
31
+
32
+ **Why a second shape.** The callable API (`count()`, `count.set(x)`) is the most
33
+ ergonomic surface, but constructing a callable means building a function object
34
+ and hanging methods/state off it. For code that creates *many* short-lived
35
+ reactive cells, or that wants a plain serializable-looking handle, the box trades
36
+ call ergonomics for cheaper construction:
37
+
38
+ - **Box creation is faster than callable** -- on this host, 10,000 `signalBox`
39
+ in ~10ms vs ~18ms for 10,000 callable `signal` (about 1.7x cheaper),
40
+ because `Object.create(proto)` is cheaper than allocating a closure with
41
+ attached properties.
42
+ - **The hot read/write path stays zero-GC** -- 200,000 box writes through a
43
+ 256-wide graph allocate nothing and grow the pool zero times. The box is a
44
+ thin handle over the same pooled node; only the *handle object* differs from
45
+ the callable, and it is created once.
46
+
47
+ ### Engineering note -- monomorphic boxes via `Object.create`, not `setPrototypeOf`
48
+
49
+ Each box is built with `Object.create(SIGNAL_BOX_PROTO)` (resp.
50
+ `COMPUTED_BOX_PROTO`) and then has its two own properties (`NODE_PTR`,
51
+ `NODE_GEN`) added in a fixed order. This is deliberate: using `setPrototypeOf`
52
+ on an already-constructed object transitions it to dictionary mode and forces the
53
+ method-call inline caches at `box.get()` / `box.set()` to megamorphic. Building on
54
+ the shared prototype from the start keeps every box monomorphic, so the method
55
+ calls stay inline-cached and fast. This is the same class of V8-closure-tax
56
+ avoidance the engine applies throughout; a rejected earlier prototype that used
57
+ `setPrototypeOf` regressed box method calls and was not shipped.
58
+
59
+ ### Interop -- one graph, two handle shapes
60
+
61
+ A box and a callable handle wrap the same kind of `ReactiveNode`. Verified both
62
+ directions: a callable `computed` that reads `box.get()` tracks the box as a
63
+ dependency and updates correctly; a `computedBox` that reads a callable
64
+ `signal()` does the same. Glitch-freedom, batching, ownership/auto-disposal, and
65
+ the introspection surface all apply uniformly -- a box node is indistinguishable
66
+ from a callable node to the graph, the owner tree, and devtools.
67
+
68
+ ### Added -- `test/24-signalbox_test.mjs` activated (9 tests)
69
+
70
+ The suite that was committed-but-skipped since 1.3.0 now runs against the real
71
+ implementation: box get/set/peek/update, computedBox derive + memoize,
72
+ peek-does-not-track, subscribe fires-and-untracks, box<->callable interop both
73
+ directions, batch coalescing across boxes, dispose stopping updates with
74
+ ABA-safety, and the `equals` short-circuit. All 9 pass.
75
+
76
+ ### Added -- `createRoot(fn)` (ownership escape hatch)
77
+
78
+ `createRoot` runs `fn` in a **detached ownership scope**: effects and computeds
79
+ created inside `fn` are not adopted by the enclosing owner, so they survive the
80
+ enclosing effect's re-runs and disposal. The caller owns their lifecycle (there
81
+ is no parent to auto-dispose them -- `fn` typically returns a disposer or the
82
+ created handle). Exported as a registry method and a top-level helper, mirroring
83
+ `signal` / `computed` / `untrack`.
84
+
85
+ **Why it exists.** The owner tree's defining behavior is that owned children
86
+ dispose with their parent -- correct and intended (pinned by the cleanup-ordering
87
+ tests since 1.2.0). But that makes one pattern a footgun: lazily spawning a
88
+ *long-lived* node from *inside* a consumer effect. The spawned node is adopted by
89
+ the consumer, so the consumer's next re-run cascade-disposes it. This is not an
90
+ engine defect -- it is the ownership model working as designed -- but until now
91
+ there was no sanctioned way to opt a child *out* of ownership. `createRoot` is
92
+ that opt-out. The engine head comment has named `runWithOwner` / `createRoot` as
93
+ the intended future API for exactly this since the owner/observer split shipped
94
+ in 1.2.0 (`currentOwner` and `currentObserver` were made distinct pointers
95
+ precisely so ownership could be detached without affecting tracking); 1.5.0
96
+ delivers the first of the two.
97
+
98
+ **What it detaches.** For the duration of `fn`, both `currentOwner` and
99
+ `currentObserver` (and the tracking flag) are nulled, so neither ownership nor a
100
+ reactive dependency leaks from `fn`'s direct body into the enclosing scope. Inner
101
+ effect / computed bodies still establish their own owner+observer scopes as
102
+ usual -- only the boundary at `fn` is detached. Mirrors Solid's `createRoot` on
103
+ the lifecycle axis.
104
+
105
+ **Who needs it.** Any consumer that lazily creates a watcher/subscription inside
106
+ a reactive scope and expects it to outlive that scope -- `lite-query`'s
107
+ query-watcher being the first in the ecosystem. Those consumers wrap the spawn in
108
+ `createRoot(() => effect(...))` and dispose it themselves; the watcher then
109
+ survives consumer re-runs.
110
+
111
+
112
+ - **Full suite green** against the 1.5.0 engine: 439 tests, 438 pass, 0 fail,
113
+ 1 skip (only the architecturally-N/A SSR case in `17-reactivity`; the 9
114
+ `24-signalbox` tests are now active, +6 `createRoot` tests in
115
+ `test/27-create-root_test.mjs`, +3 box-coverage tests). **Coverage** (c8@11,
116
+ Node 22): `Signal.js` 100% statements / 97.35% branches / 100% functions / 100%
117
+ lines; `Watch.js` 100% across all four.
118
+ - **Box hot path is zero-GC**: 200,000 writes through a 256-wide box graph,
119
+ 0 heap growth, 0 pool growths after warm-up -- identical steady-state profile
120
+ to the callable API.
121
+ - **Box creation is allocation-light**: measurably cheaper construction than the
122
+ callable equivalent (~1.7x on this host), the design goal of the second shape.
123
+ - **Interop confirmed**: callable-reads-box and box-reads-callable both track and
124
+ update correctly in a single graph; `stats()` counts box nodes in `signals` /
125
+ `computeds` exactly as callable nodes.
126
+ - **`stats()` shape unchanged** from 1.4.0 (11 keys); boxes allocate nodes
127
+ through the same `createNode` path, so the 1.4.0 lifecycle counters
128
+ (`totalAllocations` etc.) account for box nodes automatically.
129
+ - **`createRoot` detaches ownership without leaking**: a watcher effect spawned
130
+ inside a consumer effect via `createRoot` survives the consumer's re-run (fires
131
+ on later dependency changes where, unwrapped, it would have been cascade-
132
+ disposed), and an explicit disposer on the detached effect still stops it
133
+ cleanly -- detachment costs no auto-cleanup but introduces no leak. Verified
134
+ against the exact lazy-watcher pattern `lite-query` uses.
135
+
136
+
137
+
138
+ The observability minor: `stats()` gains **three cumulative lifecycle counters**
139
+ (`totalAllocations`, `totalDisposals`, `poolGrowths`) -- the surface reserved for
140
+ 1.4.0 in the 1.2.x and 1.3.0 notes, now delivered. This is what lite-devtools /
141
+ lite-studio read to chart allocation rate, pool-reuse ratio, and graph churn over
142
+ time. Drop-in over 1.3.0 -- no hot-path change, no public callable API change; the
143
+ counters are bumped on existing lifecycle edges (acquire / dispose / grow) that
144
+ already ran, so steady-state throughput and zero-GC are unchanged. The eager pool
145
+ default introduced in 1.3.0 carries forward (`prealloc: "eager"`).
146
+
147
+ ### Added -- cumulative lifecycle counters on `stats()`
148
+
149
+ `stats()` now returns **11 keys**: the 8 from 1.2.x/1.3.0 plus three monotonic
150
+ counters. They are cumulative over the registry's life and reset only by
151
+ `destroy()`.
152
+
153
+ - **`totalAllocations`** -- incremented on every node acquire, whether the node
154
+ is popped from the free list or freshly constructed during a pool-growth chunk.
155
+ This is the true number of nodes the registry has ever handed out, not the
156
+ current live count (`activeNodes` remains the live gauge).
157
+ - **`totalDisposals`** -- incremented on every `disposeNode`, i.e. every node
158
+ returned to the pool. `totalAllocations - totalDisposals` tracks the live set
159
+ and should equal `activeNodes` in a quiescent registry.
160
+ - **`poolGrowths`** -- incremented whenever a node *or* link refill chunk pushes
161
+ capacity past its current ledger (`maxNodes` / `maxLinks`). A nonzero value
162
+ after warm-up means the initial pool was undersized for the workload and the
163
+ registry grew at runtime -- the signal a tool uses to recommend a larger
164
+ `maxNodes` / `maxLinks`, or that confirms an eager pool was sized correctly
165
+ (stays 0).
166
+
167
+ The counters are exact, not sampled: they sit on the same `createNode` /
168
+ `disposeNode` / chunk-refill edges the engine already executes, so reading them
169
+ costs nothing and they cannot drift from the real lifecycle.
170
+
171
+ ### Why these three, and what they enable
172
+
173
+ The point is *derivable* observability without the engine itself computing rates.
174
+ A consumer sampling `stats()` over time gets, with no extra engine work:
175
+
176
+ - **allocation rate** = delta `totalAllocations` / delta t (graph build pressure),
177
+ - **pool-reuse ratio** = `1 - poolGrowths * initialCapacity / totalAllocations`
178
+ (how much work the pool absorbed vs. how much forced growth),
179
+ - **approximate average lifetime** ~ `totalDisposals` / allocation rate (churn).
180
+
181
+ These are exactly the series lite-devtools 1.2 / lite-studio 1.2 plot. The engine
182
+ stays a measurement *source*, not a metrics framework -- consistent with the
183
+ zero-overhead-in-steady-state contract.
184
+
185
+ ### Changed -- `destroy()` resets the counters
186
+
187
+ `destroy()` (the in-place arena reset) now also zeroes the three counters along
188
+ with the rest of registry state, so a reused registry reports lifecycle numbers
189
+ for its current epoch only. Grown pool *capacity* is retained across `destroy()`
190
+ as before (the reset keeps the arena warm); only the cumulative counts reset.
191
+
192
+ ### Verified
193
+
194
+ - **Full suite green** against the 1.4.0 engine: 430 tests, 420 pass, 0 fail,
195
+ 10 skip (9 signalBox-staged-for-1.5.0 plus 1 architecturally-N/A SSR skip). The eager-default and the counter additions
196
+ changed no existing test outcome.
197
+ - **Counter correctness** confirmed directly: after building a signal ->
198
+ computed -> effect graph, `totalAllocations` equals the node count and
199
+ `totalDisposals` tracks effect/computed teardown; forcing a pool past its
200
+ ledger under `onCapacityExceeded: "grow"` increments `poolGrowths`; an
201
+ eager pool sized to cover its graph keeps `poolGrowths` at 0.
202
+ - **Zero-GC steady state holds**: the counters bump only on acquire / dispose /
203
+ grow, none of which occur on the steady-state write path after warm-up. Writing
204
+ through a built graph allocates nothing and moves no counter.
205
+ - **`stats()` shape** is now the authoritative 11-key 1.4.x shape; the
206
+ introspection-contract test is updated to expect the three counters present
207
+ (the 1.2.x/1.3.0 test pinned their *absence*; that pin is correctly inverted
208
+ for 1.4.0).
209
+
210
+
8
211
 
9
212
  The pool minor: the node and link pools become **growable and incrementally
10
213
  populated**, the propagation mark phase moves to an **intrusive linked-list
@@ -83,16 +286,9 @@ in 1.3.0.
83
286
  ### Verified
84
287
 
85
288
  - **Full suite green** against the 1.3.0 engine: 424 tests, 414 pass, 0 fail,
86
- 10 skip. The 10 skips are the 9 `{skip:true}` `signalBox` tests in
87
- `24-signalbox` (those primitives land in 1.5.0) plus 1 architecturally-N/A
88
- SSR case in `17-reactivity`. The eager-default flip changed no test outcome.
89
- Four new tests in `03-pool` cover the 1.3.0 paths: lazy on-demand construction
90
- reaching the same steady state as eager, a never-allocated lazy registry
91
- surviving `destroy()`, `"grow"` extending both pool ledgers, and the
92
- `maxLinks * 16` link ceiling.
93
- - **Coverage** (c8@11, Node 22): `Signal.js` 100% statements / 98.26% branches /
94
- 100% functions / 100% lines; `Watch.js` 100% across all four. The lazy-pool
95
- `destroy()` paths added in 1.3.0 are covered by the new `03-pool` tests.
289
+ 1 architecturally-N/A SSR skip (the `24-signalbox` suite is `{skip:true}` on
290
+ 1.3.x -- those primitives land in 1.5.0). The eager-default flip changed no
291
+ test outcome.
96
292
  - **Behavior-preservation difftest**: 20,000 direct + 10,000 batched writes
97
293
  against the published 1.1.5 reference, 0 disagreements. Pool growth, chunked
98
294
  refill, and the intrusive mark stack do not alter observable propagation.
package/README.md CHANGED
@@ -241,7 +241,9 @@ Computeds are **pull-based** -- they're not in the effect queue. Reading a compu
241
241
  import {
242
242
  // Core
243
243
  signal, computed, effect,
244
+ signalBox, computedBox, // 1.5.0 -- allocation-light, non-callable
244
245
  batch, untrack, onCleanup, isTracking,
246
+ createRoot, // 1.5.0 -- detached ownership scope
245
247
  // Registry / lifecycle
246
248
  createRegistry, setDefaultRegistry, dispose, destroy,
247
249
  stats, CapacityError,
@@ -286,6 +288,26 @@ const off = c.subscribe(value => { ... });
286
288
 
287
289
  Computeds **cache by version**, not by value. Reading a clean computed (one whose dependencies haven't changed since its `evalVersion`) is `O(deps)` -- it still walks the dep list to check versions, then returns the cached value. The `equals` option short-circuits downstream propagation when the new computed value matches the old.
288
290
 
291
+ ### SignalBox / ComputedBox (1.5.0)
292
+
293
+ Non-callable, allocation-light variants of `signal` / `computed`. Instead of a callable function they return a plain object on a shared prototype:
294
+
295
+ ```ts
296
+ const s = signalBox(initial, { equals?: (a, b) => boolean });
297
+ s.get(); // tracked read (vs callable s())
298
+ s.set(value); // notify downstream
299
+ s.peek(); // untracked read
300
+ s.update(fn); // s.set(fn(currentValue))
301
+ const off = s.subscribe(value => { ... });
302
+
303
+ const c = computedBox(() => s.get() * 2, { equals? });
304
+ c.get(); // tracked read, lazy
305
+ c.peek(); // untracked read
306
+ c.subscribe(value => { ... }); // no set / update -- it's derived
307
+ ```
308
+
309
+ Same `ReactiveNode` machinery, same zero-GC read/write path, fully interoperable with callable handles in one graph (a callable `computed` can read `box.get()` and vice versa; ownership, batching, glitch-freedom, and introspection all apply uniformly). The trade is **call ergonomics for cheaper construction**: a box is `Object.create(proto)` plus two own properties rather than a closure with attached methods, so creating many short-lived cells is ~1.7x cheaper. Boxes are built on the shared prototype from the start (never `setPrototypeOf`, which would deopt the method-call inline caches to megamorphic). Reach for a box when you create *many* reactive cells or want a plain serializable-looking handle; reach for the callable when call-site ergonomics matter more.
310
+
289
311
  ### Effect
290
312
 
291
313
  ```ts
@@ -321,6 +343,21 @@ const value = untrack(() => s()); // read without subscribing
321
343
 
322
344
  Useful inside computeds/effects when you need a current value but don't want it as a dependency.
323
345
 
346
+ ### createRoot (1.5.0)
347
+
348
+ ```ts
349
+ const dispose = createRoot(() => {
350
+ // effects/computeds created here are NOT owned by the enclosing scope
351
+ return effect(() => { /* long-lived watcher */ });
352
+ });
353
+ // ... later, the caller owns the lifecycle:
354
+ dispose();
355
+ ```
356
+
357
+ Runs `fn` in a **detached ownership scope** and returns whatever `fn` returns. Effects and computeds created directly inside `fn` are not adopted by the enclosing owner, so they survive the enclosing effect's re-runs and disposal -- there is no parent to auto-dispose them, so the caller is responsible (typically `fn` returns a disposer or the created handle). Both ownership *and* tracking are detached for the duration of `fn`'s direct body; inner effect/computed bodies still establish their own scopes as usual. Mirrors Solid's `createRoot` on the lifecycle axis.
358
+
359
+ The problem it solves: lazily spawning a *long-lived* node from *inside* a consumer effect is otherwise a footgun -- the spawned node is adopted by the consumer, so the consumer's next re-run cascade-disposes it. That is the ownership model working as designed (owned children dispose with their parent); `createRoot` is the sanctioned opt-out. Any consumer that creates a watcher/subscription inside a reactive scope and expects it to outlive that scope wraps the spawn in `createRoot(() => effect(...))` -- `lite-query`'s query-watcher being the first in the ecosystem. (The companion `runWithOwner`, for re-attaching to a captured owner, is named in the engine as the intended second half of this API and is not yet shipped.)
360
+
324
361
  ### isTracking
325
362
 
326
363
  ```ts
@@ -494,7 +531,7 @@ Default sizing for a Twitch-extension-style budget:
494
531
  | Heavy dashboard (variable scale) | 2048 | 16384 | `"eager"` | `"grow"` |
495
532
  | Per-viewer sandbox / short-lived | 512 | 2048 | `"lazy"` | `"throw"` |
496
533
 
497
- `stats()` reports `signals`, `computeds`, `effects`, `activeNodes`, `activeLinks`, `pooledLinks`, `nodePoolCapacity`, `linkPoolCapacity` (8 keys; the capacity keys are ledgers under `"lazy"`). Drop it on screen for live observability.
534
+ `stats()` reports 11 keys: eight live gauges -- `signals`, `computeds`, `effects`, `activeNodes`, `activeLinks`, `pooledLinks`, `nodePoolCapacity`, `linkPoolCapacity` (the capacity keys are ledgers under `"lazy"`) -- plus three cumulative lifecycle counters added in **1.4.0**: `totalAllocations`, `totalDisposals`, and `poolGrowths` (monotonic over the registry's life, reset only by `destroy()`). Sample them over time to chart allocation rate, pool-reuse ratio, and graph churn; in a quiescent registry `totalAllocations - totalDisposals === activeNodes`. Drop it on screen for live observability.
498
535
 
499
536
  </details>
500
537
 
@@ -658,7 +695,7 @@ These are the questions you'd ask in a code review, with the answers:
658
695
 
659
696
  ## Benchmarks
660
697
 
661
- Honest numbers, against the same workload, with anti-DCE sinks and verified effect execution. All measurements: Node 22, **2016-era Intel MacBook Pro (4 cores, ~10 yr old hardware)**, **one engine per cold process**, median across reps. Newer/faster machines shift all libs up proportionally; the relative ordering between libs is what matters. Numbers below are lite-signal **@1.3.0** (default `prealloc: "eager"`) vs alien-signals on the same `benchmark.mjs` loop -- the harness now reports **median execution time + transient heap** rather than ops/s. 1.3.0's hot paths are byte-identical to 1.2.2, so these track the 1.2.2 measurement; the deltas are run-to-run noise on this old host, not engine changes.
698
+ Honest numbers, against the same workload, with anti-DCE sinks and verified effect execution. All measurements: Node 22, **2016-era Intel MacBook Pro (4 cores, ~10 yr old hardware)**, **one engine per cold process**, median across reps. Newer/faster machines shift all libs up proportionally; the relative ordering between libs is what matters. Numbers below are lite-signal **@1.3.0** (default `prealloc: "eager"`) vs alien-signals on the same `benchmark.mjs` loop -- the harness now reports **median execution time + transient heap** rather than ops/s. 1.3.0's hot paths are byte-identical to 1.2.2, so these track the 1.2.2 measurement; the deltas are run-to-run noise on this old host, not engine changes. **1.4.0 carries these forward unchanged** -- its only addition is three `stats()` counters that bump on acquire/dispose/grow, never on the steady-state read path, so throughput is identical (a fresh 1.4.0 bench run will be published when available). Full per-engine tables: [`results.txt`](./results.txt) (this propagation suite) and [`resultsReactive.txt`](./resultsReactive.txt) (the cross-framework reactivity suite).
662
699
 
663
700
  | Scenario | What it stresses | lite-signal | alien-signals | lite vs alien | transient heap (lite / alien) |
664
701
  | ---------- | -------------------------------- | ----------- | ------------- | ------------- | ----------------------------- |
@@ -705,7 +742,7 @@ Three tiers, all reproducible.
705
742
 
706
743
  - **`01-core_test.mjs`** -- signal/computed/effect basics, equality semantics, NaN/+/-0, subscribe/peek/update, untrack, batch, cleanup ordering, first-run error recovery, nested object reference-identity gotchas.
707
744
  - **`02-topology_test.mjs`** -- diamond glitch-freedom, 256-deep and 1024-deep computed chains, wide fan-out (1000 effects from one signal), dynamic dependency switching, conditional fan-out, nested effects, cycle detection (`CycleError`).
708
- - **`03-pool_test.mjs`** -- `CapacityError` under both `"throw"` and `"grow"` policies, the 16× link ceiling, stable pool reuse across thousands of create/dispose cycles, registry isolation, and (1.3.0) the lazy-prealloc paths: on-demand construction reaching the same steady state as eager, a never-allocated lazy registry surviving `destroy()`, and `"grow"` extending both pool ledgers past their initial capacity.
745
+ - **`03-pool_test.mjs`** -- `CapacityError` under both `"throw"` and `"grow"` policies, the 16× link ceiling, stable pool reuse across thousands of create/dispose cycles, registry isolation, (1.3.0) the lazy-prealloc paths: on-demand construction reaching the same steady state as eager, a never-allocated lazy registry surviving `destroy()`, and `"grow"` extending both pool ledgers past their initial capacity, and (1.4.0) the `stats()` lifecycle counters: the 11-key shape, `totalAllocations` / `totalDisposals` tracking the `activeNodes` live invariant, `poolGrowths` firing on growth and staying 0 on a correctly-sized eager pool, and `destroy()` resetting all three.
709
746
  - **`05-scheduler_test.mjs`** -- scheduler-deferred effects, dispose-during-schedule races, microtask integration, 32-bit version wrap (simulated), `setDefaultRegistry`, `onCleanup` inside computeds.
710
747
  - **`06-nested-objects_test.mjs`** -- array mutation patterns (push/splice/spread), deep nested paths, Map/Set/Date inside signals, custom structural equality, computed memoisation cutoffs over object slices, signal-of-signals composition, high-frequency object updates, batched immutable updates.
711
748
  - **`07-dispose_test.mjs`** -- unified `dispose(api)` across signals, computeds and effect handles, idempotency, cross-registry isolation (per-registry Symbol prevents pool corruption), foreign-value safety, top-level helper routing, 500-cycle balanced churn leaving pool and stats stable.
@@ -725,8 +762,9 @@ Three tiers, all reproducible.
725
762
  - **`21-perf-pins_test.mjs`** -- v1.2.1 construction-shape pins (6 tests). Locks the canonical handle shapes (`signal` 6 own props: peek/set/update/subscribe + NODE_PTR/NODE_GEN; `computed` 4: peek/subscribe + NODE_PTR/NODE_GEN) so a future "let's unify them" change has to be explicit. Locks the 1.2.1 ABA guards: detached `const {set} = signal()` keeps working on a LIVE signal; `read()` returns `undefined` and skips dep-tracking on a stale handle (no phantom subscription to the recycled slot); `set()` on a stale handle is a no-op across three corruption tiers (disposed slot, recycled slot, downstream propagation); `peek()` returns `undefined` for stale signal and computed handles.
726
763
  - **`22-mutation-hook_test.mjs`** -- 1.2.1 `onGraphMutation` semantics (12 tests across 2 suites). Registration: unsubscribe returns a function; `null` argument clears and the unsub restores the prior listener; non-function/non-null throws `TypeError`; multiple registrations stack LIFO; registries are isolated (no cross-talk). Opcode emission: `1` node-create fires with `(id, flags)` for signal (32) / computed (1) / effect (2); `2` node-dispose fires for cascade-disposed owned children; `3` link-add fires with `(source.id, target.id)` on dependency record; `4` link-remove fires when a dep-set flip severs the tail; `5` recompute fires on initial eval AND re-eval; the hook fires synchronously inside the mutation (listener sees its own event before the caller returns); payload is always three plain numbers -- no objects, no closures.
727
764
  - **`23-owner-introspection_test.mjs`** -- 1.2.1 owner-tree introspection + effect-disposer regression (22 tests across 4 suites). `ownerOf`: undefined for top-level / garbage input / stale handle; returns the enclosing effect's descriptor for a child created inside an effect body. `forEachOwned`: no-op for handles with no owned children / garbage input / stale handle; iterates owned children as `{id, kind, value}` descriptors. Gen-guarded introspection (ABA fix): `nodeId` / `describe` / `hasObservers` return undefined / false for stale handles; `observeObservers` throws `TypeError`; `forEachObserver` / `forEachSource` are no-ops; descriptors returned by `describeNode` are themselves gen-stamped so a descriptor obtained pre-recycle correctly walks as a no-op post-recycle (the "descriptors are re-walkable handles" contract survives the guard). Plus the 1.2.1 effect-dispose-handle fix: passing the effect's disposer directly to `describe` / `nodeId` / `forEachSource` / `forEachOwned` / `ownerOf` / `hasObservers` works as a first-class introspection handle (pre-fix it was a bare closure and returned `undefined` for a *live* effect); after `fx()` dispose the same handle correctly goes stale on every entry point; the disposer's `NODE_GEN` mirrors the effect node's birthGen exactly.
728
- - **`24-signalbox_test.mjs`** -- staged for v1.5.0; all 9 tests `{skip: true}` on 1.3.x. The `signalBox` / `computedBox` allocation-light handle API lands in 1.5.0; the suite is committed early so the surface is pinned and the skips are visible in the test count (the 10 skips on 1.3.0 are these 9 plus 1 architecturally-N/A SSR case in `17-reactivity`).
729
- - **`25-devtools-real-boot_test.mjs`** -- Devtools/Studio contract (10 tests). Boots the actual `Devtools.js` against the 1.3.0 engine and exercises all 19 Devtools exports plus the 10 symbols Studio imports from Devtools. Pins the ghost contract: heavy introspection (graph walk, owner-tree, observer descriptors) adds **zero** nodes to the live graph. Catches the real-rig failure mode where importing the package by its own name from a repo whose `package.json` declares `name: "@zakkster/lite-signal"` resolves to the published build instead of the local engine.
765
+ - **`24-signalbox_test.mjs`** -- the `signalBox` / `computedBox` allocation-light handle API, **activated in 1.5.0** (committed `{skip:true}` since 1.3.0, now running against the real implementation). 12 tests: box get/set/peek/update, `computedBox` derive + memoize, peek-does-not-track, subscribe fires-and-untracks, box<->callable interop both directions, batch coalescing (including set-then-revert net no-op), dispose with ABA-safety, the `equals` short-circuit, `computedBox.peek`, and the top-level helpers bound to the default registry.
766
+ - **`27-create-root_test.mjs`** -- `createRoot` (1.5.0), the ownership escape hatch. A watcher spawned inside a consumer effect via `createRoot` survives the consumer's re-run (the exact `lite-query` lazy-watcher pattern); the contrast case confirms an *unwrapped* spawn is cascade-disposed; `createRoot` returns `fn`'s value, detaches tracking in `fn`'s direct body while inner effect bodies still track, and composes with box handles.
767
+ - **`25-devtools-real-boot_test.mjs`** -- Devtools/Studio contract (10 tests). Boots the actual `Devtools.js` against the 1.5.0 engine and exercises all 19 Devtools exports plus the 10 symbols Studio imports from Devtools. Pins the ghost contract: heavy introspection (graph walk, owner-tree, observer descriptors) adds **zero** nodes to the live graph. Catches the real-rig failure mode where importing the package by its own name from a repo whose `package.json` declares `name: "@zakkster/lite-signal"` resolves to the published build instead of the local engine.
730
768
  - **`26-free-list-invariant_test.mjs`** -- the 1.2.2 audit's cleanliness pins (3 invariant tests + 1 targeted coverage test). Asserts directly -- by inspecting freshly-allocated nodes through the documented `describe()` -> `NODE_PTR` introspection protocol -- that the `ReactiveNode` constructor and the fresh-pool-growth path initialize the ten fields the audit removed from `createNode` to identical values, so the deleted writes were defending against a state the engine cannot produce on a clean free list. The 4th test covers the swallow-on-self-dispose-then-throw branch in `pullComputed` (the path that lifted branch coverage from 98.07% to 98.43%).
731
769
 
732
770
  ```bash
@@ -825,7 +863,7 @@ In stable environments (game engines, particle systems, visualizers), `lite-sign
825
863
  > not engine changes. lite remains the only zero-alloc library on every stable scenario
826
864
  > (see [`results.txt`](./results.txt)).
827
865
 
828
- The cross-framework reactivity suite agrees independently, re-run on **1.3.0** (default eager, median-of-10, isolated): lite-signal is the **fastest of five frameworks on all five `dyn` rows** -- `dyn: large web app` **544ms** (+7% vs alien-signals' 586ms) and `dyn: wide dense` **902ms** (+3% vs 926ms), plus simple component (+17%), dynamic component (+15%), and deep (+14%) -- with preact 6-19× slower and vue 15-32× slower on the app-shaped graphs (see the `run_*.txt` logs). On the tiny `S: updateComputations` micro-rows lite and alien trade the lead within a few percent (lite ahead on 3 of 7); these sub-60ms kernels are dominated by run-to-run noise on this old host. The retracking is verified correct by `retracking.difftest.mjs` -- 20,000 direct + 10,000 batched writes, 0 disagreements against the **published 1.1.5** reference (re-pinned for v1.2).
866
+ The cross-framework reactivity suite agrees independently, re-run on **1.3.0** (default eager, median-of-10, isolated): lite-signal is the **fastest of five frameworks on all five `dyn` rows** -- `dyn: large web app` **544ms** (+7% vs alien-signals' 586ms) and `dyn: wide dense` **902ms** (+3% vs 926ms), plus simple component (+17%), dynamic component (+15%), and deep (+14%) -- with preact 6-19× slower and vue 15-32× slower on the app-shaped graphs (see [`resultsReactive.txt`](./resultsReactive.txt)). On the tiny `S: updateComputations` micro-rows lite and alien trade the lead within a few percent (lite ahead on 3 of 7); these sub-60ms kernels are dominated by run-to-run noise on this old host. The retracking is verified correct by `retracking.difftest.mjs` -- 20,000 direct + 10,000 batched writes, 0 disagreements against the **published 1.1.5** reference (re-pinned for v1.2).
829
867
 
830
868
  **The Takeaway:** as of 1.1.4 you no longer have to choose, and 1.3.0 holds the line -- the engine still ranks **4th of 15** on the official js-reactivity-benchmark (the only zero-GC library in the field). `lite-signal` keeps the zero-GC, flat-arena profile for 120fps Canvas/WebGL **and** wins decisively on the high-churn dynamic and fan-in topologies that dominate live UI -- the shapes where zero allocation pays off most. It runs at parity with alien-signals on cheap stable shapes. The one shape where alien's flatter representation still leads is the 256-deep computed pipeline (DEEP CHAIN, -18% on the 1.3.0 isolated run).
831
869
 
@@ -833,7 +871,9 @@ The cross-framework reactivity suite agrees independently, re-run on **1.3.0** (
833
871
  - **1.1.5** -- additions in service of `lite-devtools` (node identity/traversability on the introspection walkers, for full auto-discovered graph rendering). *Shipped.*
834
872
  - **1.2.0** -- the **ownership hybrid**: an owner tree so nested effects/computeds auto-dispose with their parent (closes conformance #209 / #210, matching Solid's `createRoot` ergonomics). Plus three additive features built on the same internal split: pre-batch revert (`batch(() => { a.set(99); a.set(10); })` doesn't re-fire), multi-throw `AggregateError`, and scheduler-thunk caching with an ABA gen guard. *Shipped.*
835
873
  - **1.3.0** -- the **pool minor**: node and link pools become growable and incrementally populated. New `prealloc` config (`"eager"` default | `"lazy"`) chooses up-front vs on-demand construction; `onCapacityExceeded: "grow"` extends pools via chunked refill (runs of up to 1024 links / 256 nodes, ledger doubles) bounded by the 16x link ceiling; `maxFlushPasses` is now a public config. Internally the propagation mark phase moved to an intrusive linked-list stack (a `nextMark` field) -- the only node-shape change. The hot paths and public callable API are byte-identical to 1.2.2; steady-state zero-GC is unchanged. *Shipped.*
836
- - **1.4** -- next engine work. The pull-mode recursion depth limit (~5,000 chained computeds) is the main outstanding architectural item; cumulative allocation counters (`totalAllocations` / `totalDisposals` / `poolGrowths`) are reserved for the `stats()` surface here.
874
+ - **1.4.0** -- the **observability minor**: `stats()` gains three cumulative lifecycle counters (`totalAllocations`, `totalDisposals`, `poolGrowths`), the surface reserved for it in the 1.2.x/1.3.0 notes. Monotonic over the registry's life, reset by `destroy()`, bumped on the existing acquire/dispose/grow edges -- no hot-path change, no public callable API change. This is what lite-devtools / lite-studio read to chart allocation rate, pool-reuse ratio, and graph churn. Drop-in over 1.3.0. *Shipped (beta).*
875
+ - **1.5.0** -- the **API-surface minor**: two non-callable, allocation-light primitives `signalBox` / `computedBox` land alongside the callable `signal` / `computed` (same `ReactiveNode`, full interop, ~1.7x cheaper construction), and **`createRoot`** lands as the ownership escape hatch the owner tree was designed for (detached scope for lazily spawning long-lived nodes from inside a consumer effect -- the pattern `lite-query` needs). The callable API, hot paths, and `stats()` shape are unchanged; the `24-signalbox` suite (staged since 1.3.0) now runs and passes. *Shipped (alpha).*
876
+ - **Next** -- `runWithOwner` (the re-attach companion to `createRoot`); the pull-mode recursion depth limit (~5,000 chained computeds) remains the main outstanding architectural item.
837
877
 
838
878
  > Note: the retracking rewrite that closes the dynamic-topology gap shipped in **1.1.4**, not a future release. The earlier roadmap that listed it under "v1.2" is superseded.
839
879
 
package/Signal.d.ts CHANGED
@@ -43,7 +43,7 @@ export type Dispose = () => void;
43
43
  * a {@link Computed}, or an effect's {@link Dispose} function. Passing an
44
44
  * unrelated value is a safe no-op.
45
45
  */
46
- export type Disposable<T = unknown> = Signal<T> | Computed<T> | Dispose;
46
+ export type Disposable<T = unknown> = Signal<T> | Computed<T> | SignalBox<T> | ComputedBox<T> | Dispose;
47
47
 
48
48
  // --- Reactive primitive shapes ------------------------------------------------
49
49
 
@@ -71,6 +71,38 @@ export interface Computed<T> {
71
71
  subscribe(fn: (value: T) => void): Dispose;
72
72
  }
73
73
 
74
+ /**
75
+ * Allocation-light, non-callable signal (1.5.0). A plain object on a shared
76
+ * prototype rather than a callable function -- cheaper to construct than
77
+ * {@link Signal} (no closure allocation), with an identical zero-GC read/write
78
+ * path. Interoperates freely with callable handles in the same graph.
79
+ */
80
+ export interface SignalBox<T> {
81
+ /** Read the current value, tracking the read if inside an effect or computed. */
82
+ get(): T;
83
+ /** Overwrite the value. No-op if equal under the box's equality predicate. */
84
+ set(value: T): void;
85
+ /** Read the value WITHOUT tracking. */
86
+ peek(): T;
87
+ /** Functional update: `set(fn(currentValue))`. Reads the current value without tracking. */
88
+ update(fn: (current: T) => T): void;
89
+ /** Subscribe to value changes. Fires immediately with the current value; the callback runs untracked. */
90
+ subscribe(fn: (value: T) => void): Dispose;
91
+ }
92
+
93
+ /**
94
+ * Allocation-light, non-callable computed (1.5.0). The derived counterpart to
95
+ * {@link SignalBox}: `{ get, peek, subscribe }`, no `set` / `update`.
96
+ */
97
+ export interface ComputedBox<T> {
98
+ /** Resolve the value, tracking the read if inside an effect or computed. */
99
+ get(): T;
100
+ /** Resolve the value WITHOUT tracking. */
101
+ peek(): T;
102
+ /** Subscribe to value changes. Fires immediately with the current value; the callback runs untracked. */
103
+ subscribe(fn: (value: T) => void): Dispose;
104
+ }
105
+
74
106
  // --- Diagnostics --------------------------------------------------------------
75
107
 
76
108
  export interface RegistryStats {
@@ -92,6 +124,26 @@ export interface RegistryStats {
92
124
  nodePoolCapacity: number;
93
125
  /** Number of nodes currently allocated (signals + computeds + alive effects). */
94
126
  activeNodes: number;
127
+ /**
128
+ * Cumulative count of every node acquired over the registry's life -- whether
129
+ * popped from the free list or freshly constructed during a pool-growth chunk.
130
+ * Monotonic; reset only by {@link Registry.destroy}. The true total ever handed
131
+ * out, not the live count (`activeNodes` is the live gauge). Added in 1.4.0.
132
+ */
133
+ totalAllocations: number;
134
+ /**
135
+ * Cumulative count of every node returned to the pool (`disposeNode`). Monotonic;
136
+ * reset only by {@link Registry.destroy}. In a quiescent registry
137
+ * `totalAllocations - totalDisposals === activeNodes`. Added in 1.4.0.
138
+ */
139
+ totalDisposals: number;
140
+ /**
141
+ * Cumulative count of pool-growth chunks -- incremented whenever a node *or* link
142
+ * refill pushes capacity past its current ledger. Nonzero after warm-up means the
143
+ * initial pool was undersized and grew at runtime; an eager pool sized for its
144
+ * workload keeps this at 0. Reset only by {@link Registry.destroy}. Added in 1.4.0.
145
+ */
146
+ poolGrowths: number;
95
147
  }
96
148
 
97
149
  // --- Observer-lifecycle introspection (1.1.4) ---------------------------------
@@ -121,7 +173,7 @@ export interface ObserveObserversHooks {
121
173
  export type Unobserve = () => void;
122
174
 
123
175
  /** Anything carrying a node identity that the introspection surface can read. */
124
- export type ReactiveHandle = Signal<any> | Computed<any>;
176
+ export type ReactiveHandle = Signal<any> | Computed<any> | SignalBox<any> | ComputedBox<any>;
125
177
 
126
178
  // --- Graph-mutation hook (1.2.1) ----------------------------------------------
127
179
 
@@ -201,10 +253,25 @@ export interface Registry {
201
253
  signal<T>(initial: T, opts?: SignalOptions<T>): Signal<T>;
202
254
  computed<T>(fn: () => T, opts?: ComputedOptions<T>): Computed<T>;
203
255
  effect(fn: () => void, opts?: EffectOptions): Dispose;
256
+ /** Allocation-light, non-callable signal (1.5.0). See {@link SignalBox}. */
257
+ signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
258
+ /** Allocation-light, non-callable computed (1.5.0). See {@link ComputedBox}. */
259
+ computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
260
+ /**
261
+ * Run `fn` in a detached ownership scope (1.5.0). Effects/computeds created
262
+ * directly in `fn` are NOT adopted by the enclosing owner, so they survive
263
+ * the enclosing effect's re-runs and disposal -- the caller owns their
264
+ * lifecycle (`fn` typically returns a disposer or the created handle). Both
265
+ * ownership and tracking are detached for the duration of `fn`; inner
266
+ * effect/computed bodies still establish their own scopes. The ownership
267
+ * escape hatch for lazily spawning a long-lived node from inside a consumer
268
+ * effect (e.g. a query watcher). Returns whatever `fn` returns.
269
+ */
270
+ createRoot<T>(fn: () => T): T;
204
271
  /**
205
272
  * Universal disposal for anything created by this registry: signals,
206
- * computeds, or effect dispose handles. Cross-registry calls are silent
207
- * no-ops (each registry owns its own private node-identity Symbol).
273
+ * computeds, boxes, or effect dispose handles. Cross-registry calls are
274
+ * silent no-ops (each registry owns its own private node-identity Symbol).
208
275
  * Passing an unrelated value is also a safe no-op.
209
276
  */
210
277
  dispose(api: Disposable): void;
@@ -275,6 +342,12 @@ export function setDefaultRegistry(registry: Registry): void;
275
342
  export function signal<T>(initial: T, opts?: SignalOptions<T>): Signal<T>;
276
343
  export function computed<T>(fn: () => T, opts?: ComputedOptions<T>): Computed<T>;
277
344
  export function effect(fn: () => void, opts?: EffectOptions): Dispose;
345
+ /** Allocation-light, non-callable signal (1.5.0), bound to the default registry. See {@link SignalBox}. */
346
+ export function signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
347
+ /** Allocation-light, non-callable computed (1.5.0), bound to the default registry. See {@link ComputedBox}. */
348
+ export function computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
349
+ /** Run `fn` in a detached ownership scope (1.5.0), bound to the default registry. See {@link Registry.createRoot}. */
350
+ export function createRoot<T>(fn: () => T): T;
278
351
  /** Universal disposal -- see {@link Registry.dispose}. */
279
352
  export function dispose(api: Disposable): void;
280
353
  export function batch<T>(fn: () => T): T;
package/Signal.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @zakkster/lite-signal v1.3.0
2
+ * @zakkster/lite-signal v1.5.0
3
3
  * --------------------
4
4
  * Hybrid Doubly-Linked-List Reactive Graph Engine -- decoupled (Signal1_3) base
5
5
  * with the two 1.1.3 performance fixes ported in:
@@ -48,11 +48,13 @@
48
48
  * -- OWNER vs OBSERVER --
49
49
  * `currentObserver` = the node whose READS establish dependencies (tracking).
50
50
  * `currentOwner` = the node that OWNS anything created right now (lifecycle).
51
- * Today they move together, so behaviour is unchanged -- but they are distinct
52
- * pointers so future runWithOwner/createRoot can attach ownership without
53
- * establishing reactive dependencies (and untrack can suppress tracking
54
- * without orphaning created nodes). createNode and onCleanup key off the
55
- * OWNER; the read fast-path and allocateLink key off the OBSERVER.
51
+ * They move together by default, but are distinct pointers so ownership can be
52
+ * detached without affecting tracking. createRoot (1.5.0) uses this: it nulls
53
+ * the OWNER (and OBSERVER) for the duration of a callback so nodes created
54
+ * inside survive the enclosing scope's re-runs; runWithOwner (re-attaching to a
55
+ * chosen owner) remains future work on the same split. untrack suppresses
56
+ * tracking without orphaning created nodes. createNode and onCleanup key off
57
+ * the OWNER; the read fast-path and allocateLink key off the OBSERVER.
56
58
  */
57
59
 
58
60
  const FLAG_COMPUTED = 1 << 0;
@@ -201,6 +203,7 @@ export class CapacityError extends Error {
201
203
  * miss, not a single doubling burst -- so any one growth pause stays
202
204
  * bounded; the capacity ledger still doubles (`stats()` semantics
203
205
  * unchanged). Link growth is bounded by a hard ceiling of `maxLinks * 16`.
206
+ * Each chunk increments `stats().poolGrowths`.
204
207
  * @param {number} [config.maxFlushPasses=100] Cycle-protection: max effect-queue
205
208
  * drain passes before throwing an
206
209
  * Error prefixed `"CycleError:"`.
@@ -240,6 +243,13 @@ export function createRegistry(config) {
240
243
  let statSignals = 0;
241
244
  let statComputeds = 0;
242
245
  let statEffects = 0;
246
+ // 1.4: cumulative lifecycle counters for churn-rate observability (lite-devtools
247
+ // / lite-studio derive allocationRate, poolReuseRate, avg node lifetime from these).
248
+ // Monotonic across the registry's life; reset only by destroy(). Three integer
249
+ // bumps at existing chokepoints -- no new node fields, no hot-path cost.
250
+ let statTotalAllocations = 0; // bumped on every createNode (pool pop OR fresh build)
251
+ let statTotalDisposals = 0; // bumped on every disposeNode
252
+ let statPoolGrowths = 0; // bumped when a node/link chunk pushes capacity past its ledger
243
253
 
244
254
  const effectQueueA = [];
245
255
  const effectQueueB = [];
@@ -259,35 +269,20 @@ export function createRegistry(config) {
259
269
  let nodeSeq = 1 | 0;
260
270
  let lifecycleCount = 0 | 0;
261
271
  const lifecycleMap = new WeakMap();
262
-
263
272
  function fireConnect(node) {
264
273
  const e = lifecycleMap.get(node);
265
274
  if (e === undefined || e.onConnect === undefined) return;
266
275
  const po = currentObserver, pt = isTrackingDeps;
267
- currentObserver = null;
268
- isTrackingDeps = false;
269
- try {
270
- e.onConnect();
271
- } finally {
272
- currentObserver = po;
273
- isTrackingDeps = pt;
274
- }
276
+ currentObserver = null; isTrackingDeps = false;
277
+ try { e.onConnect(); } finally { currentObserver = po; isTrackingDeps = pt; }
275
278
  }
276
-
277
279
  function fireDisconnect(node) {
278
280
  const e = lifecycleMap.get(node);
279
281
  if (e === undefined || e.onDisconnect === undefined) return;
280
282
  const po = currentObserver, pt = isTrackingDeps;
281
- currentObserver = null;
282
- isTrackingDeps = false;
283
- try {
284
- e.onDisconnect();
285
- } finally {
286
- currentObserver = po;
287
- isTrackingDeps = pt;
288
- }
283
+ currentObserver = null; isTrackingDeps = false;
284
+ try { e.onDisconnect(); } finally { currentObserver = po; isTrackingDeps = pt; }
289
285
  }
290
-
291
286
  let isFlushing = false;
292
287
 
293
288
  const flushErrorBuffer = [];
@@ -319,21 +314,18 @@ export function createRegistry(config) {
319
314
  *
320
315
  * @private
321
316
  */
322
- // --- Graph-mutation hook (1.2.1 keystone prototype) ---------------------
323
- // Single nullable listener; every fire point is `if (mutationHook !== null)`
324
- // -- branch-predicted free when absent, allocation-free when present
325
- // (opcode + two int args). Enables push-based devtools (watchGraph) and the
326
- // recompute profiler. Opcodes: 1 node-create, 2 node-dispose, 3 link-add,
327
- // 4 link-remove, 5 recompute.
317
+ // --- Graph-mutation hook (1.2.1 keystone prototype) ---------------------
318
+ // Single nullable listener; every fire point is `if (mutationHook !== null)`
319
+ // -- branch-predicted free when absent, allocation-free when present
320
+ // (opcode + two int args). Enables push-based devtools (watchGraph) and the
321
+ // recompute profiler. Opcodes: 1 node-create, 2 node-dispose, 3 link-add,
322
+ // 4 link-remove, 5 recompute.
328
323
  let mutationHook = null;
329
-
330
324
  function onGraphMutation(fn) {
331
325
  if (fn !== null && typeof fn !== "function") throw new TypeError("onGraphMutation: listener must be a function or null");
332
326
  const prev = mutationHook;
333
327
  mutationHook = fn;
334
- return () => {
335
- if (mutationHook === fn) mutationHook = prev;
336
- };
328
+ return () => { if (mutationHook === fn) mutationHook = prev; };
337
329
  }
338
330
 
339
331
  function allocateLink(source, target) {
@@ -391,6 +383,7 @@ export function createRegistry(config) {
391
383
  let doubled = currentLinkCapacity;
392
384
  while (doubled < linkPool.length) doubled *= 2;
393
385
  currentLinkCapacity = doubled > maxLinkLimit ? maxLinkLimit : doubled;
386
+ statPoolGrowths++; // 1.4: link capacity ledger crossed
394
387
  }
395
388
  } else {
396
389
  link = freeLinkHead;
@@ -565,6 +558,7 @@ export function createRegistry(config) {
565
558
  node.nextFree = freeNodeHead;
566
559
  freeNodeHead = node;
567
560
  activeNodes = (activeNodes - 1) | 0;
561
+ statTotalDisposals++; // 1.4: every node returned to the pool
568
562
  }
569
563
 
570
564
  /**
@@ -599,6 +593,7 @@ export function createRegistry(config) {
599
593
  let doubled = currentNodesCapacity;
600
594
  while (doubled < nodePool.length) doubled *= 2;
601
595
  currentNodesCapacity = doubled;
596
+ statPoolGrowths++; // 1.4: capacity ledger crossed
602
597
  }
603
598
  } else {
604
599
  node = freeNodeHead;
@@ -606,6 +601,7 @@ export function createRegistry(config) {
606
601
  node.nextFree = null;
607
602
  }
608
603
  activeNodes = (activeNodes + 1) | 0;
604
+ statTotalAllocations++; // 1.4: every node acquired (pool pop or fresh build)
609
605
 
610
606
  // 1.2.3: Clean free-list invariant (Andrii's recommendation).
611
607
  //
@@ -625,8 +621,7 @@ export function createRegistry(config) {
625
621
  node.version = 0;
626
622
  node.evalVersion = 0;
627
623
  node.markEpoch = 0;
628
- node.id = nodeSeq;
629
- nodeSeq = (nodeSeq + 1) | 0; // fresh identity per allocation (ported from 1.1.5)
624
+ node.id = nodeSeq; nodeSeq = (nodeSeq + 1) | 0; // fresh identity per allocation (ported from 1.1.5)
630
625
 
631
626
  // Wire into Owner Context (lifecycle, not tracking -- keyed off currentOwner).
632
627
  // ONLY observers (computed/effect) are adopted: a re-running owner disposes
@@ -1000,10 +995,7 @@ export function createRegistry(config) {
1000
995
  // closures: set() is the hot write path (a closure over `node` beats the
1001
996
  // this[NODE_PTR] load and keeps `const {set} = signal()` working), and peek()'s
1002
997
  // body is too cheap to absorb the node recovery.
1003
- function sharedUpdate(fn) {
1004
- return this.set(fn(this[NODE_PTR].value));
1005
- }
1006
-
998
+ function sharedUpdate(fn) { return this.set(fn(this[NODE_PTR].value)); }
1007
999
  function sharedSubscribe(fn) {
1008
1000
  const read = this;
1009
1001
  return effect(() => {
@@ -1017,7 +1009,6 @@ export function createRegistry(config) {
1017
1009
  }
1018
1010
  });
1019
1011
  }
1020
-
1021
1012
  // Shared peeks (one per registry, not per primitive). Save one closure
1022
1013
  // allocation per signal/computed creation versus the previous per-instance
1023
1014
  // arrows. Method-invoked, so `this` is the read function and this[NODE_PTR]
@@ -1028,7 +1019,6 @@ export function createRegistry(config) {
1028
1019
  if (this[NODE_GEN] !== node.gen) return undefined; // stale handle: slot recycled (ABA guard, matches read())
1029
1020
  return node.value;
1030
1021
  }
1031
-
1032
1022
  function sharedComputedPeek() {
1033
1023
  const node = this[NODE_PTR];
1034
1024
  if (this[NODE_GEN] !== node.gen) return undefined;
@@ -1144,6 +1134,162 @@ export function createRegistry(config) {
1144
1134
  return read;
1145
1135
  }
1146
1136
 
1137
+ // --- 1.5: signalBox / computedBox -- non-callable, allocation-light API ------
1138
+ //
1139
+ // The callable signal()/computed() pay an irreducible per-primitive cost: a
1140
+ // `read` closure + (for signals) a `set` closure, both capturing `node` and
1141
+ // `birthGen`. That is the price of the ergonomic `count()` / `count.set(x)`
1142
+ // surface, and it is why creation can't reach alien-signals territory on the
1143
+ // callable path (Andrii's analysis; confirmed empirically).
1144
+ //
1145
+ // signalBox() trades the call ergonomics for allocation: it returns a PLAIN
1146
+ // OBJECT whose methods live on a shared prototype, so creation allocates one
1147
+ // object and writes two own props (NODE_PTR, NODE_GEN) -- zero closures. The
1148
+ // graph machinery underneath is identical; a box and a callable handle wrap
1149
+ // the same kind of ReactiveNode and interoperate freely in one graph.
1150
+ //
1151
+ // const s = registry.signalBox(0);
1152
+ // s.get(); s.set(1); s.peek(); s.update(n => n+1); s.subscribe(fn);
1153
+ //
1154
+ // Hot-path note: get()/set() resolve the node via this[NODE_PTR] (one prop
1155
+ // load) instead of a lexical capture. On a monomorphic box shape V8 compiles
1156
+ // that to a pointer-offset load; the cost vs the callable closure is in the
1157
+ // low single digits on read-heavy graphs and is the explicit, documented
1158
+ // tradeoff for the creation win.
1159
+
1160
+ function boxGet() {
1161
+ const node = this[NODE_PTR];
1162
+ if (node.gen !== this[NODE_GEN]) return undefined; // stale: slot recycled (ABA guard)
1163
+ if (isTrackingDeps && currentObserver !== null) {
1164
+ const expected = activeObserverCurrentDep;
1165
+ if (expected !== null && expected.source === node) {
1166
+ activeObserverCurrentDep = expected.nextDep;
1167
+ } else {
1168
+ allocateLink(node, currentObserver);
1169
+ }
1170
+ }
1171
+ return node.value;
1172
+ }
1173
+ function boxSet(value) {
1174
+ const node = this[NODE_PTR];
1175
+ if (node.gen !== this[NODE_GEN]) return;
1176
+ const eq = node.equals;
1177
+ if (eq && eq(node.value, value)) return;
1178
+ if (batchDepth > 0 && node.revertEpoch !== batchEpoch) {
1179
+ node.preBatchValue = node.value;
1180
+ node.preBatchVersion = node.version;
1181
+ node.revertEpoch = batchEpoch;
1182
+ }
1183
+ node.value = value;
1184
+ if (batchDepth > 0 && node.revertEpoch === batchEpoch && eq && eq(node.preBatchValue, value)) {
1185
+ node.version = node.preBatchVersion;
1186
+ return;
1187
+ }
1188
+ globalVersion = (globalVersion + 1) | 0;
1189
+ node.version = globalVersion;
1190
+ markDownstream(node);
1191
+ if (batchDepth === 0) flushEffects();
1192
+ }
1193
+ function boxPeek() {
1194
+ const node = this[NODE_PTR];
1195
+ if (node.gen !== this[NODE_GEN]) return undefined;
1196
+ return node.value;
1197
+ }
1198
+ function boxUpdate(fn) {
1199
+ const node = this[NODE_PTR];
1200
+ if (node.gen !== this[NODE_GEN]) return;
1201
+ boxSet.call(this, fn(node.value));
1202
+ }
1203
+ // Subscribe drives an effect that reads this box's value untracked-in-callback.
1204
+ // Mirrors sharedSubscribe but calls get() through `this` (boxes aren't callable).
1205
+ function boxSubscribe(fn) {
1206
+ const box = this;
1207
+ return effect(() => {
1208
+ const val = box.get();
1209
+ const prevTracking = isTrackingDeps;
1210
+ isTrackingDeps = false;
1211
+ try { fn(val); } finally { isTrackingDeps = prevTracking; }
1212
+ });
1213
+ }
1214
+ function boxComputedGet() {
1215
+ const node = this[NODE_PTR];
1216
+ if (node.gen !== this[NODE_GEN]) return undefined;
1217
+ if (isTrackingDeps && currentObserver !== null) {
1218
+ const expected = activeObserverCurrentDep;
1219
+ if (expected !== null && expected.source === node) {
1220
+ activeObserverCurrentDep = expected.nextDep;
1221
+ } else {
1222
+ allocateLink(node, currentObserver);
1223
+ }
1224
+ }
1225
+ return pullComputed(node);
1226
+ }
1227
+ function boxComputedPeek() {
1228
+ const node = this[NODE_PTR];
1229
+ if (node.gen !== this[NODE_GEN]) return undefined;
1230
+ return pullComputed(node);
1231
+ }
1232
+
1233
+ // Shared prototypes -- methods defined once per registry, inherited by every box.
1234
+ const SIGNAL_BOX_PROTO = {
1235
+ get: boxGet,
1236
+ set: boxSet,
1237
+ peek: boxPeek,
1238
+ update: boxUpdate,
1239
+ subscribe: boxSubscribe,
1240
+ };
1241
+ const COMPUTED_BOX_PROTO = {
1242
+ get: boxComputedGet,
1243
+ peek: boxComputedPeek,
1244
+ subscribe: boxSubscribe,
1245
+ };
1246
+
1247
+ /**
1248
+ * Allocation-light, non-callable signal. Returns a plain object on a shared
1249
+ * prototype: `{ get, set, peek, update, subscribe }`. Interoperates with
1250
+ * callable signal()/computed() in the same graph.
1251
+ * @template T
1252
+ * @param {T} initial
1253
+ * @param {object} [opts]
1254
+ * @param {(a:T,b:T)=>boolean} [opts.equals=Object.is]
1255
+ * @returns {SignalBox<T>}
1256
+ */
1257
+ function signalBox(initial, opts) {
1258
+ const node = createNode(initial, FLAG_SIGNAL);
1259
+ node.equals = (opts !== undefined && opts.equals !== undefined) ? opts.equals : OBJECT_IS;
1260
+ node.version = globalVersion;
1261
+ statSignals++;
1262
+ // Object.create(proto) allocates the box already on the shared prototype's
1263
+ // map -- no setPrototypeOf transition (which deopts the object to dictionary
1264
+ // mode and blows the method-call ICs to megamorphic). Own props are then
1265
+ // added in a stable order, keeping every box monomorphic.
1266
+ const box = Object.create(SIGNAL_BOX_PROTO);
1267
+ box[NODE_PTR] = node;
1268
+ box[NODE_GEN] = node.gen;
1269
+ return box;
1270
+ }
1271
+
1272
+ /**
1273
+ * Allocation-light, non-callable computed. Returns `{ get, peek, subscribe }`
1274
+ * on a shared prototype.
1275
+ * @template T
1276
+ * @param {() => T} fn
1277
+ * @param {object} [opts]
1278
+ * @param {(a:T,b:T)=>boolean} [opts.equals=Object.is]
1279
+ * @returns {ComputedBox<T>}
1280
+ */
1281
+ function computedBox(fn, opts) {
1282
+ const node = createNode(undefined, FLAG_COMPUTED);
1283
+ node.computeFn = fn;
1284
+ node.equals = (opts !== undefined && opts.equals !== undefined) ? opts.equals : OBJECT_IS;
1285
+ statComputeds++;
1286
+ const box = Object.create(COMPUTED_BOX_PROTO);
1287
+ box[NODE_PTR] = node;
1288
+ box[NODE_GEN] = node.gen;
1289
+ return box;
1290
+ }
1291
+
1292
+
1147
1293
  /**
1148
1294
  * Create an eagerly-run side effect that re-executes whenever its tracked
1149
1295
  * dependencies change. The body runs synchronously on creation.
@@ -1293,6 +1439,40 @@ export function createRegistry(config) {
1293
1439
  }
1294
1440
  }
1295
1441
 
1442
+ /**
1443
+ * Run `fn` in a detached ownership scope: nodes (effects / computeds)
1444
+ * created inside `fn` are NOT adopted by the enclosing owner, so they
1445
+ * survive the enclosing effect's re-runs and disposal. Use this for
1446
+ * long-lived reactive work spawned lazily from inside a consumer effect
1447
+ * (e.g. a query watcher created on first read) -- without it, the
1448
+ * enclosing effect owns the watcher and cascade-disposes it on its next
1449
+ * run. The caller is responsible for disposing anything created here
1450
+ * (there is no owner to do it automatically).
1451
+ *
1452
+ * Detaches BOTH ownership and tracking for the duration of `fn`, so reads
1453
+ * performed directly in `fn` (outside any inner effect/computed body) do
1454
+ * not link the enclosing observer either. Inner effect/computed bodies
1455
+ * establish their own owner+observer scopes as usual.
1456
+ *
1457
+ * Mirrors Solid's `createRoot` for the lifecycle axis. Returns whatever
1458
+ * `fn` returns (typically a disposer or the created handle).
1459
+ */
1460
+ function createRoot(fn) {
1461
+ const prevOwner = currentOwner;
1462
+ const prevObserver = currentObserver;
1463
+ const prevTracking = isTrackingDeps;
1464
+ currentOwner = null;
1465
+ currentObserver = null;
1466
+ isTrackingDeps = false;
1467
+ try {
1468
+ return fn();
1469
+ } finally {
1470
+ currentOwner = prevOwner;
1471
+ currentObserver = prevObserver;
1472
+ isTrackingDeps = prevTracking;
1473
+ }
1474
+ }
1475
+
1296
1476
  /**
1297
1477
  * Register a function to run when the enclosing effect/computed re-runs or
1298
1478
  * is disposed. Cascade order on disposal is inside-out: an effect's owned
@@ -1314,6 +1494,16 @@ export function createRegistry(config) {
1314
1494
  /**
1315
1495
  * Snapshot of registry counters. Useful for diagnostics and tests --
1316
1496
  * e.g. asserting that `activeNodes` returns to a baseline after teardown.
1497
+ *
1498
+ * Returns 11 keys: eight live gauges (`signals`, `computeds`, `effects`,
1499
+ * `activeNodes`, `activeLinks`, `pooledLinks`, `nodePoolCapacity`,
1500
+ * `linkPoolCapacity`) plus three cumulative lifecycle counters added in 1.4.0
1501
+ * (`totalAllocations`, `totalDisposals`, `poolGrowths`). The counters are
1502
+ * monotonic over the registry's life and reset only by {@link destroy}; sample
1503
+ * them over time to derive allocation rate, pool-reuse ratio, and graph churn
1504
+ * without the engine computing rates itself. In a quiescent registry
1505
+ * `totalAllocations - totalDisposals === activeNodes`. Box nodes
1506
+ * (`signalBox` / `computedBox`) are counted exactly as callable nodes.
1317
1507
  * @returns {RegistryStats}
1318
1508
  */
1319
1509
  function stats() {
@@ -1325,7 +1515,13 @@ export function createRegistry(config) {
1325
1515
  pooledLinks: currentLinkCapacity - activeLinks,
1326
1516
  linkPoolCapacity: currentLinkCapacity,
1327
1517
  nodePoolCapacity: currentNodesCapacity,
1328
- activeNodes
1518
+ activeNodes,
1519
+ // 1.4: cumulative lifecycle counters (monotonic; reset by destroy()).
1520
+ // Derive: allocationRate = deltatotalAllocations/deltat; poolReuseRate =
1521
+ // 1 - poolGrowths*initialCap/totalAllocations; avgLifetime ~ totalDisposals/rate.
1522
+ totalAllocations: statTotalAllocations,
1523
+ totalDisposals: statTotalDisposals,
1524
+ poolGrowths: statPoolGrowths
1329
1525
  };
1330
1526
  }
1331
1527
 
@@ -1406,6 +1602,9 @@ export function createRegistry(config) {
1406
1602
  statSignals = 0;
1407
1603
  statComputeds = 0;
1408
1604
  statEffects = 0;
1605
+ statTotalAllocations = 0;
1606
+ statTotalDisposals = 0;
1607
+ statPoolGrowths = 0;
1409
1608
 
1410
1609
  for (let i = 0; i < flushErrorCount; i++) flushErrorBuffer[i] = null;
1411
1610
  flushErrorCount = 0;
@@ -1416,7 +1615,6 @@ export function createRegistry(config) {
1416
1615
  const node = liveNode(handle);
1417
1616
  return node !== undefined && node.headSub !== null;
1418
1617
  }
1419
-
1420
1618
  function observeObservers(handle, opts) {
1421
1619
  const node = liveNode(handle);
1422
1620
  if (node === undefined) throw new TypeError("observeObservers: argument is not a reactive handle");
@@ -1437,7 +1635,6 @@ export function createRegistry(config) {
1437
1635
  if (lifecycleMap.delete(node)) lifecycleCount = (lifecycleCount - 1) | 0;
1438
1636
  };
1439
1637
  }
1440
-
1441
1638
  function describeNode(node) {
1442
1639
  const fl = node.flags;
1443
1640
  const kind = (fl & FLAG_EFFECT) !== 0 ? "effect" : (fl & FLAG_COMPUTED) !== 0 ? "computed" : "signal";
@@ -1451,7 +1648,6 @@ export function createRegistry(config) {
1451
1648
  d[NODE_GEN] = node.gen; // descriptors are re-walkable handles; stamp gen so the ABA guard holds for them too
1452
1649
  return d;
1453
1650
  }
1454
-
1455
1651
  // Gen-guarded handle resolution (1.2.1): with the v1.2 owner tree, the
1456
1652
  // ENGINE recycles slots autonomously (owner re-run cascade-disposes owned
1457
1653
  // children), so stale handles are a normal occurrence -- introspecting the
@@ -1465,28 +1661,20 @@ export function createRegistry(config) {
1465
1661
  if (handle[NODE_GEN] !== node.gen) return undefined; // stale: slot recycled
1466
1662
  return node;
1467
1663
  }
1468
-
1469
1664
  function nodeId(handle) {
1470
1665
  const node = liveNode(handle);
1471
1666
  return node !== undefined ? node.id : undefined;
1472
1667
  }
1473
-
1474
1668
  function describe(handle) {
1475
1669
  const node = liveNode(handle);
1476
1670
  return node !== undefined ? describeNode(node) : undefined;
1477
1671
  }
1478
-
1479
1672
  function forEachObserver(handle, fn) {
1480
1673
  const node = liveNode(handle);
1481
1674
  if (node === undefined) return;
1482
1675
  let l = node.headSub;
1483
- while (l !== null) {
1484
- const nx = l.nextSub;
1485
- fn(describeNode(l.target));
1486
- l = nx;
1487
- }
1676
+ while (l !== null) { const nx = l.nextSub; fn(describeNode(l.target)); l = nx; }
1488
1677
  }
1489
-
1490
1678
  /** Iterate this node's OWNED children (v1.2 owner tree). Additive 1.3 API
1491
1679
  * prototype: lets devtools/studio walk + render the ownership hierarchy
1492
1680
  * (cascade-disposal domains), which is invisible through dep/sub edges. */
@@ -1494,52 +1682,22 @@ export function createRegistry(config) {
1494
1682
  const node = liveNode(handle);
1495
1683
  if (node === undefined) return;
1496
1684
  let c = node.firstOwned;
1497
- while (c !== null) {
1498
- const nx = c.nextOwned;
1499
- fn(describeNode(c));
1500
- c = nx;
1501
- }
1685
+ while (c !== null) { const nx = c.nextOwned; fn(describeNode(c)); c = nx; }
1502
1686
  }
1503
-
1504
1687
  /** Descriptor of this node's owner, or undefined (top-level / stale handle). */
1505
1688
  function ownerOf(handle) {
1506
1689
  const node = liveNode(handle);
1507
1690
  if (node === undefined || node.owner === null) return undefined;
1508
1691
  return describeNode(node.owner);
1509
1692
  }
1510
-
1511
1693
  function forEachSource(handle, fn) {
1512
1694
  const node = liveNode(handle);
1513
1695
  if (node === undefined) return;
1514
1696
  let l = node.headDep;
1515
- while (l !== null) {
1516
- const nx = l.nextDep;
1517
- fn(describeNode(l.source));
1518
- l = nx;
1519
- }
1697
+ while (l !== null) { const nx = l.nextDep; fn(describeNode(l.source)); l = nx; }
1520
1698
  }
1521
1699
 
1522
- return {
1523
- signal,
1524
- computed,
1525
- effect,
1526
- dispose,
1527
- batch,
1528
- untrack,
1529
- onCleanup,
1530
- stats,
1531
- destroy,
1532
- isTracking,
1533
- hasObservers,
1534
- observeObservers,
1535
- forEachObserver,
1536
- forEachSource,
1537
- forEachOwned,
1538
- ownerOf,
1539
- nodeId,
1540
- describe,
1541
- onGraphMutation
1542
- };
1700
+ return {signal, computed, effect, signalBox, computedBox, dispose, batch, untrack, createRoot, onCleanup, stats, destroy, isTracking, hasObservers, observeObservers, forEachObserver, forEachSource, forEachOwned, ownerOf, nodeId, describe, onGraphMutation};
1543
1701
  }
1544
1702
 
1545
1703
  // -----------------------------------------------------------------
@@ -1560,6 +1718,14 @@ export function computed(fn, opts) {
1560
1718
  return defaultRegistry.computed(fn, opts);
1561
1719
  }
1562
1720
 
1721
+ export function signalBox(initial, opts) {
1722
+ return defaultRegistry.signalBox(initial, opts);
1723
+ }
1724
+
1725
+ export function computedBox(fn, opts) {
1726
+ return defaultRegistry.computedBox(fn, opts);
1727
+ }
1728
+
1563
1729
  export function effect(fn, opts) {
1564
1730
  return defaultRegistry.effect(fn, opts);
1565
1731
  }
@@ -1575,6 +1741,9 @@ export function batch(fn) {
1575
1741
  export function untrack(fn) {
1576
1742
  return defaultRegistry.untrack(fn);
1577
1743
  }
1744
+ export function createRoot(fn) {
1745
+ return defaultRegistry.createRoot(fn);
1746
+ }
1578
1747
 
1579
1748
  /**
1580
1749
  * True iff a read RIGHT NOW would record a dependency on the default registry.
@@ -1599,35 +1768,27 @@ export function destroy() {
1599
1768
  export function hasObservers(handle) {
1600
1769
  return defaultRegistry.hasObservers(handle);
1601
1770
  }
1602
-
1603
1771
  export function observeObservers(handle, opts) {
1604
1772
  return defaultRegistry.observeObservers(handle, opts);
1605
1773
  }
1606
-
1607
1774
  export function forEachObserver(handle, fn) {
1608
1775
  return defaultRegistry.forEachObserver(handle, fn);
1609
1776
  }
1610
-
1611
1777
  export function forEachSource(handle, fn) {
1612
1778
  return defaultRegistry.forEachSource(handle, fn);
1613
1779
  }
1614
-
1615
1780
  export function onGraphMutation(fn) {
1616
1781
  return defaultRegistry.onGraphMutation(fn);
1617
1782
  }
1618
-
1619
1783
  export function forEachOwned(handle, fn) {
1620
1784
  return defaultRegistry.forEachOwned(handle, fn);
1621
1785
  }
1622
-
1623
1786
  export function ownerOf(handle) {
1624
1787
  return defaultRegistry.ownerOf(handle);
1625
1788
  }
1626
-
1627
1789
  export function nodeId(handle) {
1628
1790
  return defaultRegistry.nodeId(handle);
1629
1791
  }
1630
-
1631
1792
  export function describe(handle) {
1632
1793
  return defaultRegistry.describe(handle);
1633
1794
  }
package/llms.txt CHANGED
@@ -16,6 +16,8 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
16
16
  - **Signal**: root reactive cell. `signal(initial, { equals? })` returns a function. Call it to read (tracked), use `.peek()` to read without tracking, `.set(v)` to notify downstream, `.update(fn)` for read-modify-write, `.subscribe(fn)` for an effect-backed listener.
17
17
  - **Computed**: lazy memoized derivation. `computed(fn, { equals? })`. Cache hits return in O(deps) (version comparison only). Cache misses re-run the body and refresh `evalVersion`. Errors are cached via `FLAG_HAS_ERROR` and re-thrown on every read until a dep changes.
18
18
  - **Effect**: side-effect runner. `effect(fn, { scheduler? })`. Runs immediately on creation, then on any tracked dep change. Returns a dispose function. Optional scheduler defers execution (e.g., to rAF, microtask, custom frame loop).
19
+ - **Box (1.5.0)**: non-callable, allocation-light variants. `signalBox(initial, { equals? })` returns `{ get, set, peek, update, subscribe }`; `computedBox(fn, { equals? })` returns `{ get, peek, subscribe }` (no set/update -- derived). Same `ReactiveNode` and zero-GC read/write path as the callable forms, full interop in one graph (a callable can read `box.get()` and vice versa). Construction is ~1.7x cheaper than the callable (an `Object.create(proto)` handle, not a closure). Built on a shared prototype from the start -- never `setPrototypeOf` (which would deopt the method-call ICs to megamorphic). Exported as registry methods and top-level helpers.
20
+ - **createRoot (1.5.0)**: `createRoot(fn)` runs `fn` in a detached ownership scope and returns `fn`'s value. Effects/computeds created directly in `fn` are NOT adopted by the enclosing owner, so they survive its re-runs/disposal (the caller owns their lifecycle). Both ownership and tracking are detached for `fn`'s direct body; inner effect/computed bodies still establish their own scopes. The escape hatch for lazily spawning a long-lived node from inside a consumer effect (e.g. `lite-query`'s query-watcher) -- without it, the consumer owns the watcher and cascade-disposes it on its next re-run. Mirrors Solid's `createRoot`. The re-attach companion `runWithOwner` is named in the engine as the intended second half and is not yet shipped.
19
21
  - **dispose(api)**: universal disposal. Accepts a signal, computed, or effect dispose handle; idempotent; cross-registry calls are silent no-ops (per-registry `Symbol("node_ptr")` keys the node-identity slot on the returned API function, foreign signals fail the lookup and fall through). Passing an unrelated value is also safe; passing an arbitrary function invokes it (effect-handle contract).
20
22
  - **Batch**: `batch(fn)` defers effect flush until the outermost batch closes. Nestable.
21
23
  - **Untrack**: `untrack(fn)` reads without subscribing.
@@ -50,10 +52,67 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
50
52
 
51
53
  ## Version notes
52
54
 
53
- - **1.3.0** (current): the **pool minor**. Node and link pools become growable
54
- and incrementally populated; the propagation mark phase moves to an intrusive
55
- linked-list stack; a small registry config surface is exposed. **The hot paths
56
- and public callable API are byte-identical to 1.2.2** -- everything here is
55
+ - **1.5.0-alpha** (current): the **API-surface minor**. Two non-callable,
56
+ allocation-light primitives -- `signalBox(initial, opts?)` returning
57
+ `{ get, set, peek, update, subscribe }` and `computedBox(fn, opts?)` returning
58
+ `{ get, peek, subscribe }` -- land alongside the callable `signal` / `computed`,
59
+ plus **`createRoot(fn)`** as the ownership escape hatch. **The callable API, hot
60
+ paths, and `stats()` shape (11 keys) are unchanged from 1.4.0**; this is an
61
+ additive surface, not a second engine. Boxes wrap the same `ReactiveNode` and
62
+ interoperate freely with callables in one graph (verified both directions);
63
+ ownership, batching, glitch-freedom, and introspection apply uniformly, and box
64
+ nodes count in `stats().signals` / `computeds` exactly as callable nodes. Box
65
+ construction is ~1.7x cheaper than the callable (an `Object.create(proto)` handle
66
+ with two own props added in fixed order -- never `setPrototypeOf`, which would
67
+ transition the object to dictionary mode and blow the method-call ICs to
68
+ megamorphic); the read/write hot path stays zero-GC (200k box writes through a
69
+ 256-wide graph: 0 heap growth, 0 pool growths). `createRoot` runs `fn` with
70
+ `currentOwner` and `currentObserver` (and the tracking flag) nulled, so
71
+ effects/computeds created directly in `fn` are not adopted by the enclosing owner
72
+ and survive its re-runs/disposal -- the sanctioned opt-out for lazily spawning a
73
+ long-lived watcher from inside a consumer effect (`lite-query`'s pattern);
74
+ unwrapped, the consumer owns the watcher and cascade-disposes it. Inner
75
+ effect/computed bodies still establish their own scopes; `createRoot` returns
76
+ whatever `fn` returns. The owner/observer split (1.2.0) made `currentOwner` and
77
+ `currentObserver` distinct precisely so ownership could be detached without
78
+ affecting tracking; `createRoot` is the first of the two named primitives
79
+ (`runWithOwner`, the re-attach half, is not yet shipped). The `24-signalbox`
80
+ suite (staged `{skip:true}` since 1.3.0) now runs and passes. **Tests:** 439
81
+ total, 438 pass, 0 fail, **1 skip** (only the architecturally-N/A SSR case in
82
+ `17-reactivity`; the 9 signalBox tests are now active, +6 `createRoot` tests in
83
+ `test/27-create-root_test.mjs`, +3 box-coverage tests). **Coverage:** `Signal.js`
84
+ 100% statements / 97.35% branches / 100% functions / 100% lines; `Watch.js` 100%.
85
+ Drop-in over 1.4.0.
86
+
87
+ - **1.4.0-beta** (drop-in over 1.3.0): the **observability minor**. `stats()` gains three
88
+ cumulative lifecycle counters -- `totalAllocations`, `totalDisposals`,
89
+ `poolGrowths` -- the surface reserved for 1.4.0 in the 1.2.x/1.3.0 notes, now
90
+ delivered. **The hot paths and public callable API are byte-identical to 1.3.0**;
91
+ the counters bump on existing acquire / dispose / pool-grow edges that already
92
+ ran, never on the steady-state read path, so throughput and zero-GC are
93
+ unchanged. The 1.3.0 eager pool default carries forward (`prealloc: "eager"`).
94
+ **`stats()` now returns 11 keys** (the 8 live gauges plus the 3 counters).
95
+ `totalAllocations` counts every node acquired (pool pop OR fresh build);
96
+ `totalDisposals` counts every node returned to the pool, with
97
+ `totalAllocations - totalDisposals === activeNodes` in a quiescent registry;
98
+ `poolGrowths` counts pool-growth chunks (node OR link crossing its ledger) --
99
+ nonzero after warm-up means the initial pool was undersized, 0 means an eager pool
100
+ was sized right. All three are monotonic and reset only by `destroy()`. They are
101
+ exact, not sampled: a consumer sampling `stats()` over time derives allocation
102
+ rate (delta totalAllocations / delta t), pool-reuse ratio
103
+ (1 - poolGrowths*initialCap/totalAllocations), and churn without the engine
104
+ computing rates -- the series lite-devtools 1.2 / lite-studio 1.2 plot. **Tests:**
105
+ 430 total, 420 pass, 0 fail, 10 skip (6 new counter tests in `test/03-pool_test.mjs`
106
+ cover the 11-key shape, the live invariant, poolGrowths firing on growth vs staying
107
+ 0 on a sized eager pool, and destroy() reset). **Coverage:** `Signal.js` 100%
108
+ statements / 98.26% branches / 100% functions / 100% lines; `Watch.js` 100%.
109
+ Drop-in over 1.3.0.
110
+
111
+ - **1.3.0** (drop-in over 1.2.2): the **pool minor**. Node and link pools become
112
+ growable and incrementally populated; the propagation mark phase moves to an
113
+ intrusive linked-list stack (a `nextMark` field); a small registry config surface
114
+ (`prealloc`, `onCapacityExceeded`, `maxFlushPasses`) is exposed. The hot paths and
115
+ public callable API are byte-identical to 1.2.2 -- everything here is
57
116
  pool mechanics, construction-time behavior, and new opt-in config. Steady-state
58
117
  zero-GC is unchanged: after warm-up the pools recycle exactly as before.
59
118
  **`prealloc` (`"eager"` default | `"lazy"`):** `"eager"` constructs the full
@@ -265,7 +324,10 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
265
324
  function signal<T>(initial: T, opts?: { equals?: (a: T, b: T) => boolean }): Signal<T>;
266
325
  function computed<T>(fn: () => T, opts?: { equals?: (a: T, b: T) => boolean }): Computed<T>;
267
326
  function effect(fn: () => void, opts?: { scheduler?: (run: () => void) => void }): Dispose;
268
- function dispose(api: Signal<any> | Computed<any> | Dispose): void;
327
+ function signalBox<T>(initial: T, opts?: { equals?: (a: T, b: T) => boolean }): SignalBox<T>; // 1.5.0
328
+ function computedBox<T>(fn: () => T, opts?: { equals?: (a: T, b: T) => boolean }): ComputedBox<T>; // 1.5.0
329
+ function createRoot<T>(fn: () => T): T; // 1.5.0 -- detached ownership scope; returns fn's value
330
+ function dispose(api: Signal<any> | Computed<any> | SignalBox<any> | ComputedBox<any> | Dispose): void;
269
331
  function batch<T>(fn: () => T): T;
270
332
  function untrack<T>(fn: () => T): T;
271
333
  function isTracking(): boolean;
@@ -304,6 +366,20 @@ interface Computed<T> {
304
366
  subscribe(fn: (value: T) => void): Dispose;
305
367
  }
306
368
 
369
+ interface SignalBox<T> { // 1.5.0 -- non-callable, allocation-light
370
+ get(): T; // tracked read
371
+ set(value: T): void;
372
+ peek(): T; // untracked read
373
+ update(fn: (prev: T) => T): void;
374
+ subscribe(fn: (value: T) => void): Dispose;
375
+ }
376
+
377
+ interface ComputedBox<T> { // 1.5.0
378
+ get(): T; // tracked read
379
+ peek(): T; // untracked read
380
+ subscribe(fn: (value: T) => void): Dispose;
381
+ }
382
+
307
383
  type Dispose = () => void;
308
384
 
309
385
  interface NodeDescriptor { // yielded by forEachObserver / forEachSource / describe
@@ -320,15 +396,18 @@ interface RegistryConfig {
320
396
  onCapacityExceeded?: "throw" | "grow"; // default "throw"; "grow" = chunked refill, ledger doubles, 16x link ceiling
321
397
  }
322
398
 
323
- interface RegistryStats {
399
+ interface RegistryStats { // 11 keys as of 1.4.0
324
400
  signals: number;
325
401
  computeds: number;
326
402
  effects: number;
327
403
  activeLinks: number;
328
404
  pooledLinks: number;
329
- linkPoolCapacity: number;
330
- nodePoolCapacity: number;
331
- activeNodes: number;
405
+ linkPoolCapacity: number; // ledger; doubles under "grow"
406
+ nodePoolCapacity: number; // ledger; doubles under "grow"
407
+ activeNodes: number; // live gauge
408
+ totalAllocations: number; // 1.4.0: cumulative node acquires; reset by destroy()
409
+ totalDisposals: number; // 1.4.0: cumulative node disposals; totalAllocations - totalDisposals === activeNodes
410
+ poolGrowths: number; // 1.4.0: cumulative pool-growth chunks; 0 if eager pool sized right
332
411
  }
333
412
 
334
413
  class CapacityError extends Error {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zakkster/lite-signal",
3
- "version": "1.3.0-rc.0",
3
+ "version": "1.5.0-alpha",
4
4
  "description": "Zero-GC reactive graph. Monomorphic object pool, versioned push-pull propagation, 32-bit modular versioning. Built for hot paths and long-running processes.",
5
5
  "author": "Zahary Shinikchiev <shinikchiev@yahoo.com>",
6
6
  "license": "MIT",