@solidjs/signals 2.0.0-rc.7 → 2.0.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/dist/dev-shared.js +6357 -0
  2. package/dist/dev.attribution.js +2485 -0
  3. package/dist/dev.js +2851 -7027
  4. package/dist/observe/affects.js +129 -0
  5. package/dist/observe/attribution.js +7 -0
  6. package/dist/observe/boundaries.js +641 -0
  7. package/dist/observe/core/action.js +177 -0
  8. package/dist/observe/core/async.js +846 -0
  9. package/dist/observe/core/attribution-costs.js +66 -0
  10. package/dist/observe/core/attribution-feedback.js +282 -0
  11. package/dist/observe/core/attribution-hooks.js +82 -0
  12. package/dist/observe/core/attribution-queries.js +28 -0
  13. package/dist/observe/core/attribution.js +2095 -0
  14. package/dist/observe/core/constants.js +248 -0
  15. package/dist/{types-cjs/core/context.d.cts → observe/core/context.js} +37 -12
  16. package/dist/observe/core/core.js +1789 -0
  17. package/dist/observe/core/dev.js +293 -0
  18. package/dist/observe/core/effect.js +195 -0
  19. package/dist/observe/core/error-hooks.js +71 -0
  20. package/dist/observe/core/error.js +80 -0
  21. package/dist/observe/core/external.js +98 -0
  22. package/dist/observe/core/graph.js +155 -0
  23. package/dist/observe/core/heap.js +147 -0
  24. package/dist/observe/core/invariants.js +45 -0
  25. package/dist/observe/core/lanes.js +205 -0
  26. package/dist/observe/core/optimistic.js +585 -0
  27. package/dist/observe/core/owner.js +322 -0
  28. package/dist/observe/core/scheduler.js +1428 -0
  29. package/dist/observe/core/verdict.js +669 -0
  30. package/dist/observe/index.js +59 -0
  31. package/dist/observe/map.js +484 -0
  32. package/dist/{types-cjs/signals.d.cts → observe/signals.js} +311 -317
  33. package/dist/observe/store/index.js +40 -0
  34. package/dist/observe/store/next/optimistic.js +660 -0
  35. package/dist/observe/store/next/projection.js +255 -0
  36. package/dist/observe/store/next/reconcile.js +375 -0
  37. package/dist/observe/store/next/store.js +2327 -0
  38. package/dist/observe/store/next/target.js +51 -0
  39. package/dist/observe/store/store.js +325 -0
  40. package/dist/observe/store/storePath.js +103 -0
  41. package/dist/observe/store/utils.js +1023 -0
  42. package/dist/prod/attribution.js +41 -0
  43. package/dist/prod/boundaries.js +128 -76
  44. package/dist/prod/core/action.js +65 -37
  45. package/dist/prod/core/async.js +324 -172
  46. package/dist/prod/core/constants.js +57 -1
  47. package/dist/prod/core/context.js +3 -3
  48. package/dist/prod/core/core.js +1003 -364
  49. package/dist/prod/core/dev.js +17 -1
  50. package/dist/prod/core/effect.js +76 -42
  51. package/dist/prod/core/error-hooks.js +71 -0
  52. package/dist/prod/core/external.js +4 -4
  53. package/dist/prod/core/graph.js +37 -37
  54. package/dist/prod/core/heap.js +61 -56
  55. package/dist/prod/core/lanes.js +107 -63
  56. package/dist/prod/core/optimistic.js +374 -93
  57. package/dist/prod/core/owner.js +62 -46
  58. package/dist/prod/core/scheduler.js +653 -286
  59. package/dist/prod/core/verdict.js +245 -127
  60. package/dist/prod/index.js +15 -5
  61. package/dist/prod/map.js +292 -141
  62. package/dist/prod/signals.js +29 -16
  63. package/dist/prod/store/next/optimistic.js +77 -55
  64. package/dist/prod/store/next/projection.js +31 -20
  65. package/dist/prod/store/next/reconcile.js +87 -84
  66. package/dist/prod/store/next/store.js +718 -401
  67. package/dist/prod/store/next/target.js +32 -10
  68. package/dist/prod/store/store.js +12 -14
  69. package/dist/prod/store/utils.js +950 -130
  70. package/dist/types/attribution.d.ts +20 -0
  71. package/dist/types/attribution.prod.d.ts +22 -0
  72. package/dist/types/boundaries.d.ts +10 -1
  73. package/dist/types/core/action.d.ts +12 -5
  74. package/dist/types/core/async.d.ts +1 -1
  75. package/dist/types/core/attribution-costs.d.ts +35 -0
  76. package/dist/types/core/attribution-feedback.d.ts +133 -0
  77. package/dist/types/core/attribution-hooks.d.ts +147 -9
  78. package/dist/types/core/attribution-queries.d.ts +10 -0
  79. package/dist/types/core/attribution.d.ts +216 -182
  80. package/dist/types/core/constants.d.ts +56 -0
  81. package/dist/types/core/core.d.ts +190 -2
  82. package/dist/types/core/dev.d.ts +246 -28
  83. package/dist/types/core/effect.d.ts +8 -1
  84. package/dist/types/core/error-hooks.d.ts +71 -0
  85. package/dist/types/core/index.d.ts +4 -1
  86. package/dist/types/core/invariants.d.ts +4 -0
  87. package/dist/types/core/lanes.d.ts +39 -5
  88. package/dist/types/core/scheduler.d.ts +153 -0
  89. package/dist/types/core/types.d.ts +32 -9
  90. package/dist/types/index.d.ts +10 -3
  91. package/dist/types/map.d.ts +2 -0
  92. package/dist/types/signals.d.ts +8 -0
  93. package/dist/types/store/index.d.ts +2 -0
  94. package/dist/types/store/next/optimistic.d.ts +1 -1
  95. package/dist/types/store/next/store.d.ts +11 -5
  96. package/dist/types/store/next/target.d.ts +37 -10
  97. package/dist/types/store/utils.d.ts +178 -0
  98. package/package.json +21 -17
  99. package/dist/node.cjs +0 -10541
  100. package/dist/node.dev.cjs +0 -13724
  101. package/dist/types-cjs/affects.d.cts +0 -47
  102. package/dist/types-cjs/boundaries.d.cts +0 -175
  103. package/dist/types-cjs/core/action.d.cts +0 -64
  104. package/dist/types-cjs/core/async.d.cts +0 -23
  105. package/dist/types-cjs/core/attribution-hooks.d.cts +0 -127
  106. package/dist/types-cjs/core/attribution.d.cts +0 -495
  107. package/dist/types-cjs/core/constants.d.cts +0 -159
  108. package/dist/types-cjs/core/core.d.cts +0 -185
  109. package/dist/types-cjs/core/dev.d.cts +0 -136
  110. package/dist/types-cjs/core/effect.d.cts +0 -30
  111. package/dist/types-cjs/core/error.d.cts +0 -56
  112. package/dist/types-cjs/core/external.d.cts +0 -15
  113. package/dist/types-cjs/core/graph.d.cts +0 -28
  114. package/dist/types-cjs/core/heap.d.cts +0 -24
  115. package/dist/types-cjs/core/index.d.cts +0 -13
  116. package/dist/types-cjs/core/invariants.d.cts +0 -59
  117. package/dist/types-cjs/core/lanes.d.cts +0 -54
  118. package/dist/types-cjs/core/optimistic.d.cts +0 -6
  119. package/dist/types-cjs/core/owner.d.cts +0 -124
  120. package/dist/types-cjs/core/scheduler.d.cts +0 -236
  121. package/dist/types-cjs/core/types.d.cts +0 -204
  122. package/dist/types-cjs/core/verdict.d.cts +0 -2
  123. package/dist/types-cjs/index.d.cts +0 -10
  124. package/dist/types-cjs/map.d.cts +0 -69
  125. package/dist/types-cjs/package.json +0 -3
  126. package/dist/types-cjs/store/index.d.cts +0 -18
  127. package/dist/types-cjs/store/next/optimistic.d.cts +0 -25
  128. package/dist/types-cjs/store/next/projection.d.cts +0 -8
  129. package/dist/types-cjs/store/next/reconcile.d.cts +0 -10
  130. package/dist/types-cjs/store/next/store.d.cts +0 -121
  131. package/dist/types-cjs/store/next/target.d.cts +0 -166
  132. package/dist/types-cjs/store/store.d.cts +0 -143
  133. package/dist/types-cjs/store/storePath.d.cts +0 -58
  134. package/dist/types-cjs/store/utils.d.cts +0 -74
