@solidjs/signals 2.0.0-rc.6 → 2.0.0-rc.8

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