@@ -0,0 +1,2327 @@
1
+ import { attrHooks } from "../../core/attribution-hooks.js";
2
+
3
+ import { unwrapOverride, $REFRESH, CONFIG_CHILDREN_FORBIDDEN, CONFIG_OWNED_WRITE, NOT_PENDING, CONFIG_OPTIMISTIC, STATUS_UNINITIALIZED, STATUS_ERROR, CONFIG_AUTHORITATIVE_READ } from "../../core/constants.js";
4
+
5
+ import { setSlotUnobserved, setSignal, isEqual, read, hasActiveOverride, pendingCheckActive, visibleOverride, latestReadActive, readNodeFast, READ_SLOW, signal, unlinkFirewallChild, ext, ownsHold, setLatestReadActive, prepareComputed, slotSignal, serve, stale, recordStaleReplay, enterStagedRead, context } from "../../core/core.js";
6
+
7
+ import { projectionWriteActive, setProjectionWriteActive, activeTransition, schedule, currentTransition, deferSlotRelease, setStoreCommitHook } from "../../core/scheduler.js";
8
+
9
+ import "../../core/invariants.js";
10
+
11
+ import { getOwner, getObserver } from "../../core/owner.js";
12
+
13
+ import { registerGraph } from "../../core/dev.js";
14
+
15
+ import { $TARGET, isWrappable, markRawIngest, $PROXY, getWriteOverride, markRawOne, witnessAffectsMark, $TRACK, affectsScopesLive, inheritAffectsMarks, $AFFECTS, rawValuesUsed, isRawValue, setNextAffectsNodeResolver } from "../store.js";
16
+
17
+ import { lookupTarget, optHooks, storeNextLookup, $OWNER, isOwned, markDescendants, devAssertNeverUserMutation } from "./target.js";
18
+
19
+ /**
20
+ * Store rewrite — increment 2: plain deep stores with pending-backing writes.
21
+ * Contract: INTERNALS-STORE-STATE.md.
22
+ *
23
+ * Write model (RUL-1, unified): the first draft write to a target creates its
24
+ * pending backing `pb` — a descriptor-preserving CoW clone. The draft mutates
25
+ * `pb` natively (array methods, defineProperty, deletes all just work).
26
+ * Reads: drafts and owner-context reads see `pb`; context-free reads see the
27
+ * committed `b` until flush. At flush commit (core's storeCommitHook), each
28
+ * written target folds: diff old `b` vs new backing notifies exactly the
29
+ * changed keys through equality-gated nodes, then `b` becomes the new
30
+ * backing. Setter return-value replacement parks the UNOWNED incoming object
31
+ * in `pb` — adoption: fold swaps it in, ownership resets (2026-08-16c).
32
+ *
33
+ * Nodes carry no pending state — they are pure subscription points; `pb` is
34
+ * the pending home. Laziness: a written target with no subscriptions folds as
35
+ * a pointer swap with zero node work.
36
+ */
37
+ // ---------------------------------------------------------------------------
38
+ // wrap / dedupe
39
+ /** Pre-shaped constructor for OBJECT proxy targets: V8 tips a bare `{}` into
40
+ * dictionary mode once ~19 named properties are assigned onto it (the #3044
41
+ * `ovl`/`del` fields crossed that line — every trap's field read became a
42
+ * hash lookup, a 15% deep-dbmon tick regression). Declaring every field in a
43
+ * constructor pre-allocates in-object slots so the map stays fast, with
44
+ * headroom for future fields. The prototype is reset to `Object.prototype`
45
+ * so proxy-forwarded semantics (getPrototypeOf, constructor) are exactly a
46
+ * plain object's. Array targets keep the bare-`[]` path — they must carry
47
+ * the array exotic class for `Array.isArray(proxy)`.
48
+ *
49
+ * ARRAY SHAPE RULE: arrays normalize their named properties to dictionary
50
+ * mode as the count grows (V8 13.x: counts ≡ 0 mod 3 from 18 up), so the
51
+ * target's named field count is capped at 20 — any future write-side state
52
+ * beyond `wk` must ride an extension object (see target.ts), never new
53
+ * named fields here. */
54
+ function TargetShape() {
55
+ this.v = undefined;
56
+ this.ch = undefined;
57
+ this.pb = undefined;
58
+ this.n = undefined;
59
+ this.h = undefined;
60
+ this.k = undefined;
61
+ this.dk = undefined;
62
+ this.u = undefined;
63
+ this.pk = undefined;
64
+ this.px = undefined;
65
+ this.d = undefined;
66
+ this.a = undefined;
67
+ this.sc = undefined;
68
+ this.kc = undefined;
69
+ this.nc = undefined;
70
+ this.ab = undefined;
71
+ this.fam = undefined;
72
+ this.s = undefined;
73
+ this.ovl = undefined;
74
+ this.del = undefined;
75
+ this.wk = undefined;
76
+ this.hv = undefined;
77
+ this.ht = undefined;
78
+ }
79
+
80
+ TargetShape.prototype = Object.prototype;
81
+
82
+ function createTarget(e, t, n, r = t?.fam ?? null) {
83
+ // The proxy target carries the array exotic class when the value is an
84
+ // array, so Array.isArray(proxy) is true; the fields live on it directly.
85
+ // Direct field assignment in one fixed order (no Object.assign literal
86
+ // copy): every target shares a hidden-class transition chain — createTarget
87
+ // was the #2 store cost in the uibench creation profile.
88
+ const i = Array.isArray(e) ? [] : new TargetShape;
89
+ i.v = e;
90
+ // Chained-backing flag (backing IS another store's proxy, §7b) — cached so
91
+ // the hot read path never does a per-read symbol lookup on the backing.
92
+ i.ch = e[$TARGET] !== undefined;
93
+ i.pb = null;
94
+ i.n = null;
95
+ i.h = null;
96
+ i.k = null;
97
+ i.dk = null;
98
+ i.wk = null;
99
+ i.u = t;
100
+ i.pk = n;
101
+ i.px = null;
102
+ i.d = false;
103
+ i.a = false;
104
+ i.sc = 0;
105
+ i.kc = 0;
106
+ i.nc = 0;
107
+ i.ab = null;
108
+ i.fam = r;
109
+ i.s = false;
110
+ i.ovl = false;
111
+ i.del = null;
112
+ i.hv = null;
113
+ i.ht = null;
114
+ i.px = new Proxy(i, traps);
115
+ // Legacy interop: shared machinery (affects walks, wrap dedupe) reads the
116
+ // proxy off looked-up targets as a field.
117
+ i[$PROXY] = i.px;
118
+ (r?.map ?? storeNextLookup).set(e, i);
119
+ return i;
120
+ }
121
+
122
+ function wrapNext(e, t = null, n = null, r = t?.fam ?? null) {
123
+ // markRaw'd values never wrap through ANY store (R42; sticky raw-marking
124
+ // is one half of the never-both-wrapped-and-raw invariant, RUL-12).
125
+ if (rawValuesUsed && isRawValue(e)) return e;
126
+ const i = lookupTarget(e, r);
127
+ if (i !== undefined) return i.px;
128
+ const o = e[$TARGET];
129
+ if (o !== undefined && o.px === e) {
130
+ // Foreign-family proxies re-wrap into THIS family (writes stay isolated);
131
+ // same-family and plain-store proxies pass through.
132
+ if (r === null || o.fam === r) return e;
133
+ return createTarget(e, t, n, r).px;
134
+ }
135
+ return createTarget(e, t, n, r).px;
136
+ }
137
+
138
+ /** Unwrap our own proxies to their current backing; leave everything else. */ function unwrapValue(e) {
139
+ if (e == null || typeof e !== "object") return e;
140
+ const t = e[$TARGET];
141
+ if (t !== undefined && t.px === e && t.v !== undefined) {
142
+ // A draft escaping into other storage must be a REAL container that
143
+ // becomes this target's committed backing at fold (the shared-raw
144
+ // contract) — a prototype overlay is neither.
145
+ if (t.ovl) materializePB(t);
146
+ return t.pb ?? t.v;
147
+ }
148
+ return e;
149
+ }
150
+
151
+ // ---------------------------------------------------------------------------
152
+ // nodes: pure subscription points (values used only for equality gating)
153
+ // Shared slot-node equality (create-floor diet): ONE function for every
154
+ // store node — `this` is the node (method-call convention at every _equals
155
+ // site), `_host` is the baked-in target backref. Logical-slot equality:
156
+ // values resolving to the same child target are the same slot
157
+ // (privatization/adoption swap raw identity without changing the logical
158
+ // value — only changed leaves notify, R9).
159
+ const slotNodeEquals = function(e, t) {
160
+ return isEqual(e, t) || sameLogicalSlot(this.dn, e, t);
161
+ };
162
+
163
+ // Shared slot-node unobserved handler (create-floor diet): registered once;
164
+ // the core sweep dispatches CONFIG_SLOT_NODE nodes here instead of holding a
165
+ // per-node closure in a per-node NodeExtension.
166
+ setSlotUnobserved(e => {
167
+ // A live affects() mark keeps the node addressable (sweep parity).
168
+ if (e.o?.t) return;
169
+ // An active override or a staged write is state only the node holds (an
170
+ // optimistic signal keeps its override whether or not anything reads it —
171
+ // store parity, posture-store-parity S7): defer the release to the flush
172
+ // that resolves it (the scheduler's transient-node sweep).
173
+ if (hasActiveOverride(e) || e._e !== NOT_PENDING) return deferSlotRelease(e);
174
+ const t = e.dn;
175
+ const n = e.En;
176
+ if (t.n && t.n[n] === e) {
177
+ delete t.n[n];
178
+ t.nc--;
179
+ // Projection leaves also leave the firewall child chain (#3351): a
180
+ // dropped node is unreachable through the store — a fresh read makes a
181
+ // fresh node — so the chain would only retain it and its last value.
182
+ unlinkFirewallChild(e);
183
+ }
184
+ });
185
+
186
+ function getNode(e, t, n,
187
+ // First-read dedupe (create-floor slice 2): the get trap probes
188
+ // accessor-ness right before creating the node — pass the verdict through
189
+ // so creation skips the second descriptor scan. -1 = unknown (other
190
+ // callers), 0/1 = probed.
191
+ r = -1) {
192
+ const i = e.n ??= Object.create(null);
193
+ let o = i[t];
194
+ if (o === undefined) {
195
+ // Born holding (#3330 store twin): a key first read while a live
196
+ // transaction holds an ADOPTION on this target (adoptPB's `ht`) is
197
+ // created as if it had existed when the hold was notified — the adopted
198
+ // value already swapped into `v`, so committed is the held view
199
+ // `hv[key]` and the adopted `v[key]` is staged under the transaction
200
+ // (stageHeldKey). Its held-adoption notification (stageHeldAdoptions)
201
+ // ran before the node existed and the drain has nothing left to say.
202
+ // Without this the node was born from whichever view its first reader
203
+ // saw and never learned the other. Two kinds of hold, one rule (#3336):
204
+ // - a held FOLD (pb): a setter's write to an unobserved key landed only
205
+ // in the pending backing; committed is `v[key]`, staged is `pb[key]`
206
+ // (undefined for a deleted key);
207
+ // - a held ADOPTION (ht): the adopted value already swapped into `v`;
208
+ // committed is the held view `hv[key]`, staged is `v[key]`.
209
+ const l = heldFoldTransition(e);
210
+ let f = heldAdoptionTransition(e);
211
+ if (f !== null) n = e.hv[t]; else if ((f = l) !== null) n = e.v[t];
212
+ // Create-floor diet: slotSignal bakes the whole node into one literal —
213
+ // no options object, no equals/unobserved closures, no NodeExtension,
214
+ // no post-construction expandos (acc + the wrap cache px/pxv are
215
+ // pre-shaped fields: the proxy last served for this key and the raw it
216
+ // wrapped — one pointer compare replaces the per-read WeakMap lookup in
217
+ // wrapNext). ownedWrite rides the literal's config: the setter carries
218
+ // the owned-scope write guard; node-level setSignals are internal
219
+ // notification machinery. Projection nodes carry the projection
220
+ // computed as their firewall: reads through them link the derive's
221
+ // status/lifecycle (§7b).
222
+ const s = o = slotSignal(n, slotNodeEquals, e, t,
223
+ // Accessor-ness resolved ONCE per node (no per-object descriptor
224
+ // scan on reads): accessor keys serve through Reflect.get with the
225
+ // proxy receiver.
226
+ r === -1 ? isOwnAccessor(e.pb ?? e.v, t) : r === 1, e.fam?.node ?? undefined);
227
+ // Attribution-only: name store property nodes by path segment so
228
+ // attribution chains and wide-scope warnings read "store.todos", not
229
+ // "signal". Gated on the engine being installed — node creation is
230
+ // the hottest store path, and the disabled cost must stay one null
231
+ // check (nodes created before enable() stay generically named).
232
+ if (attrHooks !== null) {
233
+ s._name = "store." + String(t);
234
+ stampNodeOwner(s, e);
235
+ }
236
+ // Optimistic families: arm the override slot — setSignal routes armed
237
+ // nodes through the core engine (lanes, ownership, reverts all native).
238
+ if (e.fam?.opt) {
239
+ ext(s).Ne = NOT_PENDING;
240
+ s.C |= CONFIG_OPTIMISTIC;
241
+ }
242
+ // A node born inside a live mark's identity scope inherits the mark
243
+ // (the declaration walk could only cover nodes existing then).
244
+ if (t !== $AFFECTS && affectsScopesLive()) inheritAffectsMarks(s, e.v, t);
245
+ if (f !== null) stageHeldKey(s, l !== null ? e.del !== null && e.del.has(t) ? undefined : e.pb[t] : e.v[t], f);
246
+ i[t] = o;
247
+ e.nc++;
248
+ markDescendants(e);
249
+ }
250
+ return o;
251
+ }
252
+
253
+ /** The live transaction holding an adoption on `target` (adoptPB's `ht`;
254
+ * a latest()-pull PLAIN_HOLD is not a transaction), else null. */ function heldAdoptionTransition(e) {
255
+ if (e.ht === null || e.ht === PLAIN_HOLD || heldMaskView(e) === null) return null;
256
+ const t = currentTransition(e.ht);
257
+ return t.yt === false ? t : null;
258
+ }
259
+
260
+ /**
261
+ * Materialization under a hold. A node created by a first tracked read while
262
+ * a transaction holds this target must carry the same state a node that
263
+ * existed when the hold was notified carries — a transaction-stamped
264
+ * `_pendingValue` that core read() serves by ITS rules (a stale render reader
265
+ * of a foreign transaction's write sees committed, an owner-context reader
266
+ * inside the transaction sees the write) — or the reader's answer depends on
267
+ * whether some OTHER reader had materialized the key before the hold. Stage
268
+ * `nv` (the held value for the key — see getNode for which view it comes
269
+ * from) as the holding transaction's write — directly, not through
270
+ * setSignal: it is not a new write (it staged with the adoption's batch) and
271
+ * it walks no subscriber (the node has none yet). Transition-stamped now, as
272
+ * `runFolded` does — no parked-flush pass will stamp it.
273
+ */
274
+ /** The live transaction holding `target`'s pending backing (the #3089
275
+ * write-time stamp, resolved through merges), else null. */ function liveFoldTransition(e) {
276
+ if (e.pb === null) return null;
277
+ const t = foldBatches.get(e);
278
+ if (t === undefined) return null;
279
+ const n = currentTransition(t);
280
+ return n.yt === false ? n : null;
281
+ }
282
+
283
+ /** liveFoldTransition for node materialization (stageHeldKey). Inside the
284
+ * draft the backing is the setter's working copy, not a flushed hold — its
285
+ * nodes take their writes at setter exit (notifyWrites). Optimistic families
286
+ * hold at the backing: tentative writes are node overrides over a discarded
287
+ * clone, and a truth-staged landing is masked from ordinary readers by
288
+ * heldTruthMasked — neither is a plain staged write to mirror. Chained
289
+ * backings serve the inner store's live value, never a node value. */ function heldFoldTransition(e) {
290
+ if (e.ch || e.fam?.opt === true || inDraft(e)) return null;
291
+ return liveFoldTransition(e);
292
+ }
293
+
294
+ /**
295
+ * Rule 1 at the backing, the hold half (core serve()'s stale-of-foreign and
296
+ * A29 arms, for a container instead of a node): given the transaction
297
+ * holding what a reader `c` (a pass; callers serve context-free readers the
298
+ * committed container themselves) is about to be served, is the STAGED
299
+ * container its to see? Its own hold, or none — yes. A foreign hold — a
300
+ * stale pass (render effect) keeps the committed frame and is recorded for
301
+ * replay at the hold's commit (recordStaleReplay, A15 / A26); a deriving
302
+ * pass takes the staged world and enters the transaction (enterStagedRead,
303
+ * A29). Shared by both hold kinds: a setter's fold (committed `v`, staged
304
+ * `pb`, the write-time stamp) and an adoption under a transaction
305
+ * (committed = the held view `hv`, staged = the adopted `v`, #3074).
306
+ */ function holdVisible(e, t) {
307
+ if (e === null || ownsHold(e)) return true;
308
+ if (stale) {
309
+ recordStaleReplay(e, t);
310
+ return false;
311
+ }
312
+ enterStagedRead(null, e);
313
+ return true;
314
+ }
315
+
316
+ function stageHeldKey(e, t, n) {
317
+ if (slotNodeEquals.call(e, e.Ae, t)) return;
318
+ e._e = t;
319
+ e.Te = n;
320
+ n.sn.push(e);
321
+ }
322
+
323
+ function sameLogicalSlot(e, t, n) {
324
+ if (t === null || typeof t !== "object" || n === null || typeof n !== "object") return false;
325
+ const r = lookupTarget(t, e.fam);
326
+ return r !== undefined && r === lookupTarget(n, e.fam);
327
+ }
328
+
329
+ /**
330
+ * Observe-tier: the owner each store root was created under. The proxy
331
+ * cannot carry `_owner` itself (`registerGraph`'s stamp is swallowed by the
332
+ * set trap outside a draft), so the root target keys it here and the store's
333
+ * nodes copy it into `_owner` as they are created — an `OBSERVE.exclude`d
334
+ * panel's store nodes are then excluded subjects, exactly like its signals.
335
+ * Both ends are gated with the naming on the engine being installed: node
336
+ * creation is the hottest store path, store creation is next, and the
337
+ * disabled cost of each stays one null check. A store created before
338
+ * `enable()` therefore has no recorded owner and its nodes are never excluded
339
+ * subjects — the same boundary the naming draws; a panel enables first.
340
+ */ const storeOwners = new WeakMap;
341
+
342
+ function storeRootOwner(e) {
343
+ let t = e;
344
+ while (t.u !== null) t = t.u;
345
+ return storeOwners.get(t);
346
+ }
347
+
348
+ function stampNodeOwner(e, t) {
349
+ e.nt = storeRootOwner(t) ?? null;
350
+ }
351
+
352
+ function getHasNode(e, t, n) {
353
+ const r = e.h ??= Object.create(null);
354
+ let i = r[t];
355
+ if (i === undefined) {
356
+ const o = i = signal(n, {
357
+ equals: isEqual,
358
+ unobserved() {
359
+ if (o.o?.t) return;
360
+ // The structural twin of the value slot's rule (setSlotUnobserved,
361
+ // S7): an optimistic add/delete lives on this presence node as its
362
+ // override — releasing it with the override on would let `in`,
363
+ // `Object.keys` and descriptors fall back to committed structure
364
+ // while the action is live. Defer to the flush that resolves it.
365
+ if (hasActiveOverride(o) || o._e !== NOT_PENDING) return deferSlotRelease(o);
366
+ if (e.h && e.h[t] === o) {
367
+ delete e.h[t];
368
+ unlinkFirewallChild(o);
369
+ }
370
+ }
371
+ }, e.fam?.node ?? undefined);
372
+ o.C |= CONFIG_OWNED_WRITE;
373
+ if (attrHooks !== null) stampNodeOwner(o, e);
374
+ if (e.fam?.opt) {
375
+ ext(o).Ne = NOT_PENDING;
376
+ o.C |= CONFIG_OPTIMISTIC;
377
+ }
378
+ if (affectsScopesLive()) inheritAffectsMarks(o, e.v, t);
379
+ r[t] = i;
380
+ markDescendants(e);
381
+ }
382
+ return i;
383
+ }
384
+
385
+ function getKeySetNode(e) {
386
+ let t = e.k;
387
+ if (t === null) {
388
+ const n = t = signal(0, {
389
+ equals: false,
390
+ unobserved() {
391
+ if (e.k === n) {
392
+ e.k = null;
393
+ unlinkFirewallChild(n);
394
+ }
395
+ }
396
+ }, e.fam?.node ?? undefined);
397
+ n.C |= CONFIG_OWNED_WRITE;
398
+ if (attrHooks !== null) stampNodeOwner(n, e);
399
+ if (e.fam?.opt) {
400
+ ext(n).Ne = NOT_PENDING;
401
+ n.C |= CONFIG_OPTIMISTIC;
402
+ }
403
+ e.k = t;
404
+ markDescendants(e);
405
+ }
406
+ return t;
407
+ }
408
+
409
+ function getDeepNode(e) {
410
+ let t = e.dk;
411
+ if (t === null) {
412
+ const n = t = signal(0, {
413
+ equals: false,
414
+ unobserved() {
415
+ if (e.dk === n) {
416
+ e.dk = null;
417
+ unlinkFirewallChild(n);
418
+ }
419
+ }
420
+ }, e.fam?.node ?? undefined);
421
+ n.C |= CONFIG_OWNED_WRITE;
422
+ if (attrHooks !== null) stampNodeOwner(n, e);
423
+ if (e.fam?.opt) {
424
+ ext(n).Ne = NOT_PENDING;
425
+ n.C |= CONFIG_OPTIMISTIC;
426
+ }
427
+ if (affectsScopesLive()) inheritAffectsMarks(n, e.v, $TRACK);
428
+ e.dk = t;
429
+ markDescendants(e);
430
+ }
431
+ return t;
432
+ }
433
+
434
+ /** Deep-witness bump: any value/shape change on a record with a live deep()
435
+ * subscriber notifies it. One null check when unused. */ function bumpDeep(e) {
436
+ if (e.dk !== null) setSignal(e.dk, 1);
437
+ }
438
+
439
+ // ---------------------------------------------------------------------------
440
+ // pending backing + fold (the single mutation point)
441
+ /** target → committed backing at batch start (the fold diff's old side). */ const foldOlds = new Map;
442
+
443
+ let hookInstalled = false;
444
+
445
+ /** Shallow-clone `source` as a backing OWNED by `t` (stamped `$OWNER`, see
446
+ * target.ts). Callers always pass their own committed backing as `source`. */ function cloneRaw(e, t) {
447
+ // Plain-data fast path (#3360): a scanned `Object.prototype` container
448
+ // whose own keys are all enumerable data clones by spread — the same
449
+ // result as the descriptor walk below (own enumerable string+symbol keys,
450
+ // normalized writable+configurable), at ~1/50th the cost.
451
+ t.sc || scanAccessorsOnce(t);
452
+ if (t.sc === 2) {
453
+ const n = {
454
+ ...e
455
+ };
456
+ n[$OWNER] = t;
457
+ return n;
458
+ }
459
+ // Descriptor-preserving shallow clone (R29: installed getters stay live;
460
+ // ruled 2026-08-17: frozen sources clone unfrozen — theirs stays frozen).
461
+ // Data descriptors normalize to writable+configurable (the clone is OURS to
462
+ // mutate — R51's "source-non-configurable is writable through the store");
463
+ // enumerability and accessors are preserved. The scan doubles as the
464
+ // accessor-flag detector (free — we're enumerating descriptors anyway).
465
+ const n = Object.getOwnPropertyDescriptors(e);
466
+ for (const r of Reflect.ownKeys(n)) {
467
+ const i = n[r];
468
+ if (r === "length" && Array.isArray(e)) continue;
469
+ i.configurable = true;
470
+ if (!i.get && !i.set) i.writable = true; else t.a = true;
471
+ }
472
+ const r = Array.isArray(e) ? Object.defineProperties([], n) : Object.create(Object.getPrototypeOf(e), n);
473
+ r[$OWNER] = t;
474
+ return r;
475
+ }
476
+
477
+ /** Copy own `key` from `from` onto `to`. A plain data slot (enumerable,
478
+ * writable, configurable, no accessor) is a bare assignment — the common case
479
+ * and the cheap one; anything else goes through defineProperty so accessors
480
+ * and attribute flags survive the copy. */ function copyOwn(e, t, n) {
481
+ const r = Object.getOwnPropertyDescriptor(t, n);
482
+ if (r.get || r.set || !r.enumerable || !r.writable || !r.configurable) Object.defineProperty(e, n, r); else e[n] = r.value;
483
+ }
484
+
485
+ /** One-time own-accessor scan (Annex-B probes, no descriptor allocation);
486
+ * returns true when the container is plain data (overlay-safe). Also grades
487
+ * the container for the plain-data fast paths (`sc` = 2): `Object.prototype`
488
+ * and every own key an enumerable data property — what a spread copies
489
+ * exactly and what a bare assignment lands exactly. */ function scanAccessorsOnce(e) {
490
+ const t = e.v;
491
+ const n = Reflect.ownKeys(t);
492
+ let r = Object.getPrototypeOf(t) === Object.prototype;
493
+ for (const i of n) {
494
+ // Own keys shadow prototype accessors, so the lookups are exact here.
495
+ if (lookupGetter.call(t, i) !== undefined || lookupSetter.call(t, i) !== undefined) {
496
+ e.a = true;
497
+ r = false;
498
+ break;
499
+ }
500
+ if (r && !propertyIsEnumerable.call(t, i)) r = false;
501
+ }
502
+ e.sc = r ? 2 : 1;
503
+ e.kc = n.length;
504
+ return !e.a;
505
+ }
506
+
507
+ /** Own-key count above which a draft opens as a prototype overlay rather
508
+ * than a clone (#3360). Below it a spread clone of a plain container is
509
+ * cheaper than the overlay's `Object.create` (V8 converts the committed
510
+ * backing into a prototype, and every later flatten writes into that
511
+ * prototype); above it the clone's O(keys) copy dominates (#3044). */ const OVERLAY_MIN_KEYS = 32;
512
+
513
+ /** Downgrade a prototype-overlay pending backing to the clone path: builds
514
+ * the real container (committed + overlay writes − deletes) that fold will
515
+ * SWAP in as the committed backing, exactly as if the draft had started on
516
+ * the clone path. Consumers that need a complete container (reconcile's
517
+ * diff walks, drafts escaping into other storage) call this. */ function materializePB(e) {
518
+ if (!e.ovl) return;
519
+ const t = e.pb;
520
+ const n = cloneRaw(e.v, e);
521
+ for (const e of Reflect.ownKeys(t)) copyOwn(n, t, e);
522
+ if (e.del !== null) {
523
+ for (const t of e.del) delete n[t];
524
+ e.del = null;
525
+ }
526
+ e.pb = n;
527
+ e.ovl = false;
528
+ }
529
+
530
+ function ensurePB(e) {
531
+ let t = e.pb;
532
+ // Truth-staged backing hand-off (#3164 fold): a TENTATIVE draft opening on
533
+ // a target whose pending backing is truth-staged (a landing folded into a
534
+ // retaining transaction — it carries a foldBatches stamp) must not share
535
+ // the container. Tentative writes would pollute staged truth, and the
536
+ // tentative discard (notifyOptimisticWrites nulls pb) would destroy the
537
+ // landing. Park the staged backing and open a fresh draft seeded from the
538
+ // optimistic view below; the tentative discard restores it. The
539
+ // tentativePBs guard scopes this to draft OPEN: the draft's own backing
540
+ // (foldBatches-stamped by its first write when an action's transition is
541
+ // ambient) must not be parked by its own later writes.
542
+ if (t !== null && !tentativePBs.has(t) && e.fam?.opt === true && !projectionWriteActive && !getWriteOverride() && foldBatches.has(e)) {
543
+ stagedTruthPB.set(e, t);
544
+ t = e.pb = null;
545
+ }
546
+ if (activeTransition !== null) foldBatches.set(e, activeTransition);
547
+ if (t === null) {
548
+ // Prototype-chain overlay (#3044): plain-data non-array containers open
549
+ // drafts in O(1) — own keys are the writes, reads fall through to
550
+ // committed. Projection and derived-store families take it too (#3352:
551
+ // a derive touching one root key of a wide keyed record paid an
552
+ // O(keys) clone per recompute). Everything else keeps the descriptor
553
+ // clone: arrays (splice/length semantics), OPTIMISTIC families (the
554
+ // view-seeding below writes and deletes on the draft container, and the
555
+ // tentative discard/truth-park hand whole backings around), chained
556
+ // backings (the committed layer is another store's proxy — an overlay
557
+ // would route every read-through into its traps), accessor containers
558
+ // (live getters).
559
+ // The overlay pays off only for a WIDE container over an OWNED committed
560
+ // backing (#3360). Narrow containers clone cheaper than they overlay (a
561
+ // spread is a fast-path copy; `Object.create` turns the backing into a
562
+ // V8 prototype and every later flatten writes into that prototype). An
563
+ // unowned backing has to be privatized (cloned) at commit anyway, so an
564
+ // overlay there would cost the create PLUS the clone PLUS a per-key
565
+ // copy — the clone path does the one clone and swaps it in. The first
566
+ // write on a fresh store is exactly that case.
567
+ const n = e.v;
568
+ if (!e.fam?.opt && !e.ch && !Array.isArray(n) && (e.sc !== 0 ? !e.a : scanAccessorsOnce(e)) && e.kc > OVERLAY_MIN_KEYS && isOwned(n)) {
569
+ // Inherits `v`'s $OWNER stamp — the overlay resolves and reads as
570
+ // owned without a registration of its own.
571
+ t = e.pb = Object.create(n);
572
+ e.ovl = true;
573
+ } else t = e.pb = cloneRaw(n, e);
574
+ // Optimistic families: seed USER drafts from the OPTIMISTIC VIEW
575
+ // (committed + active node overrides), so follow-up writes compose on
576
+ // optimism instead of clobbering from base (#2951's compose half).
577
+ // AUTHORITATIVE drafts (projection recompute / write-override landings)
578
+ // seed from committed truth — seeding overrides there would fold a lane
579
+ // value into the committed home ("authority wins at reveal" would break).
580
+ if (e.fam?.opt && !projectionWriteActive && !getWriteOverride()) {
581
+ tentativePBs.add(t);
582
+ const n = e.n;
583
+ if (n !== null) {
584
+ for (const e of Reflect.ownKeys(n)) {
585
+ const r = n[e];
586
+ if (hasActiveOverride(r)) t[e] = unwrapOverride(r.o?.Ne);
587
+ }
588
+ }
589
+ const r = e.h;
590
+ if (r !== null) {
591
+ for (const e of Reflect.ownKeys(r)) {
592
+ const n = r[e];
593
+ if (hasActiveOverride(n) && !unwrapOverride(n.o?.Ne)) delete t[e];
594
+ }
595
+ }
596
+ }
597
+ queueFold(e);
598
+ }
599
+ return t;
600
+ }
601
+
602
+ /** Sentinel holder for `t.ht`: a latest()-pull staged this adoption outside
603
+ * any transition — the hold lasts until the fold commit (drainFolds). */ const PLAIN_HOLD = Symbol("plainHold");
604
+
605
+ /** True while a latest() read is pulling the projection computed up to date
606
+ * (see the get trap): adoptions landing during the pull are speculative
607
+ * against the un-flushed batch and stage a held view. (Not injectable — the
608
+ * derived createStore overload retains projection machinery in every store
609
+ * bundle, see treeshake.test.ts.) */ let latestPullActive = false;
610
+
611
+ /** Resolve the held committed view (#3074): answers the masked old backing
612
+ * while the hold is live, and lazily clears a hold whose transition has
613
+ * committed (transitions merge — resolve through currentTransition, same as
614
+ * foldHeld's node stamps). */ function heldMaskView(e) {
615
+ const t = e.ht;
616
+ if (t === null) return null;
617
+ if (t !== PLAIN_HOLD && currentTransition(t)?.yt === true) return e.ht = e.hv = null;
618
+ return e.hv;
619
+ }
620
+
621
+ /**
622
+ * Adoption (2026-08-16c): the incoming object becomes the committed backing
623
+ * IMMEDIATELY — reconcile is eagerly visible to every reader (shipped
624
+ * contract; only its notifications batch), unlike setter writes which stay
625
+ * pending until flush. Ownership resets (incoming is unowned/user data). Any
626
+ * staged draft clone folds into the diff and is discarded — next is the
627
+ * authoritative base (R21/R32).
628
+ */ function adoptPB(e, t, n = false) {
629
+ // Eager mode (plain-store adoption): the caller notifies inline after its
630
+ // descent — no foldOlds queue/drain round trip (the reconcile diff IS the
631
+ // fold diff; ~half of dbmon tick time was this duplication).
632
+ if (!n) {
633
+ queueFold(e);
634
+ // records the pre-batch old before we swap
635
+ // Diff base = the view the nodes were last told (#3296). A draft's
636
+ // setter-exit notifications already moved them to its pending backing,
637
+ // so a later adoption diffs against THAT — against committed, a key the
638
+ // draft changed and the adoption restores would never re-notify. An
639
+ // adoption with no draft leaves nodes where they were: keep an existing
640
+ // base, else the pre-batch committed (foldOlds' entry itself stays the
641
+ // committed identity for the path-copy CAS). Eager callers read t.pb
642
+ // directly; this hand-off exists because pb is gone by drain time.
643
+ if (e.pb !== null) {
644
+ if (e.ovl) materializePB(e);
645
+ e.ab = e.pb;
646
+ } else e.ab ??= foldOlds.get(e);
647
+ }
648
+ // #3074/#3075: a projection recompute deriving from uncommitted inputs
649
+ // swaps the backing SPECULATIVELY — committed-visibility readers must
650
+ // keep the pre-hold view until the hold resolves (a source held by a
651
+ // live transition, or a latest()-pull ahead of the flush). Post-await
652
+ // landings (write-override) stay immediately visible — landed truth —
653
+ // and clear any hold. Optimistic families hold too (#3330 store twin):
654
+ // their tentative edits ride the lane machinery, but a sync derive
655
+ // adopting under a transaction is held TRUTH like any projection's —
656
+ // unheld, handlers read it early and an optimistic write equal to it
657
+ // compared as a no-op against the swapped-in backing. A plain store's
658
+ // reconcile inside an action holds the same way: its nodes stage under the
659
+ // transaction (the inline notify), and the backing must not show handlers
660
+ // and stale readers what the tracked read masks (signal parity, #3336).
661
+ if (getWriteOverride()) {
662
+ e.ht = e.hv = null;
663
+ } else if (activeTransition !== null || !n && latestPullActive) {
664
+ if (heldMaskView(e) === null) e.hv = e.v;
665
+ e.ht = activeTransition ?? PLAIN_HOLD;
666
+ if (!n && activeTransition !== null) heldAdoptions.add(e);
667
+ }
668
+ e.pb = null;
669
+ // Overlay and accessor-scan state describe the OUTGOING backing — a
670
+ // swapped container must not inherit them: a stale `ovl` beside a nulled
671
+ // pb crashes materializePB (unwrapValue consults ovl before the
672
+ // null-coalesce), a stale `del` would read the adoptee's keys as deleted
673
+ // in the next draft, and a stale plain-data verdict (`sc`/`a`) could
674
+ // admit an accessor-bearing adoptee to the overlay path. Reset; the next
675
+ // draft rescans once (#3044 audit follow-up).
676
+ e.ovl = false;
677
+ e.del = null;
678
+ e.sc = 0;
679
+ e.a = false;
680
+ e.wk = null;
681
+ // adoption supersedes staged trap writes
682
+ e.v = t;
683
+ e.ch = t[$TARGET] !== undefined;
684
+ // An adoptee we own within this family (a draft aliasing one of the
685
+ // family's own backings) re-stamps to its new owner — the stamp is the
686
+ // family's registration for it; everything else registers in the map.
687
+ const r = t[$OWNER];
688
+ if (r !== undefined && r.fam === e.fam) t[$OWNER] = e; else (e.fam?.map ?? storeNextLookup).set(t, e);
689
+ }
690
+
691
+ /** Sentinel for `t.wk`: the written-keys bound is unusable this batch (an
692
+ * array length write implicitly deleted indices) — consumers full-scan. */ const WK_ALL = new Set;
693
+
694
+ const plainProto = e => {
695
+ const t = Object.getPrototypeOf(e);
696
+ return t === Object.prototype || t === Array.prototype || t === null;
697
+ };
698
+
699
+ function queueFold(e) {
700
+ if (foldOlds.has(e)) return;
701
+ if (!hookInstalled) {
702
+ hookInstalled = true;
703
+ setStoreCommitHook(drainFolds);
704
+ }
705
+ // Always arm — "map non-empty ⇒ drain scheduled" is NOT an invariant: a
706
+ // held re-queue, or an incomplete-transition flush (which skips
707
+ // commitPendingNodes entirely), leaves entries behind after `scheduled`
708
+ // was consumed. A size-gated arm then strands every LATER fold — queued
709
+ // silently, never drained, committed base frozen at stale state while its
710
+ // nodes commit (#3089). schedule() early-returns when already armed.
711
+ schedule();
712
+ foldOlds.set(e, e.v);
713
+ }
714
+
715
+ /** Fold write-attribution (#3089): a draft written while a transition is
716
+ * active belongs to that transition — its fold must not commit before the
717
+ * transition settles. Observed keys already defer through the held check in
718
+ * drainFolds (their nodes carry _pendingValue); this write-time stamp is the
719
+ * equivalent hold for UNOBSERVED keys, which have no node to consult.
720
+ * Refreshed on every write; resolved through currentTransition at drain
721
+ * (transitions merge — same rule as heldMaskView). */ const foldBatches = new WeakMap;
722
+
723
+ /** Parked truth-staged pending backings (#3164 fold): a tentative draft that
724
+ * opens while a folded landing's backing is live moves the staged container
725
+ * here (see ensurePB); the tentative discard in notifyOptimisticWrites
726
+ * restores it in place of the usual null. */ const stagedTruthPB = new WeakMap;
727
+
728
+ /** Backings opened by TENTATIVE drafts (optimistic user setters): ensurePB's
729
+ * truth-park must not fire against the draft's own container on its second
730
+ * and later writes (the first write stamps foldBatches whenever an action's
731
+ * transition is ambient). Entries die with their draft — tentative backings
732
+ * are consumed at setter exit. */ const tentativePBs = new WeakSet;
733
+
734
+ /** A draft read composes the live optimistic view until the draft has opened
735
+ * its OWN view-seeded backing (ensurePB seeds that clone from the view and
736
+ * registers it in tentativePBs; from then on reads must see the draft's
737
+ * writes, not the overrides they superseded). A pending backing that exists
738
+ * for any other reason is not that clone — a truth landing staged into a
739
+ * retaining transaction (#3164 fold) is authoritative truth WITHOUT the
740
+ * live overrides. ensurePB parks such a backing on the draft's first WRITE
741
+ * and reseeds from the view, but the reads that precede that write went to
742
+ * the staged truth: `votes++` read base, wrote base+1, and the override it
743
+ * emitted landed on the value already displayed — a second in-flight
744
+ * increment made after a sibling's landing was invisible (#2951's compose
745
+ * half, one landing later). */ function draftSeesOverrides(e) {
746
+ return e.pb === null || !tentativePBs.has(e.pb);
747
+ }
748
+
749
+ /** Committed-time privatization for parent-chain slot updates (path copying). */ function privatizeCommitted(e) {
750
+ if (isOwned(e.v)) return;
751
+ const t = e.v;
752
+ const n = cloneRaw(t, e);
753
+ e.v = n;
754
+ e.ch = false;
755
+ if (e.u) {
756
+ privatizeCommitted(e.u);
757
+ devAssertNeverUserMutation(e.u.v);
758
+ // CAS, same as drainFolds' path copy: re-point the parent slot only
759
+ // while it still holds the raw we cloned. A parent that folded EARLIER
760
+ // in this drain may have replaced or deleted this slot (the same batch
761
+ // wrote the child and then `parent.row = fresh` / `parent.length = 0`)
762
+ // — an unconditional write resurrected the dropped child over it.
763
+ const n = e.u.v;
764
+ const r = parentSlotKey(e, t);
765
+ if (n[r] === t) n[r] = e.v;
766
+ }
767
+ }
768
+
769
+ /** Resolve the slot this child currently occupies in its parent's committed
770
+ * backing (#3282). `pk` is stamped at wrap time and arrays MOVE: a reverse/
771
+ * unshift/splice relocates the raw, and a fold that re-points the wrap-time
772
+ * slot writes the clone over whichever row lives there now. Objects never
773
+ * move keys, so the stamp is authoritative; for arrays, verify and re-locate
774
+ * by identity when stale (fold-time only — never on a read path). */ function parentSlotKey(e, t) {
775
+ const n = e.pk;
776
+ const r = e.u.v;
777
+ if (r[n] === t || !Array.isArray(r)) return n;
778
+ const i = r.indexOf(t);
779
+ if (i === -1) return n;
780
+ e.pk = i;
781
+ return i;
782
+ }
783
+
784
+ /** Overlay commit (#3044): apply the batch's writes onto an OWNED committed
785
+ * backing in place — O(written), not O(container). Unowned backings
786
+ * privatize first (clone once, parents re-slotted) — the never-mutate-user-
787
+ * data contract holds. Shared by the deferred fold (drainFolds) and the
788
+ * projection landing's immediate commit (notifyWrites). */ function flattenOverlay(e, t) {
789
+ privatizeCommitted(e);
790
+ const n = e.v;
791
+ // Plain-data grade (sc 2): every own key on the overlay is an enumerable
792
+ // writable data slot (set-trap writes; a non-plain defineProperty
793
+ // downgrades the grade) — a bare assignment lands it without the
794
+ // descriptor round trip.
795
+ for (const r of Reflect.ownKeys(t)) e.sc === 2 ? n[r] = t[r] : copyOwn(n, t, r);
796
+ if (e.del !== null) {
797
+ for (const t of e.del) delete n[t];
798
+ e.del = null;
799
+ }
800
+ e.pb = null;
801
+ e.ovl = false;
802
+ e.wk = null;
803
+ // written-keys window closes with the commit
804
+ }
805
+
806
+ function drainFolds() {
807
+ if (foldOlds.size === 0) return;
808
+ const e = [ ...foldOlds ];
809
+ foldOlds.clear();
810
+ for (const [t, n] of e) {
811
+ // A latest()-pull staging holds only until the fold commit: this flush
812
+ // is committing the batch the pull ran ahead of. Transition holds stay —
813
+ // they clear when their transition is done (heldMaskView).
814
+ if (t.ht === PLAIN_HOLD) t.ht = t.hv = null;
815
+ if (t.pb !== null) {
816
+ // #3089: a fold written under a still-running transition defers to
817
+ // that transition's settle (the write-time stamp covers unobserved
818
+ // keys; observed keys also hit the pending-node held check below).
819
+ const e = foldBatches.get(t);
820
+ if (e !== undefined) {
821
+ if (currentTransition(e).yt === false) {
822
+ foldOlds.set(t, n);
823
+ continue;
824
+ }
825
+ foldBatches.delete(t);
826
+ }
827
+ // Setter path: nodes were setSignal'd at setter exit (write-time
828
+ // notification — transitions/holds ride core machinery). Commit the
829
+ // backing only for keys whose nodes have committed; a still-pending
830
+ // node (transition-held) re-queues the target for the settling flush.
831
+ let r = false;
832
+ const i = t.pb;
833
+ const o = t.n;
834
+ if (o !== null) {
835
+ // Only written keys can hold (their nodes took the setSignal); the
836
+ // wk bound keeps this O(written) — see notifyWrites. Same fallback
837
+ // rules as the notify (WK_ALL / accessors / non-plain prototypes).
838
+ const e = t.wk;
839
+ const n = e === null || e === WK_ALL || t.a === true ||
840
+ // Overlay pbs chain to the COMMITTED object (#3044) — plainness is
841
+ // the committed container's prototype, not the overlay's.
842
+ !plainProto(t.ovl ? t.v : i) ? Reflect.ownKeys(o) : e;
843
+ for (const e of n) {
844
+ const t = o[e];
845
+ if (t !== undefined && t._e !== NOT_PENDING) {
846
+ r = true;
847
+ break;
848
+ }
849
+ }
850
+ }
851
+ if (r) {
852
+ foldOlds.set(t, n);
853
+ // re-queue: commit happens when the hold settles
854
+ continue;
855
+ }
856
+ if (t.ovl) {
857
+ // Overlay flatten (#3044): the backing keeps its identity, so the
858
+ // `t.v === old` gate below skips path copying (the parent slot
859
+ // already points here) and the adopted-notify (setter notifications
860
+ // happened at write time).
861
+ flattenOverlay(t, i);
862
+ } else if (t.v !== n) {
863
+ // Privatized mid-batch (#3271): an earlier fold in this drain
864
+ // path-copied THROUGH this target — privatizeCommitted cloned the
865
+ // committed backing, re-pointed the parent slot at the clone, and
866
+ // stitched the descendant's fold into it. The draft's pb predates
867
+ // that: swapping it in would clobber the descendant's fold, and the
868
+ // parent CAS below (still comparing against `old`) would fail and
869
+ // orphan this fold entirely — a projection draft writing descendant-
870
+ // then-ancestor silently lost the ancestor write. Merge the batch's
871
+ // writes onto the current container instead (the parent slot already
872
+ // points at it). privatize first: an adopt-then-write batch can land
873
+ // here with an unowned adoptee as t.v.
874
+ privatizeCommitted(t);
875
+ const e = t.v;
876
+ const r = t.wk;
877
+ if (r !== null && r !== WK_ALL) {
878
+ // The trap records every write/delete key — apply exactly those.
879
+ for (const t of r) {
880
+ if (hasOwn.call(i, t)) copyOwn(e, i, t); else delete e[t];
881
+ }
882
+ } else {
883
+ // Array length write poisoned the bound (WK_ALL) — value-diff
884
+ // against the pre-batch old. Slots the draft never touched hold
885
+ // the same raw reference in both, so descendant folds stay put.
886
+ // Not copyOwn: the plain-value write is GATED on "the draft changed
887
+ // this slot" — an untouched slot in pb holds the pre-batch reference,
888
+ // and writing it back would clobber a descendant fold stitched into v.
889
+ for (const t of Reflect.ownKeys(i)) {
890
+ const r = Object.getOwnPropertyDescriptor(i, t);
891
+ if (r.get || r.set || !r.enumerable || !r.writable || !r.configurable) Object.defineProperty(e, t, r); else if (r.value !== n[t] || !hasOwn.call(n, t)) e[t] = r.value;
892
+ }
893
+ for (const t of Reflect.ownKeys(n)) {
894
+ if (!hasOwn.call(i, t)) delete e[t];
895
+ }
896
+ }
897
+ t.pb = null;
898
+ t.wk = null;
899
+ // written-keys window closes with the fold commit
900
+ } else {
901
+ t.v = i;
902
+ t.ch = false;
903
+ // pb is always a plain clone
904
+ t.pb = null;
905
+ t.wk = null;
906
+ // written-keys window closes with the fold commit
907
+ }
908
+ }
909
+ const e = t.ab;
910
+ t.ab = null;
911
+ if (t.v !== n) {
912
+ // Path copying (CAS: see the eager-fold twin above). Slot resolved by
913
+ // identity (#3282): an array move relocated the raw, so the wrap-time
914
+ // pk may point at a sibling — a raw-slot CAS there both failed to
915
+ // re-point AND (via privatizeCommitted's unguarded write) clobbered
916
+ // the sibling.
917
+ if (t.u) {
918
+ const e = parentSlotKey(t, n);
919
+ if (t.u.v[e] === n) {
920
+ privatizeCommitted(t.u);
921
+ devAssertNeverUserMutation(t.u.v);
922
+ t.u.v[e] = t.v;
923
+ }
924
+ }
925
+ }
926
+ // Adoption notify against the base the nodes were last told (#3296). A
927
+ // no-op adoption (A -> B -> A before flush, no draft) has base === v and
928
+ // nothing to say; a draft superseded by an adoption back to the SAME raw
929
+ // still has (base = pending backing) !== v and must notify.
930
+ if (e !== null && e !== t.v) notifyFold(t, e, t.v);
931
+ }
932
+ }
933
+
934
+ /** Dev: dotted path of a target from its store root (`store.user.address`). */ function storePath(e) {
935
+ let t = "";
936
+ for (let n = e; n !== null; n = n.u) t = n.pk === null ? "store" + t : "." + String(n.pk) + t;
937
+ return t;
938
+ }
939
+
940
+ /**
941
+ * Dev (attribution engine installed): announce written keys whose old and new
942
+ * values are both containers but different logical slots — the raw material
943
+ * for the spread-copy diagnostic. The engine owns the verdict.
944
+ */ function reportReplacedContainers(e, t, n, r) {
945
+ const i = r ?? Reflect.ownKeys(n);
946
+ const o = Array.isArray(n);
947
+ const l = storeRootOwner(e);
948
+ for (const r of i) {
949
+ if (o && r === "length" || r === $OWNER) continue;
950
+ if (e.del !== null && e.del.has(r)) continue;
951
+ const i = unwrapValue(t[r]);
952
+ const f = unwrapValue(n[r]);
953
+ if (i === null || f === null || typeof i !== "object" || typeof f !== "object" || i === f || targetsEqual(i, f)) continue;
954
+ // Leaf census on the store side: leaves read through a draft are proxies
955
+ // of the committed raws, so identity must be judged on unwrapped values.
956
+ const s = Array.isArray(f);
957
+ if (s !== Array.isArray(i)) continue;
958
+ let u;
959
+ let a = 0;
960
+ if (s) {
961
+ u = f.length;
962
+ if (u > REPLACED_CENSUS_MAX) continue;
963
+ const e = new Set;
964
+ for (const t of i) e.add(unwrapValue(t));
965
+ for (const t of f) if (e.has(unwrapValue(t))) a++;
966
+ } else {
967
+ const e = Object.keys(f);
968
+ u = e.length;
969
+ if (u > REPLACED_CENSUS_MAX) continue;
970
+ for (const t of e) if (sameLeaf(i[t], f[t])) a++;
971
+ }
972
+ attrHooks.storeReplaced(storePath(e) + "." + String(r), s, u, a, s ? i.length : Object.keys(i).length, l);
973
+ }
974
+ }
975
+
976
+ const REPLACED_CENSUS_MAX = 64;
977
+
978
+ function sameLeaf(e, t) {
979
+ if (e === t) return true;
980
+ if (e === null || t === null || typeof e !== "object" || typeof t !== "object") return false;
981
+ return unwrapValue(e) === unwrapValue(t) || targetsEqual(e, t);
982
+ }
983
+
984
+ /**
985
+ * Setter-exit notification (write channel): diff the draft's pending backing
986
+ * against committed and setSignal every changed OBSERVED key — write-time
987
+ * notification with commit deferred to node commit, so transition holds,
988
+ * isPending, affects, and lane machinery ride the core natively (§3's
989
+ * "pending home = the node when a node exists"). Unobserved keys stay in the
990
+ * pending backing and fold directly at commit.
991
+ */ function notifyWrites(e) {
992
+ let t = e.pb;
993
+ if (t === null) return;
994
+ // Optimistic channel: user writes on an optimistic family become node-level
995
+ // engine writes (armed nodes route setSignal through optimisticWrite) — the
996
+ // committed backing is NEVER touched; the draft clone is discarded. Reverts,
997
+ // per-transaction ownership, and flash-at-flush are all core-native.
998
+ // Projection recompute writes (projectionWriteActive) and projection draft
999
+ // writes (write-override, incl. post-await async landings) are
1000
+ // authoritative and take the plain channel below (they commit silently
1001
+ // under overrides per the engine's no-revert-stash contract).
1002
+ if (e.fam?.opt) {
1003
+ if (!projectionWriteActive && !getWriteOverride()) {
1004
+ optHooks.notifyOptimisticWrites(e, t);
1005
+ return;
1006
+ }
1007
+ // Authoritative path on an optimistic family: armed nodes must commit
1008
+ // silently (engine bypass) — without this, a landing's setSignals would
1009
+ // create lanes and block their own transition's settle.
1010
+ if (!projectionWriteActive) {
1011
+ setProjectionWriteActive(true);
1012
+ try {
1013
+ notifyWrites(e);
1014
+ } finally {
1015
+ setProjectionWriteActive(false);
1016
+ }
1017
+ return;
1018
+ }
1019
+ }
1020
+ const n = e.v;
1021
+ const r = e.n;
1022
+ // Written-keys bound: trap writes record their keys, so the notify visits
1023
+ // O(written) nodes instead of every subscription on the record (a selection
1024
+ // map with thousands of per-key subscribers pays two visits per select,
1025
+ // not a full scan). Falls back to the full node scan when the bound can't
1026
+ // hold: no trap granularity (wk null), an array length write (WK_ALL —
1027
+ // implicit index deletes), accessors on the record (t.a — a getter node's
1028
+ // value can change when ANY key is written), or a non-plain prototype
1029
+ // (class instances: prototype getters derive from arbitrary fields).
1030
+ const i = e.wk;
1031
+ // Overlay pbs chain to the COMMITTED object (#3044): a prototype-overlay
1032
+ // draft is plain data on its own layer, but its getPrototypeOf is the
1033
+ // committed container — judge plainness by the COMMITTED prototype or the
1034
+ // bound never engages for overlay writes (every plain-object setter batch
1035
+ // would full-scan: the exact selection-map workload wk exists for; jf
1036
+ // `select` regressed 2x on this).
1037
+ const o = i === WK_ALL || e.a === true || !plainProto(e.ovl ? e.v : t) ? null : i;
1038
+ if (attrHooks !== null) reportReplacedContainers(e, n, t, o);
1039
+ if (r !== null) {
1040
+ const i = o ?? Reflect.ownKeys(r);
1041
+ for (const o of i) {
1042
+ const i = r[o];
1043
+ if (i === undefined) continue;
1044
+ // Per-key accessor handling: the node's cached flag plus ONE getter
1045
+ // probe on the incoming side (getters arriving via merge/adoption).
1046
+ // Setter-only props read as data (value undefined) so lookupSetter is
1047
+ // not consulted on this hot path; prototype getters never own nodes.
1048
+ if (i.acc === true || hasOwn.call(t, o) && lookupGetter.call(t, o) !== undefined) {
1049
+ i.acc = isOwnAccessor(t, o);
1050
+ const e = Object.getOwnPropertyDescriptor(n, o);
1051
+ const r = Object.getOwnPropertyDescriptor(t, o);
1052
+ if (e && (e.get || e.set) || r && (r.get || r.set)) {
1053
+ if (e?.get !== r?.get || e?.set !== r?.set || e?.value !== r?.value) setSignal(i, () => FORCE);
1054
+ continue;
1055
+ }
1056
+ if (!isEqual(e?.value, r?.value)) setSignal(i, () => r?.value);
1057
+ continue;
1058
+ }
1059
+ // No old-side pre-compare: t.v lags across multi-batch windows (a
1060
+ // projection recompute can run before the prior fold commits) — the
1061
+ // node's OWN current value is the true old side, and setSignal's
1062
+ // internal equality already checks exactly that.
1063
+ const l = e.del !== null && e.del.has(o) ? undefined : t[o];
1064
+ setSignal(i, () => l);
1065
+ }
1066
+ }
1067
+ const l = e.h;
1068
+ if (l !== null) {
1069
+ const n = o ?? Reflect.ownKeys(l);
1070
+ for (const r of n) {
1071
+ const n = l[r];
1072
+ if (n !== undefined) setSignal(n, r in t && !(e.del !== null && e.del.has(r)));
1073
+ }
1074
+ }
1075
+ // Deep-witness (dk): setter writes must notify a deep() subscriber even on
1076
+ // keys with no node. O(written/pb keys) equality only when a witness exists.
1077
+ if (e.dk !== null) {
1078
+ if (e.del !== null && e.del.size !== 0) bumpDeep(e); else for (const r of o ?? Reflect.ownKeys(t)) {
1079
+ if (r === $OWNER) continue;
1080
+ const i = t[r];
1081
+ const o = n[r];
1082
+ if (i !== null && typeof i === "object" ? !targetsEqual(o, i) : !isEqual(o, i)) {
1083
+ bumpDeep(e);
1084
+ break;
1085
+ }
1086
+ }
1087
+ }
1088
+ if (e.k !== null) {
1089
+ let r;
1090
+ if (e.ovl) {
1091
+ // Overlay membership: only NEW own keys or deletes can change it.
1092
+ r = e.del !== null && e.del.size !== 0;
1093
+ if (!r) {
1094
+ for (const e of Reflect.ownKeys(t)) {
1095
+ if (!hasOwn.call(n, e)) {
1096
+ r = true;
1097
+ break;
1098
+ }
1099
+ }
1100
+ }
1101
+ } else {
1102
+ r = Array.isArray(t) && Array.isArray(n) ? arrayStructureChanged(n, t) : membershipChanged(n, t);
1103
+ }
1104
+ if (r) setSignal(e.k, e => e + 1);
1105
+ }
1106
+ // Projection backing folds split by channel (two pinned contracts):
1107
+ // - sync-derive drafts (recompute body): NEVER eager — a downstream async
1108
+ // hold can form LATER in the same flush and the leaf must stay at stale
1109
+ // committed for context-free readers (spec-async "pends only the written
1110
+ // leaf"). drainFolds commits when held-ness is knowable.
1111
+ // - post-await async LANDINGS (write-override per-op, microtask context —
1112
+ // no enclosing flush can capture them): the data-level commit is
1113
+ // IMMEDIATE — landed truth shows to untracked readers even while a
1114
+ // downstream consumer's own async still holds the effect-level reveal
1115
+ // (spec-async "verdicts never inherit consumers' in-flight state").
1116
+ // EXCEPT under an active transaction (#3164 fold): a landing riding a
1117
+ // retaining transaction (the optimistic module's aroundWrite binds it)
1118
+ // stages instead — ensurePB stamped foldBatches, so the backing commits
1119
+ // with the transaction and the reveal is atomic at settle. The pinned
1120
+ // immediate-commit contract is stated over the no-transaction microtask
1121
+ // posture, which `activeTransition === null` is exactly.
1122
+ if (e.fam !== null && e.pb !== null && getWriteOverride() && activeTransition === null) {
1123
+ // Landed truth (post-await write-override): immediately visible to every
1124
+ // reader — any staged held view is superseded.
1125
+ if (e.ht !== null) e.ht = e.hv = null;
1126
+ // Overlay landing (#3352): flatten in place — identity-stable, and
1127
+ // privatizeCommitted re-slots the parent itself when it has to clone an
1128
+ // unowned seed, so no path copy is needed.
1129
+ if (e.ovl) return flattenOverlay(e, t);
1130
+ const n = e.v;
1131
+ e.pb = null;
1132
+ e.v = t;
1133
+ e.ch = false;
1134
+ if (e.u) {
1135
+ // Identity-resolved slot (#3282) — see drainFolds' path-copy twin.
1136
+ const r = parentSlotKey(e, n);
1137
+ if (e.u.v[r] === n) {
1138
+ privatizeCommitted(e.u);
1139
+ devAssertNeverUserMutation(e.u.v);
1140
+ e.u.v[r] = t;
1141
+ }
1142
+ }
1143
+ }
1144
+ }
1145
+
1146
+ const FORCE = Symbol();
1147
+
1148
+ /** Same logical slot: both values resolve to one (re-pointed) child target —
1149
+ * adoption preserved identity, so the slot did not change (R9). */ function targetsEqual(e, t) {
1150
+ if (e === null || typeof e !== "object" || t === null || typeof t !== "object") return false;
1151
+ const n = lookupTarget(e, null);
1152
+ return n !== undefined && n === lookupTarget(t, null);
1153
+ }
1154
+
1155
+ function arrayStructureChanged(e, t) {
1156
+ if (e.length !== t.length) return true;
1157
+ for (let n = 0; n < t.length; n++) {
1158
+ const r = e[n];
1159
+ const i = t[n];
1160
+ if (!isEqual(r, i) && !targetsEqual(r, i)) return true;
1161
+ }
1162
+ return false;
1163
+ }
1164
+
1165
+ function membershipChanged(e, t) {
1166
+ const n = Reflect.ownKeys(t);
1167
+ // The $OWNER stamp is not membership: an owned side counts one key more.
1168
+ if (Reflect.ownKeys(e).length - +isOwned(e) !== n.length - +isOwned(t)) return true;
1169
+ for (const t of n) if (t !== $OWNER && !(t in e)) return true;
1170
+ return false;
1171
+ }
1172
+
1173
+ /**
1174
+ * The fold diff walks SUBSCRIPTION KEYS ONLY (legacy parity: `for key in
1175
+ * nodes`): nodes exist exactly where something tracked, so unobserved data
1176
+ * costs nothing here regardless of object size. Accessor safety rides the
1177
+ * sticky `t.a` flag — a node's key was necessarily read, so the get trap has
1178
+ * already seen whether it is an accessor.
1179
+ */
1180
+ /** One node's fold notification (shared by notifyFold's walk and the fused
1181
+ * adoption walk): accessor-aware compare + equality/identity-gated setSignal. */ function notifyKeyDiff(e, t, n, r,
1182
+ // The incoming-side getter probe covers SETTER-channel arrivals (return-
1183
+ // form merges, defineProperty) — those flow through notifyWrites/
1184
+ // notifyFold, which probe. The RECONCILE channel (fused walk) passes
1185
+ // false: reconcile adopts immutable data by contract (R2a) and the pinned
1186
+ // getter-preservation tests are all setter-channel; skipping ~2 Annex-B
1187
+ // calls per key per tick is a measured dbmon win.
1188
+ i = true) {
1189
+ if (e.acc === true || i && hasOwn.call(r, t) && lookupGetter.call(r, t) !== undefined) {
1190
+ e.acc = isOwnAccessor(r, t);
1191
+ const i = Object.getOwnPropertyDescriptor(n, t);
1192
+ const o = Object.getOwnPropertyDescriptor(r, t);
1193
+ if (i && (i.get || i.set) || o && (o.get || o.set)) {
1194
+ // Accessor involved: never invoke; force-notify on shape change so
1195
+ // subscribers re-read (and re-track) through the trap.
1196
+ if (i?.get !== o?.get || i?.set !== o?.set || i?.value !== o?.value) setSignal(e, () => FORCE);
1197
+ return;
1198
+ }
1199
+ const l = i?.value;
1200
+ const f = o?.value;
1201
+ if (!isEqual(l, f) && !targetsEqual(l, f)) setSignal(e, typeof f === "function" ? () => f : f);
1202
+ } else {
1203
+ const i = n[t];
1204
+ const o = r[t];
1205
+ // Direct value write when not a function (setSignal treats functions as
1206
+ // updaters) — saves a closure allocation per changed key on the fold
1207
+ // hot path.
1208
+ if (!isEqual(i, o) && !targetsEqual(i, o)) setSignal(e, typeof o === "function" ? () => o : o);
1209
+ }
1210
+ }
1211
+
1212
+ /** Accessor-flag probe for the fused walk's early-continue (accessor keys
1213
+ * can never identity-skip: their VALUE is the descriptor's product). */ function hasAccessorFlag(e) {
1214
+ return e.acc === true;
1215
+ }
1216
+
1217
+ /** Fused-walk per-key notification with values already in hand: the caller
1218
+ * fetched both sides and handled the identity skip; this applies the
1219
+ * accessor branch (cached flag only — reconcile channel) or the plain
1220
+ * equality/identity-gated write. */ function notifyKeyValue(e, t, n, r, i, o) {
1221
+ if (e.acc === true) {
1222
+ notifyKeyDiff(e, t, i, o, false);
1223
+ return;
1224
+ }
1225
+ // The pre-compare is NOT redundant with the node's equals: setSignal parks
1226
+ // a pending value and registers with the batch before equality applies at
1227
+ // commit (RUL-1), so identity-preserved slots (adopted child containers —
1228
+ // every row's fresh `queries` array) must be gated out HERE or each one
1229
+ // pays the full write machinery every tick (measured: +0.5ms/tick dbmon).
1230
+ if (!isEqual(n, r) && !targetsEqual(n, r)) setSignal(e, typeof r === "function" ? () => r : r);
1231
+ }
1232
+
1233
+ /** Presence + membership halves of a fold notification (shared tail). */ function notifyFoldTail(e, t, n) {
1234
+ const r = e.h;
1235
+ if (r !== null) {
1236
+ for (const e of Reflect.ownKeys(r)) setSignal(r[e], e in n);
1237
+ }
1238
+ if (e.k !== null) {
1239
+ const r = Array.isArray(n) && Array.isArray(t) ? arrayStructureChanged(t, n) : membershipChanged(t, n);
1240
+ if (r) setSignal(e.k, e => e + 1);
1241
+ }
1242
+ }
1243
+
1244
+ function notifyFold(e, t, n) {
1245
+ if (e.dk !== null && t !== n) bumpDeep(e);
1246
+ // Optimistic targets: adoption notifications are authoritative landings —
1247
+ // bypass the engine (commit into _value; active overrides keep shadowing
1248
+ // until their transaction settles, per the no-revert-stash contract).
1249
+ if (e.fam?.opt && !projectionWriteActive) {
1250
+ setProjectionWriteActive(true);
1251
+ try {
1252
+ notifyFold(e, t, n);
1253
+ } finally {
1254
+ setProjectionWriteActive(false);
1255
+ }
1256
+ return;
1257
+ }
1258
+ const r = e.n;
1259
+ if (r !== null) {
1260
+ for (const e of Reflect.ownKeys(r)) {
1261
+ notifyKeyDiff(r[e], e, t, n);
1262
+ }
1263
+ }
1264
+ const i = e.h;
1265
+ if (i !== null) {
1266
+ for (const e of Reflect.ownKeys(i)) setSignal(i[e], e in n);
1267
+ }
1268
+ if (e.k !== null) {
1269
+ // Key-set/$TRACK: objects notify on membership; arrays on any index or
1270
+ // length change (mapArray and iteration re-read values — R15).
1271
+ const r = Array.isArray(n) && Array.isArray(t) ? arrayStructureChanged(t, n) : membershipChanged(t, n);
1272
+ if (r) setSignal(e.k, e => e + 1);
1273
+ }
1274
+ }
1275
+
1276
+ // ---------------------------------------------------------------------------
1277
+ // traps
1278
+ /** >0 while inside a setter: writes allowed, reads are read-your-writes. */ let writing = 0;
1279
+
1280
+ /** Write scope keys (a family object or a plain store's root target): draft
1281
+ * semantics — write permission, read-your-writes, tracking suppression —
1282
+ * apply ONLY to targets under a scope being written. Reads of OTHER stores
1283
+ * inside a setter track normally (they are dependencies: a projection derive
1284
+ * reading another store must link it). */ let writeScopes = null;
1285
+
1286
+ function scopeKey(e) {
1287
+ if (e.fam !== null) return e.fam;
1288
+ let t = e;
1289
+ while (t.u !== null) t = t.u;
1290
+ return t;
1291
+ }
1292
+
1293
+ function inDraft(e) {
1294
+ return writeScopes !== null && writeScopes.has(scopeKey(e));
1295
+ }
1296
+
1297
+ /** Shallow serve rule (#2932): raw-marked data serves VERBATIM, but a
1298
+ * store-proxy slot value gets a boundary wrapper in THIS store's own family —
1299
+ * write isolation through derived chains (downstream writes must never land
1300
+ * upstream). markRawOne skips proxies for exactly this reason. */ function serveShallow(e, t, n) {
1301
+ if (n !== null && typeof n === "object" && n[$TARGET] !== undefined) return draftServe(e, wrapNext(n, e, t));
1302
+ return n;
1303
+ }
1304
+
1305
+ /** Draft reads extend write permission to reachable stores (legacy Writing
1306
+ * semantics: wrapping a child through a draft get admits it — cross-store
1307
+ * writes like `s.inner.a = 10` work when `inner` is another store's proxy). */ function draftServe(e, t) {
1308
+ if (writeScopes !== null && inDraft(e)) {
1309
+ const e = t?.[$TARGET];
1310
+ if (e !== undefined && e.v !== undefined) writeScopes.add(scopeKey(e));
1311
+ }
1312
+ return t;
1313
+ }
1314
+
1315
+ /** Targets written during the current (outermost) setter — notified at exit. */ const pendingNotify = new Set;
1316
+
1317
+ /** Targets adopted under a live transaction this setter (adoptPB set a
1318
+ * transaction hold) — their nodes are notified at the outermost exit. */ const heldAdoptions = new Set;
1319
+
1320
+ /**
1321
+ * Write-time notification for a transaction-held adoption (#3330 store twin;
1322
+ * the setter path's notifyWrites twin for adoptions). A projection's fold
1323
+ * normally notifies its nodes at the drain — and the drain of a batch parked
1324
+ * in a live transaction is the transaction's COMMIT, so the nodes took the
1325
+ * adopted values as fresh writes at commit time: every subscriber was
1326
+ * re-marked and re-ran against a frame the lane had already published (a
1327
+ * third `v=1 d=2`), where a signal's write had staged at write time and
1328
+ * promoted silently. Staging here, inside the transaction's batch, makes the
1329
+ * two paths one: the nodes carry transition-stamped `_pendingValue`s, their
1330
+ * subscribers recompute in this flush and park with the transaction, and the
1331
+ * commit promotes without re-notifying. `ab` moves to the adopted backing —
1332
+ * the view the nodes were last told (#3296) — so the drain has nothing left
1333
+ * to say and only path-copies.
1334
+ */ function stageHeldAdoptions() {
1335
+ const e = [ ...heldAdoptions ];
1336
+ heldAdoptions.clear();
1337
+ for (const t of e) {
1338
+ const e = t.ab;
1339
+ if (e === null || e === t.v) continue;
1340
+ notifyFold(t, e, t.v);
1341
+ t.ab = t.v;
1342
+ }
1343
+ }
1344
+
1345
+ const UNSAFE_KEYS = new Set([ "__proto__", "prototype", "constructor" ]);
1346
+
1347
+ /** Mirror of core read()'s context rule: the OWNER context (not the tracking
1348
+ * observer) decides pending visibility, with Roots resolving to their parent
1349
+ * computed (#2687 — untracked reads inside mapArray Roots see in-flight
1350
+ * values mid-flush). CHILDREN_FORBIDDEN execution scopes (createTrackedEffect
1351
+ * / onSettled callbacks) get COMMITTED visibility (#3006), same as core. */
1352
+ /** Core read()'s reader: the current computation, a root reading as its
1353
+ * parent computed (`context` persists under untrack — an untracked read
1354
+ * inside an effect is still that effect's read). */ function readerContext() {
1355
+ const e = getOwner();
1356
+ return e === null ? null : e.cn ? e.fn ?? null : e;
1357
+ }
1358
+
1359
+ /** A pending fold is transition-held when any written node's parked value is
1360
+ * stamped by a live transition (a plain batch parking — the lazy-recompute
1361
+ * read case — has no transition stamp and serves fresh). */ function foldHeld(e) {
1362
+ const t = e.n;
1363
+ if (t === null) return false;
1364
+ for (const e of Reflect.ownKeys(t)) {
1365
+ const n = t[e];
1366
+ if (n._e !== NOT_PENDING && n.Te != null && n.Te.yt !== true) return true;
1367
+ }
1368
+ return false;
1369
+ }
1370
+
1371
+ function readSource(e) {
1372
+ // Adoption hold first (#3074): an adoption staged under a live transaction
1373
+ // (or a latest()-pull, PLAIN_HOLD) serves the pre-hold committed view to
1374
+ // committed-visibility readers — context-free and children-forbidden ones,
1375
+ // and stale passes off a foreign hold. Drafts, write-override and latest()
1376
+ // see the adopted backing.
1377
+ const t = e.ht;
1378
+ if (t !== null && !latestReadActive && !inDraft(e) && !getWriteOverride()) {
1379
+ const n = heldMaskView(e);
1380
+ if (n !== null) {
1381
+ const e = readerContext();
1382
+ if (e === null || e.C & CONFIG_CHILDREN_FORBIDDEN || !holdVisible(t === PLAIN_HOLD ? null : currentTransition(t), e)) return n;
1383
+ }
1384
+ }
1385
+ return pendingBackingVisible(e, false) ? e.pb : e.v;
1386
+ }
1387
+
1388
+ /** The single pb-vs-committed visibility decision (#3147), shared by per-key
1389
+ * backing reads (readSource) and deep()/snapshot composition (snapshotWalk)
1390
+ * so the two reader families can never disagree about a HELD landing.
1391
+ *
1392
+ * Signal-parity visibility (core read(): owner-context reads serve
1393
+ * _pendingValue, context-free reads serve committed — effects recompute
1394
+ * BEFORE commitPendingNodes in the flush, so the pending view must be
1395
+ * servable). Drafts (setter window OR projection write-override) and
1396
+ * owner-context reads see the pending backing; context-free reads see
1397
+ * committed. Node reads apply the same rule, so all homes agree.
1398
+ *
1399
+ * `speculative` is deep()/snapshot's posture: an untrack/deep PEEK that sees
1400
+ * ordinary pending staging regardless of owner context (the documented
1401
+ * divergence from context-free per-key reads) — but never through a hold:
1402
+ * held truth stays masked exactly as it is for per-key readers. */ function pendingBackingVisible(e, t) {
1403
+ if (e.pb === null) return false;
1404
+ // The writer's own channels compose on the pending backing regardless.
1405
+ if (inDraft(e) || getWriteOverride()) return true;
1406
+ // HELD truth on an optimistic family (#3164 fold) is masked from ordinary
1407
+ // readers until the transaction's reveal (the backing-level twin of core
1408
+ // serve()'s CONFIG_HELD_TRUTH arm; authoritative postures and latest()
1409
+ // tunnel through inside heldTruthMasked).
1410
+ if (heldTruthMasked(e)) return false;
1411
+ const n = readerContext();
1412
+ if (n === null || n.C & CONFIG_CHILDREN_FORBIDDEN) {
1413
+ // No pass, or a children-forbidden one: the committed frame (A32) —
1414
+ // except the speculative peek (deep()/snapshot()), which sees ordinary
1415
+ // pending staging but never through a live foreign hold, and a
1416
+ // projection's pending backing, authoritative-elect for context-free
1417
+ // readers UNLESS a transition holds the node commits (downstream async
1418
+ // hold — stale committed is the contract; the write-time stamp covers
1419
+ // keys with no node, #3336) or the scope is children-forbidden (#3082).
1420
+ const r = liveFoldTransition(e);
1421
+ if (t) return r === null || ownsHold(r);
1422
+ return e.fam !== null && n === null && !foldHeld(e) && r === null;
1423
+ }
1424
+ return holdVisible(liveFoldTransition(e), n);
1425
+ }
1426
+
1427
+ /** #3164 fold: HELD truth on an optimistic family — a pending backing
1428
+ * stamped by a live transition that retains optimism — is masked from
1429
+ * ordinary readers (they keep committed until the transaction's reveal);
1430
+ * the authoritative postures and latest() tunnel through. Un-stamped
1431
+ * backings and optimism-free transitions keep ordinary mid-batch/
1432
+ * speculation visibility. */ function heldTruthMasked(e) {
1433
+ if (e.fam?.opt !== true || latestReadActive || authoritativeServe()) return false;
1434
+ const t = foldBatches.get(e);
1435
+ // opt families are only created by createOptimisticStore, whose module
1436
+ // install populates optHooks — the assertion holds by construction.
1437
+ return t !== undefined && optHooks.retainsOptimism(t);
1438
+ }
1439
+
1440
+ const hasOwn = Object.prototype.hasOwnProperty;
1441
+
1442
+ // Allocation-free own-accessor probe (replaces eager descriptor scans — the
1443
+ // single biggest creation cost in the uibench profile): Annex-B lookups
1444
+ // return the fn or undefined with no descriptor object. Own data properties
1445
+ // shadow prototype accessors, so hasOwn + lookup is an exact own-check.
1446
+ const lookupGetter = Object.prototype.__lookupGetter__;
1447
+
1448
+ const lookupSetter = Object.prototype.__lookupSetter__;
1449
+
1450
+ const propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
1451
+
1452
+ function isOwnAccessor(e, t) {
1453
+ return hasOwn.call(e, t) && (lookupGetter.call(e, t) !== undefined || lookupSetter.call(e, t) !== undefined);
1454
+ }
1455
+
1456
+ /** Authoritative-write wrapper exported for the optimistic module: sets the
1457
+ * scheduler's projectionWriteActive through THIS module's binding (proven to
1458
+ * share the instance core reads — cross-module live-binding writes from other
1459
+ * store modules were observed not to propagate under the test transform). */ function runAuthoritative(e) {
1460
+ const t = projectionWriteActive;
1461
+ setProjectionWriteActive(true);
1462
+ try {
1463
+ return e();
1464
+ } finally {
1465
+ setProjectionWriteActive(t);
1466
+ }
1467
+ }
1468
+
1469
+ /** The reading computation is until()'s authoritative-view predicate — same
1470
+ * source of truth as core read()'s A17 carve-out (`context`, which persists
1471
+ * under untrack). optimisticView()'s composition gate consults exactly this:
1472
+ * write-side machinery (patch emission, tentative re-application) must keep
1473
+ * composing even when it runs inside an authoritative-write bracket. */ function authoritativeRead() {
1474
+ const e = context;
1475
+ return e !== null && (e.C & CONFIG_AUTHORITATIVE_READ) !== 0;
1476
+ }
1477
+
1478
+ /** Serve-side authoritative gate: until()'s predicate PLUS truth authors —
1479
+ * the projection derive's draft (wrapDraft trap brackets, runAuthoritative;
1480
+ * the same posture pair ensurePB classifies drafts by). A source computing
1481
+ * the next truth must never read its callers' tentative overlays: a derive
1482
+ * continuation's `store.push` computing its index from an action's
1483
+ * optimistic row landed truth in the wrong slot and corrupted committed
1484
+ * state (#3108). Trap-level overlay serves gate on this so values, length,
1485
+ * membership, and keys leave the authoritative view together. */ function authoritativeServe() {
1486
+ return projectionWriteActive || getWriteOverride() || authoritativeRead();
1487
+ }
1488
+
1489
+ /** Context-aware node view for reads outside tracking: active override >
1490
+ * held pending (owner context) > the BACKING value. Committed truth lives in
1491
+ * the backing (single-home rule, O6) — node `_value` is never served here,
1492
+ * so a lazy recompute's landing is immediately visible to the untracked
1493
+ * reader that forced it (backing commits eagerly; node values fold at flush).
1494
+ * FORCE sentinels never surface (they only bump subscribers of accessor
1495
+ * keys, which are served by the trap, not the node). */ function nodeValue(e, t) {
1496
+ // Store-only tunnels, ahead of Rule 1: truth authors (authoritativeServe —
1497
+ // the projection derive's draft, the write-override continuation) see
1498
+ // staged truth and never an override; latest() reaching this untracked
1499
+ // path for a store key sees the in-flight parked value like an
1500
+ // owner-context reader does (#3075), the visible override first.
1501
+ let n;
1502
+ if (authoritativeServe()) n = e._e !== NOT_PENDING ? e._e : t; else if (latestReadActive) n = visibleOverride(e) ? unwrapOverride(e.o?.Ne) : e._e !== NOT_PENDING ? e._e : t;
1503
+ // Otherwise the one slow selection core read() uses (serve): override,
1504
+ // lane gate, A28, readerSeesCommitted / A29 — with the BACKING as the
1505
+ // committed value (single-home rule, O6).
1506
+ else n = serve(e, readerContext(), e.ne || e, t);
1507
+ return n === FORCE ? t : n;
1508
+ }
1509
+
1510
+ /** §7b: a chained target's child found as a RAW — from its pending backing
1511
+ * (a cloneRaw of the inner proxy, whose descriptors yield the inner store's
1512
+ * raws) or from the deep() walk's descriptor read through the chain — must
1513
+ * resolve to the inner family's proxy for that object before this family
1514
+ * wraps it, so the overlay serves the same chained targets as the settled
1515
+ * state. Otherwise every row re-wrapped as a fresh non-chained target keyed
1516
+ * by the raw: identities churned for the life of an optimistic action and
1517
+ * snapped back at settle, and writes landed on those orphans while deep()'s
1518
+ * witnesses sat on the chained targets (#3323). The inner family owns the
1519
+ * raw iff it has served it or its backing holds that exact object at `key`;
1520
+ * anything else is a draft's own replacement object — view-owned, correctly
1521
+ * non-chained — and is returned as is. Recurses down further chains. */ function resolveChainedRaw(e, t, n) {
1522
+ const r = e.v[$TARGET];
1523
+ if (r.ch) {
1524
+ const e = resolveChainedRaw(r, t, n);
1525
+ return e === n ? n : wrapNext(e, r, t);
1526
+ }
1527
+ const i = lookupTarget(n, r.fam);
1528
+ if (i !== undefined) return i.px;
1529
+ if ((r.v[t] === n || r.pb?.[t] === n) && isWrappable(n)) return wrapNext(n, r, t);
1530
+ return n;
1531
+ }
1532
+
1533
+ /** Serve an own data key: node-first when a node exists (pending visibility,
1534
+ * holds, lanes ride the node); backing otherwise. Chained backings (§7b: the
1535
+ * backing IS another store's proxy) serve the read-through value — the outer
1536
+ * node is linked only for adoption-swap notification, its value never
1537
+ * shadows the live chain. */ function serveDataKey(e, t, n, r, i, o = -1) {
1538
+ const l = e.ch && r === e.v;
1539
+ let f = n;
1540
+ // §6: on optimistic arrays LENGTH IS A VIEW, not a node value — one home
1541
+ // (backing ± presence overrides) for both length and indices makes torn
1542
+ // iteration impossible (a length node's value rides different visibility
1543
+ // rails than index overrides mid-settle). The node still carries
1544
+ // subscriptions; its value is never served here.
1545
+ if (t === "length" && e.fam?.opt === true && !l && Array.isArray(r)) {
1546
+ if (!inDraft(e)) {
1547
+ const r = e.n?.length;
1548
+ if (r !== undefined) {
1549
+ if (getObserver() !== null) read(r);
1550
+ } else if (getObserver() !== null) {
1551
+ read(getNode(e, t, n));
1552
+ }
1553
+ }
1554
+ // Truth authors read the backing's own length — an optimistic row from
1555
+ // the caller's transaction must not shift where the author's next write
1556
+ // lands (#3108).
1557
+ return (authoritativeServe() ? r : optHooks.optimisticView(e, r, inDraft(e))).length;
1558
+ }
1559
+ if (inDraft(e)) {
1560
+ // Optimistic drafts before their first write have no pending backing yet;
1561
+ // reads must still see the live optimistic view (compose, not clobber —
1562
+ // #2951). Once ensurePB runs, the seeded clone carries the view.
1563
+ // AUTHORITATIVE drafts (projection derive) never overlay — ensurePB's
1564
+ // seeding rule, applied to the read side (#3108).
1565
+ if (e.fam?.opt && draftSeesOverrides(e) && !authoritativeServe()) {
1566
+ const n = e.n?.[t];
1567
+ if (n !== undefined && hasActiveOverride(n)) f = unwrapOverride(n.o?.Ne);
1568
+ }
1569
+ } else {
1570
+ // §7b: a lane value on the outer node SHADOWS read-through — an active
1571
+ // override pierces the chained gate; otherwise chained backings always
1572
+ // serve the live inner value.
1573
+ if (getObserver() !== null) {
1574
+ // First tracked read: create + link (the wrap-cache branch below
1575
+ // populates px/pxv so read #2 skips wrapNext, slice 2). The value is
1576
+ // served THROUGH the node from this read on — a node born under a held
1577
+ // fold carries the hold (getNode, #3336), and the backing it was read
1578
+ // from does not.
1579
+ if (i === undefined) i = getNode(e, t, n, o);
1580
+ // read()'s plain-signal fast path hoisted over the call (legacy trap
1581
+ // parity): READ_SLOW = a global read window or non-plain node.
1582
+ let r = readNodeFast(i);
1583
+ if (r === READ_SLOW) r = read(i);
1584
+ if (!l || hasActiveOverride(i)) f = r === FORCE ? n : r;
1585
+ } else if (i !== undefined && (!l || hasActiveOverride(i))) {
1586
+ f = nodeValue(i, n);
1587
+ }
1588
+ }
1589
+ // Shallow stores serve data raw; store-proxy slots get boundary wrappers.
1590
+ if (e.s) return serveShallow(e, t, f);
1591
+ if (e.ch && !l && f !== null && typeof f === "object" && f[$TARGET] === undefined) f = resolveChainedRaw(e, t, f);
1592
+ if (i !== undefined) {
1593
+ // Wrap cache (see getNode): only wrappables are ever cached, so a hit
1594
+ // skips isWrappable too — pointer-compare replaces both checks.
1595
+ if (i.pxv === f && f !== undefined) return draftServe(e, i.px);
1596
+ if (!isWrappable(f)) return f;
1597
+ const n = wrapNext(f, e, t);
1598
+ i.px = n;
1599
+ i.pxv = f;
1600
+ return draftServe(e, n);
1601
+ }
1602
+ if (!isWrappable(f)) return f;
1603
+ return draftServe(e, wrapNext(f, e, t));
1604
+ }
1605
+
1606
+ /** §6c store-wide status gate for reads that DON'T flow through a node:
1607
+ * untracked/raw fallthrough must still throw while the derive is
1608
+ * uninitialized (seed invisibility, proj R23) or errored (memo parity).
1609
+ * TRACKED reads never call this — store nodes carry `_firewall`, so core
1610
+ * read() links the node and throws the firewall's error itself (the node
1611
+ * link is what wakes async-memo readers when the landing writes values;
1612
+ * the firewall link rides the same read). */ function firewallGate(e) {
1613
+ // Own-draft ops are exempt: an async derive's continuation (generator body
1614
+ // after an `await`/`yield`) runs OUTSIDE the sync write scope (inDraft is
1615
+ // already false), but its draft-proxy traps mark every op with the write
1616
+ // override. Those reads are the derive working its own draft (state.push
1617
+ // reading .length) — gating them throws NotReadyError back into the derive
1618
+ // itself, which the post-await read diagnostic (#2987) then escalates to a
1619
+ // reactivity halt. The gate exists for EXTERNAL readers (seed invisibility,
1620
+ // proj R23); the derive is the author.
1621
+ if (projectionWriteActive || getWriteOverride()) return;
1622
+ const t = e.fam?.node;
1623
+ if (t != null && t.S & (STATUS_UNINITIALIZED | STATUS_ERROR)) read(t);
1624
+ }
1625
+
1626
+ /** latest() pull (#3075): bring the projection computed up to date so the
1627
+ * read serves the IN-FLIGHT derivation — signal/memo parity, where core
1628
+ * read() routes latest() through a companion that recomputes speculatively.
1629
+ * The latest flag is suspended for the recompute (the derive's own reads
1630
+ * are normal reads), and latestPullActive marks any adoption it commits as
1631
+ * staged (see adoptPB) — the speculative swap must not leak to
1632
+ * committed-visibility readers before the flush. */ function pullProjectionForLatest(e) {
1633
+ const t = e.fam.node;
1634
+ if (t == null) return;
1635
+ const n = latestReadActive;
1636
+ setLatestReadActive(false);
1637
+ const r = latestPullActive;
1638
+ latestPullActive = true;
1639
+ try {
1640
+ prepareComputed(t, true);
1641
+ } finally {
1642
+ latestPullActive = r;
1643
+ setLatestReadActive(n);
1644
+ }
1645
+ }
1646
+
1647
+ const traps = {
1648
+ get(e, t, n) {
1649
+ // One typeof gates every brand-symbol compare off the hot string path
1650
+ // (four symbol comparisons per property read otherwise).
1651
+ if (typeof t !== "string") {
1652
+ if (t === $TARGET) return e;
1653
+ if (t === $PROXY) return n;
1654
+ if (t === $OWNER) return undefined;
1655
+ // ownership stamp: never a user key
1656
+ // refresh()/isPending resolve the projection computed through $REFRESH.
1657
+ if (t === $REFRESH) return e.fam?.node ?? undefined;
1658
+ if (t === $TRACK) {
1659
+ if (pendingCheckActive) witnessAffectsMark(e, t);
1660
+ if (e.fam !== null && getObserver() === null && !inDraft(e)) firewallGate(e);
1661
+ if (!inDraft(e) && getObserver() !== null) {
1662
+ read(getKeySetNode(e));
1663
+ // Structural chaining (§7b, #2864 / core R21): a chained backing's
1664
+ // $TRACK reads through to the INNER store's key-set — structural
1665
+ // notifications land on the source's own node, never on this
1666
+ // wrapper view's.
1667
+ const t = readSource(e);
1668
+ if (t[$TARGET] !== undefined) t[$TRACK];
1669
+ }
1670
+ return undefined;
1671
+ }
1672
+ // user symbols fall through to the generic path
1673
+ }
1674
+ if (pendingCheckActive) witnessAffectsMark(e, t);
1675
+ if (e.fam !== null && getObserver() === null && !inDraft(e)) firewallGate(e);
1676
+ // latest() pull (#3075): store traps never reach core read() without an
1677
+ // observer, so bring the projection computed up to date here — signal/
1678
+ // memo parity for latest() reads through a projection.
1679
+ if (e.fam !== null && latestReadActive && !inDraft(e) && !getWriteOverride()) pullProjectionForLatest(e);
1680
+ const r = readSource(e);
1681
+ // Overlay delete (#3044): a prototype overlay cannot shadow a delete, so
1682
+ // deleted keys are tracked aside and read as absent in the pending view.
1683
+ if (e.del !== null && r === e.pb && e.del.has(t)) {
1684
+ if (!inDraft(e) && getObserver() !== null) read(getNode(e, t, undefined));
1685
+ return undefined;
1686
+ }
1687
+ // Hot inline case: existing PLAIN node (non-accessor), unchained backing,
1688
+ // tracked read of a present data key — the dbmon/uibench effect re-read
1689
+ // shape. Skips serveDataKey's frame, the FORCE compare (only accessor
1690
+ // keys ever hold the sentinel), and isWrappable for primitives.
1691
+ // ONE node-map lookup serves this block and the accessor probe below
1692
+ // (nothing between them creates nodes).
1693
+ const i = e.n?.[t];
1694
+ if (e.ch === false && writeScopes === null) {
1695
+ const n = i;
1696
+ if (n !== undefined && n.acc !== true && getObserver() !== null) {
1697
+ let r = readNodeFast(n);
1698
+ if (r === READ_SLOW) r = read(n);
1699
+ if (r === null || typeof r !== "object") return r;
1700
+ if (e.s) return serveShallow(e, t, r);
1701
+ if (n.pxv === r) return n.px;
1702
+ if (isWrappable(r)) {
1703
+ const i = wrapNext(r, e, t);
1704
+ n.px = i;
1705
+ n.pxv = r;
1706
+ return i;
1707
+ }
1708
+ return r;
1709
+ }
1710
+ }
1711
+ // Accessor keys serve through Reflect.get with the PROXY receiver
1712
+ // (R20/R29: internal reads track; the node is linked for shape-change
1713
+ // notification but its value is never served). Accessor-ness comes from
1714
+ // the node's cached flag; the first TRACKED read (which creates the
1715
+ // node) probes once — untracked node-less reads take the plain path,
1716
+ // where a raw-receiver getter still returns correct committed values.
1717
+ // Tracking suppression is PER-TARGET (inDraft), never global: `writing`
1718
+ // counts every open setter anywhere, and a projection derive runs its
1719
+ // whole body inside one — a global gate silently swallowed EXTERNAL
1720
+ // absent-key/accessor subscriptions for every store read during any
1721
+ // derive, leaving nested projections permanently dependency-less when
1722
+ // their sources hadn't materialized yet (#3037).
1723
+ // First-read dedupe (create-floor slice 2): remember the probe verdict —
1724
+ // node creation downstream reuses it instead of re-scanning the
1725
+ // descriptor, but only when the probed object IS the one getNode would
1726
+ // scan (pb ?? v).
1727
+ let o = -1;
1728
+ {
1729
+ let l;
1730
+ if (i !== undefined) l = i.acc === true; else if (!inDraft(e) && getObserver() !== null) {
1731
+ l = isOwnAccessor(r, t);
1732
+ if (r === (e.pb ?? e.v)) o = l ? 1 : 0;
1733
+ } else l = false;
1734
+ if (l) {
1735
+ if (!inDraft(e) && getObserver() !== null) read(i ?? getNode(e, t, undefined, o));
1736
+ const l = Reflect.get(r, t, n);
1737
+ if (e.s) return serveShallow(e, t, l);
1738
+ return isWrappable(l) ? draftServe(e, wrapNext(l, e, t)) : l;
1739
+ }
1740
+ }
1741
+ // Plain-data fast path: no descriptor allocation per read.
1742
+ // Inherited pollution keys are never served (core R30) — checked before
1743
+ // the proto-function branch can leak `constructor`. Interned-string
1744
+ // compares beat a Set hash on this per-read path. Overlay pending
1745
+ // backings chain to the committed backing, so "own in the view" means
1746
+ // own on either layer (ownInView) — a genuine prototype method is one
1747
+ // that is own on NEITHER.
1748
+ const l = e.ovl && r === e.pb;
1749
+ if ((t === "constructor" || t === "__proto__" || t === "prototype") && !hasOwn.call(r, t) && !(l && hasOwn.call(e.v, t))) return undefined;
1750
+ let f = r[t];
1751
+ if (f === undefined ? !hasOwn.call(r, t) && !(l && hasOwn.call(e.v, t)) : false) {
1752
+ // Inherited: prototype getters/methods run with the proxy receiver.
1753
+ f = Reflect.get(r, t, n);
1754
+ if (typeof f === "function") return f;
1755
+ // proto methods untracked
1756
+ // Reading a currently-absent own key subscribes to it (R12) — for any
1757
+ // target OUTSIDE its own draft scope, even mid-setter (#3037, above).
1758
+ if (f === undefined && !inDraft(e)) {
1759
+ if (getObserver() !== null) read(getNode(e, t, undefined, o));
1760
+ const n = e.n?.[t];
1761
+ if (n) {
1762
+ const r = nodeValue(n, undefined);
1763
+ if (e.s) return serveShallow(e, t, r);
1764
+ return isWrappable(r) ? draftServe(e, wrapNext(r, e, t)) : r;
1765
+ }
1766
+ } else if (f === undefined && inDraft(e) && e.fam?.opt && draftSeesOverrides(e) &&
1767
+ // AUTHORITATIVE drafts (landing folds) never seed from overrides —
1768
+ // the caller's optimism is not truth (has-trap twin below).
1769
+ !authoritativeServe()) {
1770
+ const n = e.n?.[t];
1771
+ if (n !== undefined && visibleOverride(n)) f = unwrapOverride(n.o?.Ne);
1772
+ }
1773
+ if (e.s) return serveShallow(e, t, f);
1774
+ return isWrappable(f) ? draftServe(e, wrapNext(f, e, t)) : f;
1775
+ }
1776
+ if (typeof f === "function" && !hasOwn.call(r, t) && !(l && hasOwn.call(e.v, t))) return f;
1777
+ // proto method
1778
+ return serveDataKey(e, t, f, r, i, o);
1779
+ },
1780
+ has(e, t) {
1781
+ if (t === $TARGET || t === $PROXY || t === $TRACK) return true;
1782
+ if (t === $OWNER) return false;
1783
+ if (pendingCheckActive) witnessAffectsMark(e, t);
1784
+ if (e.fam !== null && getObserver() === null && !inDraft(e)) firewallGate(e);
1785
+ const n = readSource(e);
1786
+ let r = t in n;
1787
+ // Overlay deletes read as absent in the pending view (#3044).
1788
+ if (r && e.del !== null && n === e.pb && e.del.has(t)) r = false;
1789
+ if (!inDraft(e)) {
1790
+ if (getObserver() !== null) {
1791
+ const n = getHasNode(e, t, r);
1792
+ // Authoritative-view readers get the right answer for free: core read()
1793
+ // skips the override arm for them, so nv is authoritative presence.
1794
+ const i = read(n);
1795
+ if (hasActiveOverride(n)) r = !!i;
1796
+ } else if (!authoritativeServe()) {
1797
+ const n = e.h?.[t];
1798
+ if (n !== undefined && visibleOverride(n)) r = !!unwrapOverride(n.o?.Ne);
1799
+ }
1800
+ } else if (e.fam?.opt && draftSeesOverrides(e) && !authoritativeServe()) {
1801
+ const n = e.h?.[t];
1802
+ if (n !== undefined && hasActiveOverride(n)) r = !!unwrapOverride(n.o?.Ne);
1803
+ }
1804
+ return r;
1805
+ },
1806
+ ownKeys(e) {
1807
+ if (pendingCheckActive) witnessAffectsMark(e);
1808
+ if (e.fam !== null && getObserver() === null && !inDraft(e)) firewallGate(e);
1809
+ if (!inDraft(e) && getObserver() !== null) read(getKeySetNode(e));
1810
+ return visibleKeys(e, readSource(e));
1811
+ },
1812
+ getOwnPropertyDescriptor(e, t) {
1813
+ if (t === $OWNER) return undefined;
1814
+ // A descriptor read is a PRESENCE read: it subscribes to the key's
1815
+ // presence node and witnesses affects()/isPending() exactly as `in` does
1816
+ // (structural oracle, 2026-09-17 — the trap read no node before, so a
1817
+ // render effect inspecting a key through getOwnPropertyDescriptor never
1818
+ // re-ran for an optimistic add or delete, and an isPending() probe over
1819
+ // it witnessed nothing). The value it reports rides the value node's
1820
+ // view through visibleDescriptor.
1821
+ if (pendingCheckActive) witnessAffectsMark(e, t);
1822
+ if (e.fam !== null && getObserver() === null && !inDraft(e)) firewallGate(e);
1823
+ const n = readSource(e);
1824
+ const r = visibleDescriptor(e, n, t);
1825
+ if (!inDraft(e) && getObserver() !== null) {
1826
+ // The node is born from the source's presence (as `has` births it),
1827
+ // not the override-adjusted answer.
1828
+ let r = t in n;
1829
+ if (r && e.del !== null && n === e.pb && e.del.has(t)) r = false;
1830
+ read(getHasNode(e, t, r));
1831
+ }
1832
+ if (r === undefined) return undefined;
1833
+ // Array targets carry a real non-configurable `length` the proxy
1834
+ // invariant forces us to report faithfully; everything else reports
1835
+ // configurable via target indirection (core R51).
1836
+ if (!(t === "length" && Array.isArray(e))) r.configurable = true;
1837
+ return r;
1838
+ },
1839
+ set(e, t, n) {
1840
+ // Writes require the target's draft scope OR the projection write
1841
+ // override (post-await async draft writes arrive outside any window);
1842
+ // everything else is silently ignored (R23).
1843
+ const r = inDraft(e);
1844
+ const i = !r && getWriteOverride();
1845
+ if (!r && !i) return true;
1846
+ if (t === "__proto__") return true;
1847
+ // pollution guard (core R30)
1848
+ // Unwrap BEFORE ensurePB: unwrapValue materializes a self-referencing
1849
+ // draft's overlay (replacing target.pb), so a pb local captured earlier
1850
+ // would be the abandoned overlay and the write would vanish.
1851
+ // Shallow slots store what was written VERBATIM — another store's proxy
1852
+ // passes through by reference (#2932; markRawOne skips proxies), while
1853
+ // deep stores unwrap to raw backings.
1854
+ const o = e.s ? n : unwrapValue(n);
1855
+ const l = ensurePB(e);
1856
+ pendingNotify.add(e);
1857
+ // Array length writes implicitly delete indices — the written-keys bound
1858
+ // can't see them, so poison to the full scan for this batch. Index
1859
+ // writes implicitly GROW length, so arrays always record it alongside.
1860
+ if (Array.isArray(l)) {
1861
+ if (t === "length") e.wk = WK_ALL; else if (e.wk !== WK_ALL) {
1862
+ const n = e.wk ??= new Set;
1863
+ n.add(t);
1864
+ n.add("length");
1865
+ }
1866
+ } else {
1867
+ if (e.wk !== WK_ALL) (e.wk ??= new Set).add(t);
1868
+ // Live own-key estimate for the overlay/clone choice (#3360): `in`
1869
+ // sees through an overlay to the committed keys, so this counts keys
1870
+ // NEW to the container. Deletes are not un-counted (a stale high
1871
+ // count only picks the overlay a little early).
1872
+ if (!(t in l)) e.kc++;
1873
+ }
1874
+ // Own data keys literally named "prototype"/"constructor" land as data —
1875
+ // defineProperty sidesteps a proto-chain setter named the same.
1876
+ if (UNSAFE_KEYS.has(t)) {
1877
+ Object.defineProperty(l, t, {
1878
+ value: o,
1879
+ writable: true,
1880
+ enumerable: true,
1881
+ configurable: true
1882
+ });
1883
+ if (e.del !== null) e.del.delete(t);
1884
+ return true;
1885
+ }
1886
+ // Overlay first-write DEFINES the own key: assignment through the proto
1887
+ // chain would reject on a non-writable committed property (the clone
1888
+ // path normalized descriptors for exactly this — R51 parity). A
1889
+ // plain-data-graded backing (sc 2, owned: every slot writable) takes the
1890
+ // bare assignment — it lands as an own key on the overlay all the same.
1891
+ if (e.ovl && e.sc !== 2 && !hasOwn.call(l, t)) {
1892
+ Object.defineProperty(l, t, {
1893
+ value: o,
1894
+ writable: true,
1895
+ enumerable: true,
1896
+ configurable: true
1897
+ });
1898
+ } else l[t] = o;
1899
+ if (e.del !== null) e.del.delete(t);
1900
+ // Shallow ingest: written records are sticky raw-marked (one entity is
1901
+ // never both deep-wrapped and raw — R41/#2932, shared invariant).
1902
+ if (e.s && o !== null && typeof o === "object") markRawOne(o);
1903
+ // Override-mode (post-await draft) writes have no setter exit — notify
1904
+ // per-op (setSignal equality-gates repeats).
1905
+ if (i) notifyWrites(e);
1906
+ return true;
1907
+ },
1908
+ defineProperty(e, t, n) {
1909
+ const r = inDraft(e);
1910
+ const i = !r && getWriteOverride();
1911
+ if (!r && !i) return true;
1912
+ if (t === "__proto__") return true;
1913
+ if (n.get || n.set) e.a = true;
1914
+ // Unwrap before ensurePB (see the set trap: self-reference materializes).
1915
+ if ("value" in n) n = {
1916
+ ...n,
1917
+ value: unwrapValue(n.value)
1918
+ };
1919
+ const o = ensurePB(e);
1920
+ // A non-default data descriptor (or an accessor) leaves the plain-data
1921
+ // grade: the key reaches the committed backing as defined, so the spread
1922
+ // clone and bare-assignment paths no longer describe it.
1923
+ if (e.a || !(n.enumerable && n.writable && n.configurable)) e.sc = 1;
1924
+ pendingNotify.add(e);
1925
+ if (e.wk !== WK_ALL) (e.wk ??= new Set).add(t);
1926
+ Object.defineProperty(o, t, n);
1927
+ if (e.del !== null) e.del.delete(t);
1928
+ if (i) notifyWrites(e);
1929
+ return true;
1930
+ },
1931
+ deleteProperty(e, t) {
1932
+ const n = inDraft(e);
1933
+ const r = !n && getWriteOverride();
1934
+ if (!n && !r) return true;
1935
+ const i = ensurePB(e);
1936
+ pendingNotify.add(e);
1937
+ if (e.wk !== WK_ALL) (e.wk ??= new Set).add(t);
1938
+ delete i[t];
1939
+ // A prototype overlay cannot shadow a delete of a committed key —
1940
+ // record it aside (#3044); reads/has/ownKeys/commit consult the set.
1941
+ if (e.ovl && hasOwn.call(e.v, t)) (e.del ??= new Set).add(t);
1942
+ if (r) notifyWrites(e);
1943
+ return true;
1944
+ }
1945
+ };
1946
+
1947
+ /** Low-level setter primitive: opens write mode on a next proxy, runs `fn`,
1948
+ * emits write-time notifications at outermost exit, applies returned
1949
+ * replacements as adoptions. `guard=false` skips the dev guards (owned-scope
1950
+ * write, thenable result) — projection recomputes legitimately write from
1951
+ * inside their computed, and their async derive is handled by the recompute,
1952
+ * not returned through here. */ function storeSetterNext(e, t, n = true) {
1953
+ const r = e[$TARGET];
1954
+ const i = writeScopes;
1955
+ writeScopes = new Set;
1956
+ writeScopes.add(scopeKey(r));
1957
+ writing++;
1958
+ let o;
1959
+ try {
1960
+ // No untrack: the writing flag already disables store-node linking
1961
+ // (draft reads never self-track, proj R2), while EXTERNAL reads (signals
1962
+ // inside a projection derive) must keep tracking — they are the derive's
1963
+ // dependencies.
1964
+ o = t(e);
1965
+ } finally {
1966
+ writing--;
1967
+ writeScopes = i;
1968
+ // Outermost setter exit: emit write-time notifications (setSignal per
1969
+ // changed observed key) so transition holds and lanes engage now.
1970
+ if (writing === 0 && pendingNotify.size) {
1971
+ const e = [ ...pendingNotify ];
1972
+ pendingNotify.clear();
1973
+ for (const t of e) notifyWrites(t);
1974
+ }
1975
+ }
1976
+ if (o !== undefined && o !== e && isWrappable(o)) {
1977
+ // Returned replacement: on an optimistic family (outside authoritative
1978
+ // writes) the replacement is itself an optimistic edit — diff it against
1979
+ // the visible view as engine writes (reverts at settle). Otherwise it is
1980
+ // an adoption of the incoming object (unowned).
1981
+ if (r.fam?.opt && !projectionWriteActive && !getWriteOverride()) {
1982
+ optHooks.notifyOptimisticWrites(r, unwrapValue(o));
1983
+ } else {
1984
+ adoptPB(r, unwrapValue(o));
1985
+ }
1986
+ }
1987
+ if (writing === 0 && heldAdoptions.size) stageHeldAdoptions();
1988
+ }
1989
+
1990
+ // Affects integration: the legacy affects machinery reads next targets
1991
+ // structurally (aliased field names); only node CREATION dispatches here.
1992
+ setNextAffectsNodeResolver((e, t) => t === $AFFECTS ? getNode(e, $AFFECTS, undefined) : getNode(e, t, (e.pb ?? e.v)[t]));
1993
+
1994
+ function createStoreNext(e, t = false) {
1995
+ const n = wrapNext(e);
1996
+ if (t) {
1997
+ n[$TARGET].s = true;
1998
+ markRawIngest(e);
1999
+ }
2000
+ {
2001
+ const e = getOwner();
2002
+ // Dev-tier graph registration (owner signal lists, onGraph); the
2003
+ // `_owner` write itself never reaches the proxy, see storeOwners.
2004
+ registerGraph(n, e);
2005
+ // Only once the engine is installed, like the node stamping it feeds: a
2006
+ // WeakMap.set per fresh store is a growing ephemeron table (~+35% on the
2007
+ // 2000-store create+commit shape, CodSpeed −11.7% on #3380's first cut)
2008
+ // and, disabled, buys nothing — a store created before enable() has no
2009
+ // excluded owner to inherit either way.
2010
+ if (attrHooks !== null) storeOwners.set(n[$TARGET], e);
2011
+ }
2012
+ const setter = e => storeSetterNext(n, e);
2013
+ return [ n, setter ];
2014
+ }
2015
+
2016
+ // ---------------------------------------------------------------------------
2017
+ // snapshot (next targets): the backing IS the plain raw graph — zero copy.
2018
+ // Sees pending (R27) by reading pb. Chained/owned-copy caching lands with the
2019
+ // utilities increment; this covers the createStore-suite contract.
2020
+ /** True when `proxy` is a SHALLOW store (children served verbatim, slots
2021
+ * replaced by reference — #2932). The list driver uses this to choose the
2022
+ * slot-patch channel (collected row bodies) over per-record registration. */ function storeIsShallow(e) {
2023
+ const t = e?.[$TARGET];
2024
+ return t !== undefined && t.s === true;
2025
+ }
2026
+
2027
+ /** True when `proxy` belongs to a projection/optimistic FAMILY. The list
2028
+ * driver must DECLINE family arrays (external audit finding): family
2029
+ * structural changes never emit row/slot ops (the setter channel is
2030
+ * fam-gated; optimistic writes ride node overrides), and the proxy identity
2031
+ * is stable so the each-watch cannot catch the change either — an engaged
2032
+ * list would freeze on optimistic/projection structural updates. Record-
2033
+ * level family patches are unaffected (they have their own emission). */ function storeHasFamily(e) {
2034
+ const t = e?.[$TARGET];
2035
+ return t !== undefined && t.fam !== null;
2036
+ }
2037
+
2038
+ /** True when `proxy` belongs to an OPTIMISTIC family specifically. The list
2039
+ * driver declines these (audit finding, narrowed): optimistic user writes
2040
+ * ride node-level overrides — they never enter the reconcile walk, so no
2041
+ * row/slot ops are emitted and an engaged list would freeze on optimistic
2042
+ * structural changes. PROJECTION (non-optimistic) families are drivable:
2043
+ * their recomputes go through the reconcile walk, whose emissions are
2044
+ * transition-stamped in the apply queue like any other (equivalence-matrix
2045
+ * gated). Re-admitting optimistic families requires a lane-timed structural
2046
+ * emission mirroring emitPatchOptimistic, plus revert resync. */ function storeHasOptimisticFamily(e) {
2047
+ const t = e?.[$TARGET];
2048
+ return t !== undefined && t.fam?.opt === true;
2049
+ }
2050
+
2051
+ // ---------------------------------------------------------------------------
2052
+ // visibility: what a reader sees on a record — ONE rule for the ownKeys /
2053
+ // getOwnPropertyDescriptor traps and the deep() walk (#3323). The walk used
2054
+ // to re-derive the trap rules over raw backings and missed each new one in
2055
+ // turn (the #3044 overlay merge, then #3323's chain, then optimistic presence
2056
+ // and value overrides); sharing the body makes parity structural.
2057
+ /** Keys visible on `target` served from `src` (= readSource(target)): the
2058
+ * pending-overlay merge (#3044) and, on optimistic families, presence-node
2059
+ * overrides (§6, FINDING-2's fix). Draft reads before the first write overlay
2060
+ * too (pb, once created, is seeded with the view). Authoritative-view reads
2061
+ * (until()'s predicate, truth-author drafts) skip the overlay. */ function visibleKeys(e, t) {
2062
+ let n;
2063
+ if (e.ovl && t === e.pb) {
2064
+ // Overlay merge (#3044): committed keys in their order, then this
2065
+ // batch's NEW keys, minus deletes.
2066
+ n = Reflect.ownKeys(e.v);
2067
+ const r = e.del;
2068
+ if (r !== null && r.size !== 0) n = n.filter(e => !r.has(e));
2069
+ for (const r of Reflect.ownKeys(t)) {
2070
+ if (!hasOwn.call(e.v, r)) n.push(r);
2071
+ }
2072
+ } else n = Reflect.ownKeys(t);
2073
+ // Drop the $OWNER stamp (owned backings carry it as an own enumerable
2074
+ // symbol). Symbols enumerate last, so the scan stops at the first string.
2075
+ for (let e = n.length - 1; e >= 0 && typeof n[e] === "symbol"; e--) {
2076
+ if (n[e] === $OWNER) {
2077
+ n.splice(e, 1);
2078
+ break;
2079
+ }
2080
+ }
2081
+ if (!authoritativeServe() && e.fam?.opt && e.h !== null && (!inDraft(e) || draftSeesOverrides(e))) {
2082
+ let t = null;
2083
+ const r = inDraft(e);
2084
+ for (const i of Reflect.ownKeys(e.h)) {
2085
+ const o = e.h[i];
2086
+ if (!(r ? hasActiveOverride(o) : visibleOverride(o))) continue;
2087
+ t ??= new Set(n);
2088
+ if (unwrapOverride(o.o?.Ne)) t.add(i); else t.delete(i);
2089
+ }
2090
+ if (t !== null) return [ ...t ];
2091
+ }
2092
+ return n;
2093
+ }
2094
+
2095
+ /** The data/accessor descriptor visible for `key` on `target` served from
2096
+ * `src`: overlay (#3044 — unwritten keys live on the committed backing,
2097
+ * deleted keys are absent) and optimistic presence overrides (an opt delete
2098
+ * hides the key; an opt add synthesizes a data descriptor from the value
2099
+ * node). `configurable` is the trap's concern (proxy invariant). */ function visibleDescriptor(e, t, n) {
2100
+ let r = Object.getOwnPropertyDescriptor(t, n);
2101
+ if (e.ovl && t === e.pb) {
2102
+ if (e.del !== null && e.del.has(n)) return undefined;
2103
+ if (r === undefined) r = Object.getOwnPropertyDescriptor(e.v, n);
2104
+ }
2105
+ if (!authoritativeServe() && e.fam?.opt && !inDraft(e)) {
2106
+ const t = e.h?.[n];
2107
+ if (t !== undefined && visibleOverride(t)) {
2108
+ if (!unwrapOverride(t.o?.Ne)) return undefined;
2109
+ // opt delete
2110
+ if (r === undefined) {
2111
+ const t = e.n?.[n];
2112
+ return {
2113
+ value: t !== undefined ? nodeValue(t, undefined) : undefined,
2114
+ writable: true,
2115
+ enumerable: true,
2116
+ configurable: true
2117
+ };
2118
+ }
2119
+ }
2120
+ }
2121
+ return r;
2122
+ }
2123
+
2124
+ /** Tracking deep snapshot (`deep()` for next targets): subscribes to the
2125
+ * key-set and deep-witness node at every reachable level, then returns the
2126
+ * plain view. Shared references and cycles handled via the visited set. */ function deepNext(e) {
2127
+ const t = e?.[$TARGET];
2128
+ if (t === undefined || t.px !== e) return e;
2129
+ const n = new Set;
2130
+ // One membership node + one deep-witness node PER RECORD (legacy $TRACK
2131
+ // parity): the walk stays O(records) in subscriptions instead of O(paths)
2132
+ // in per-key nodes, and it walks TARGETS directly — no per-child proxy
2133
+ // round-trip (wrapNext → proxy → $TARGET trap) on the re-walk every
2134
+ // effect run performs.
2135
+ // Resolve `child` (a raw or a stored proxy found under `t`) to the target
2136
+ // that `t`'s family serves for it — created on first visit, as the get trap
2137
+ // would. Undefined = leaf (unwrappable or raw-marked).
2138
+ const childTarget = (e, t, n) => {
2139
+ let r = lookupTarget(t, e.fam);
2140
+ if (r === undefined) {
2141
+ if (!isWrappable(t)) return undefined;
2142
+ wrapNext(t, e, n);
2143
+ // Stored proxies (chained slots) that this family passes through
2144
+ // resolve to their own target.
2145
+ r = lookupTarget(t, e.fam) ?? t[$TARGET];
2146
+ }
2147
+ return r;
2148
+ };
2149
+ const walkT = e => {
2150
+ const t = readSource(e);
2151
+ if (n.has(t)) return;
2152
+ n.add(t);
2153
+ read(getKeySetNode(e));
2154
+ read(getDeepNode(e));
2155
+ // Chained backing (§7b): the committed backing IS another store's proxy.
2156
+ // Writes to the inner store bump the INNER record's witnesses; this
2157
+ // target's k/dk hear only its own family's writes (optimistic overrides).
2158
+ // Read through the whole chain — the $TRACK trap's rule (#2864 / R21)
2159
+ // applied to deep() (#3323). From `t.v`, not `src`: a pending backing is a
2160
+ // raw clone and would hide the chain. Non-chained targets pay one flag.
2161
+ for (let t = e; t.ch; ) {
2162
+ t = t.v[$TARGET];
2163
+ read(getKeySetNode(t));
2164
+ read(getDeepNode(t));
2165
+ }
2166
+ // Keys and children exactly as the traps serve them — the overlay merge
2167
+ // (#3044/#3283: a bare ownKeys over a pending backing mid-flush dropped
2168
+ // every untouched child from the re-subscribing effect's dependencies)
2169
+ // and optimistic presence overrides (a row added under a held action
2170
+ // lives in `h`/`n`, not the committed backing; the walk never reached its
2171
+ // record, so deep() was deaf to every write on it until settle).
2172
+ const r = e.fam?.opt === true;
2173
+ for (const n of visibleKeys(e, t)) {
2174
+ const i = visibleDescriptor(e, t, n);
2175
+ if (i === undefined) continue;
2176
+ if (i.get || i.set) {
2177
+ e.a = true;
2178
+ continue;
2179
+ // accessors track through their own reads when invoked
2180
+ }
2181
+ let o = i.value;
2182
+ // An active value override on an optimistic node shadows the backing's
2183
+ // child (an optimistic replacement `d[i] = {...}`) — follow what reads
2184
+ // serve, as nodeValue's leading arm does.
2185
+ if (r) {
2186
+ const t = e.n?.[n];
2187
+ if (t !== undefined && hasActiveOverride(t) && !authoritativeServe()) o = unwrapOverride(t.o.Ne);
2188
+ }
2189
+ if (o === null || typeof o !== "object") continue;
2190
+ // Through a chain the descriptor yields the INNERMOST raw: resolve it to
2191
+ // the inner family's proxy so this level wraps the chained `view[i]` the
2192
+ // get trap serves, never a fresh non-chained wrapper of the base raw.
2193
+ if (e.ch && o[$TARGET] === undefined) o = resolveChainedRaw(e, n, o);
2194
+ const l = childTarget(e, o, n);
2195
+ if (l === undefined) continue;
2196
+ // raw-marked: leaf by contract
2197
+ walkT(l);
2198
+ }
2199
+ };
2200
+ walkT(t);
2201
+ return snapshotNext(e);
2202
+ }
2203
+
2204
+ /**
2205
+ * Snapshot with per-object registration resolution (RUL-12 DAG ruling): every
2206
+ * reachable wrappable resolves through its target's CURRENT backing, so
2207
+ * privatized subtrees are seen through any parent path. Identity-preserving:
2208
+ * a subtree with no substitutions below returns its own object (zero copy for
2209
+ * settled, never-diverged graphs).
2210
+ */ function snapshotNext(e) {
2211
+ const t = e?.[$TARGET];
2212
+ return snapshotWalk(e, new Map, t?.fam ?? null);
2213
+ }
2214
+
2215
+ function snapshotWalk(e, t, n) {
2216
+ if (e === null || typeof e !== "object") return e;
2217
+ // Resolve through the registration: proxies AND raws map to their target's
2218
+ // current backing (stale raw pointers through other parents resolve here).
2219
+ // Loops for chained backings (§7b: a projection's backing can be another
2220
+ // store's proxy — snapshot unwraps to the base raw).
2221
+ let r = e;
2222
+ // Chained backings can pass through several targets; optimistic overrides
2223
+ // on OUTER targets shadow the chain (§7b), so collect every opt target
2224
+ // encountered and compose their views over the resolved base, innermost
2225
+ // outward.
2226
+ let i = null;
2227
+ for (let e = true; ;e = false) {
2228
+ const t = r?.[$TARGET]?.v !== undefined;
2229
+ let o = t ? r[$TARGET] : undefined;
2230
+ if (o === undefined && n !== null) o = lookupTarget(r, n);
2231
+ if (o === undefined) o = lookupTarget(r, null);
2232
+ if (o === undefined) break;
2233
+ // Entering a level from a RAW below a chained family: the raw resolves to
2234
+ // the INNER store's target, but this family's wrapper for it — keyed by
2235
+ // the inner proxy, §7b — is where the outer overrides live. Start from
2236
+ // the wrapper so they compose (#3323: a nested optimistic write on a view
2237
+ // row was served by reads but missing from deep()/snapshot()). Entry only:
2238
+ // the descent then runs wrapper → inner → raw and terminates.
2239
+ if (e && !t && n !== null && o.fam !== n) {
2240
+ const e = n.map.get(o.px);
2241
+ if (e !== undefined) o = e;
2242
+ }
2243
+ if (o.fam !== null) n = o.fam;
2244
+ if (o.fam?.opt === true) (i ??= []).push(o);
2245
+ // The shared visibility decision (#3147): the speculative peek serves
2246
+ // pending staging, but a HELD landing is masked to committed exactly as
2247
+ // it is for per-key readers — the two families must answer alike while
2248
+ // a transaction holds store landings.
2249
+ const l = pendingBackingVisible(o, true);
2250
+ // Snapshot runs mid-flush (tracked memos execute before commit), so a
2251
+ // pending prototype overlay must present as a REAL merged container.
2252
+ if (l && o.ovl) materializePB(o);
2253
+ const f = l ? o.pb : o.v;
2254
+ if (f === r) break;
2255
+ r = f;
2256
+ }
2257
+ if (!isWrappable(r)) return r;
2258
+ // Optimistic families: compose the visible view; a composed view is a fresh
2259
+ // object and snapshots via the owned/copy path (pinned `not.toBe` identity).
2260
+ if (i !== null) {
2261
+ let e = r;
2262
+ for (let t = i.length - 1; t >= 0; t--) e = optHooks.optimisticView(i[t], e);
2263
+ if (e !== r) {
2264
+ const i = t.get(r);
2265
+ if (i !== undefined) return i;
2266
+ const o = Array.isArray(e);
2267
+ const l = o ? [] : Object.create(Object.getPrototypeOf(e));
2268
+ t.set(r, l);
2269
+ for (const r of Reflect.ownKeys(e)) {
2270
+ if (o && r === "length" || r === $OWNER) continue;
2271
+ const i = e[r];
2272
+ l[r] = i !== null && typeof i === "object" ? snapshotWalk(i, t, n) : i;
2273
+ }
2274
+ if (o) l.length = e.length;
2275
+ return l;
2276
+ }
2277
+ }
2278
+ const o = t.get(r);
2279
+ if (o !== undefined) return o;
2280
+ // OWNED (written) subtrees snapshot as copies (§7b: identity is only for
2281
+ // subtrees "unmodified relative to source"): non-enumerable symbols are
2282
+ // excluded (recon-snap R29), and the copy registers BEFORE descent so
2283
+ // cycles keep identity (FINDING-3).
2284
+ if (isOwned(r)) {
2285
+ const e = Array.isArray(r);
2286
+ const i = e ? [] : Object.create(Object.getPrototypeOf(r));
2287
+ t.set(r, i);
2288
+ for (const o of Reflect.ownKeys(r)) {
2289
+ if (e && o === "length" || o === $OWNER) continue;
2290
+ const l = Object.getOwnPropertyDescriptor(r, o);
2291
+ if (typeof o === "symbol" && !l.enumerable) continue;
2292
+ if (l.get || l.set) {
2293
+ Object.defineProperty(i, o, l);
2294
+ continue;
2295
+ }
2296
+ const f = l.value;
2297
+ const s = f !== null && typeof f === "object" ? snapshotWalk(f, t, n) : f;
2298
+ if (l.enumerable && l.writable && l.configurable) i[o] = s; else Object.defineProperty(i, o, {
2299
+ ...l,
2300
+ value: s
2301
+ });
2302
+ }
2303
+ if (e && i.length !== r.length) i.length = r.length;
2304
+ return i;
2305
+ }
2306
+ // UNOWNED (shared/user) subtrees keep identity unless a descendant
2307
+ // substituted; copy-on-substitution preserves the documented CoW contract.
2308
+ t.set(r, r);
2309
+ let l = null;
2310
+ for (const e of Reflect.ownKeys(r)) {
2311
+ const i = Object.getOwnPropertyDescriptor(r, e);
2312
+ if (!i || i.get || i.set) continue;
2313
+ const o = i.value;
2314
+ if (o === null || typeof o !== "object") continue;
2315
+ const f = snapshotWalk(o, t, n);
2316
+ if (f !== o) {
2317
+ if (l === null) {
2318
+ l = Array.isArray(r) ? [ ...r ] : Object.create(Object.getPrototypeOf(r), Object.getOwnPropertyDescriptors(r));
2319
+ t.set(r, l);
2320
+ }
2321
+ l[e] = f;
2322
+ }
2323
+ }
2324
+ return l ?? r;
2325
+ }
2326
+
2327
+ export { adoptPB, arrayStructureChanged, authoritativeRead, authoritativeServe, bumpDeep, createStoreNext, deepNext, getHasNode, getKeySetNode, getNode, hasAccessorFlag, hasActiveOverride, heldMaskView, materializePB, membershipChanged, notifyFold, notifyFoldTail, notifyKeyDiff, notifyKeyValue, runAuthoritative, snapshotNext, stagedTruthPB, storeHasFamily, storeHasOptimisticFamily, storeIsShallow, storeSetterNext, targetsEqual, unwrapValue, visibleOverride, wrapNext };