@rbxts/scribe 2.5.0

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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +21 -0
  3. package/README.md +100 -0
  4. package/Scribe-source-map.json +1 -0
  5. package/licenses/ProfileStore-Apache-2.0.txt +201 -0
  6. package/package.json +32 -0
  7. package/src/Client/DebugHook.luau +457 -0
  8. package/src/Client/init.luau +1607 -0
  9. package/src/Internal/Addons.luau +68 -0
  10. package/src/Internal/Big.luau +582 -0
  11. package/src/Internal/Budget.luau +377 -0
  12. package/src/Internal/Clock.luau +75 -0
  13. package/src/Internal/Config.luau +17 -0
  14. package/src/Internal/Conform.luau +400 -0
  15. package/src/Internal/Datatypes.luau +653 -0
  16. package/src/Internal/Defaults.luau +12 -0
  17. package/src/Internal/Derived.luau +428 -0
  18. package/src/Internal/Exchange.luau +556 -0
  19. package/src/Internal/ExchangeLeg.luau +1368 -0
  20. package/src/Internal/ExchangeVerdict.luau +179 -0
  21. package/src/Internal/Failure.luau +148 -0
  22. package/src/Internal/Health.luau +320 -0
  23. package/src/Internal/LeaderboardDiagnostics.luau +36 -0
  24. package/src/Internal/Log.luau +378 -0
  25. package/src/Internal/Marker.luau +76 -0
  26. package/src/Internal/Metrics.luau +152 -0
  27. package/src/Internal/Node.luau +3954 -0
  28. package/src/Internal/Profile.luau +69 -0
  29. package/src/Internal/Rng.luau +83 -0
  30. package/src/Internal/Sched.luau +56 -0
  31. package/src/Internal/Signal.luau +199 -0
  32. package/src/Internal/Store/ProfileStore.luau +3019 -0
  33. package/src/Internal/Store/init.luau +18 -0
  34. package/src/Internal/StudioCodec.luau +155 -0
  35. package/src/Internal/Template.luau +1848 -0
  36. package/src/Internal/Transport.luau +169 -0
  37. package/src/Internal/Util.luau +517 -0
  38. package/src/Internal/Version.luau +4 -0
  39. package/src/Internal/Wire.luau +1283 -0
  40. package/src/Server/Analytics.luau +223 -0
  41. package/src/Server/Commands.luau +728 -0
  42. package/src/Server/DebugHook.luau +1490 -0
  43. package/src/Server/Exchanges.luau +737 -0
  44. package/src/Server/Leaderboards.luau +2143 -0
  45. package/src/Server/Monetization.luau +3212 -0
  46. package/src/Server/Persistence.luau +3775 -0
  47. package/src/Server/Replication.luau +1253 -0
  48. package/src/Server/ServerStore.luau +81 -0
  49. package/src/Server/Timed.luau +579 -0
  50. package/src/Server/init.luau +672 -0
  51. package/src/Types.luau +480 -0
  52. package/src/init.luau +2231 -0
  53. package/types/api.d.ts +252 -0
  54. package/types/common.d.ts +355 -0
  55. package/types/index.d.ts +226 -0
  56. package/types/schema.d.ts +276 -0
@@ -0,0 +1,1368 @@
1
+ --!strict
2
+ -- The total-apply primitive for ClaimExchange: moves value off a declared path into the
3
+ -- owner's reserved root and later back onto a declared path, proving every step from a
4
+ -- return value AND a post-mutation re-read. Never Increment, Decrement or a bare Insert:
5
+ -- those can no-op or clamp and still report success.
6
+ --
7
+ -- Three invariants close the ways both proofs pass on a write that did nothing:
8
+ -- I1 NO-OP INTERLOCK. An intended post-state equal to the current state is refused.
9
+ -- I2 VACANCY. A credit lands only on a destination proved absent.
10
+ -- I3 SOLVENCY. A quantity leg never drives a balance below its declared floor, and a
11
+ -- path with no floor is not exchangeable.
12
+ --
13
+ -- Escrow and Deliver return RunTransaction's (ok, err). pcall false is INDETERMINATE:
14
+ -- reconcile, never retry blind. pcall true with ok false is reverted; ok true committed.
15
+ --
16
+ -- PRECONDITION: no listener on this tree may write or yield from a change handler.
17
+ -- OnChildChanged is not deferred, so it fires inside the settle transaction, where a
18
+ -- yield becomes a rollback and a write during the drain lands and stays.
19
+
20
+ local Clock = require(script.Parent.Clock)
21
+ local Template = require(script.Parent.Template)
22
+ local Util = require(script.Parent.Util)
23
+ local Big = require(script.Parent.Big)
24
+
25
+ local ExchangeLeg = {}
26
+
27
+ local RESERVED = Template.RESERVED_ROOT
28
+ local MAX_SAFE = 9007199254740992
29
+
30
+ export type Leg = {
31
+ Path: { string | number },
32
+ Kind: string, -- "Key", "Qty" or "Stack"
33
+ Key: any?, -- Key and Stack legs: dict key, set member, or array value
34
+ Amount: number?, -- Qty and Stack legs
35
+ Value: any?, -- filled by Escrow with the PACKED payload
36
+ }
37
+
38
+ --- The declared rules for one exchangeable path, resolved once at startup.
39
+ ---
40
+ --- Held on `ctx.Plans` rather than on the leg: a parked delivery can outlive the server
41
+ --- that staked it, and config in the record is config a later fix cannot reach.
42
+ export type Plan = {
43
+ Count: string?, -- Stack: the counting element field. nil when the element IS the count.
44
+ Ignore: { [string]: true }, -- fields that do not travel with the item
45
+ }
46
+
47
+ --- Raise with the module's prefix. Level 0 because a leg failure is about the exchange,
48
+ --- not about the line inside this module that noticed it.
49
+ local function fail(message: string): never
50
+ error(`ExchangeLeg: {message}`, 0)
51
+ end
52
+
53
+ --- Prove a value is present, and return it, so the guard narrows. Luau does not treat a
54
+ --- call to `fail` as terminating a branch even though it is declared `never`, so after a
55
+ --- plain `if x == nil then fail(...) end` the value is still optional to the checker.
56
+ local function present<T>(value: T?, message: string): T
57
+ if value == nil then
58
+ fail(message)
59
+ end
60
+ return value :: T
61
+ end
62
+
63
+ --- Walk to a schema node without Template.Resolve, which returns the deepest static
64
+ --- ANCESTOR rather than nil and so lets a typo resolve to a parent.
65
+ local function resolveStrict(compiled: any, path: { string | number }): any
66
+ local node = compiled.Root
67
+ for index, segment in path do
68
+ if node == nil or node.Kind == "leaf" then
69
+ fail(`path "{Util.pathString(path)}" descends through a leaf at "{segment}"`)
70
+ end
71
+ node = present(
72
+ Template.ChildSchema(node, segment),
73
+ `path "{Util.pathString(path)}" has no declared field "{segment}"`
74
+ )
75
+ -- A synthesized AnyChild is what an undeclared key resolves to. Accepting it
76
+ -- would make every misspelling a valid path.
77
+ if node.Kind == "any" and node.IsElement ~= true then
78
+ fail(`path "{Util.pathString(path)}" segment {index} ("{segment}") is not a declared field`)
79
+ end
80
+ end
81
+ return node
82
+ end
83
+
84
+ --- The stored parent table and key for a path, with no accessor and no unpack.
85
+ --- LiveData only: a non-persisted root is refused at registration, so routing to the
86
+ --- session store here would contradict that refusal.
87
+ local function rawStore(ctx: any, path: { string | number }): (any, any)
88
+ local parent = ctx.Entry.LiveData
89
+ for index = 1, #path - 1 do
90
+ if type(parent) ~= "table" then
91
+ return nil, nil
92
+ end
93
+ parent = parent[path[index]]
94
+ end
95
+ if type(parent) ~= "table" then
96
+ return nil, nil
97
+ end
98
+ return parent, path[#path]
99
+ end
100
+
101
+ --- Deep equality that understands buffers, which is what a packed datatype is.
102
+ local function packedEquals(a: any, b: any): boolean
103
+ if type(a) == "buffer" or type(b) == "buffer" then
104
+ return type(a) == "buffer" and type(b) == "buffer" and Util.bufferEquals(a, b)
105
+ end
106
+ if type(a) == "table" and type(b) == "table" then
107
+ for key, value in a do
108
+ if not packedEquals(value, b[key]) then
109
+ return false
110
+ end
111
+ end
112
+ for key in b do
113
+ if a[key] == nil then
114
+ return false
115
+ end
116
+ end
117
+ return true
118
+ end
119
+ return a == b
120
+ end
121
+
122
+ --- The accessor at a declared path, indexed fresh. Never cached and never passed across
123
+ --- a transaction boundary: a handle taken before the transaction opened escapes the
124
+ --- cross-tree guard (Node.luau:4370-4374).
125
+ local function accessorAt(ctx: any, path: { string | number }): any
126
+ local accessor = ctx.Tree.Accessor
127
+ for _, segment in path do
128
+ local ok, child = pcall(function()
129
+ return accessor[segment]
130
+ end)
131
+ if not ok or child == nil then
132
+ fail(`no accessor at "{Util.pathString(path)}"`)
133
+ end
134
+ accessor = child
135
+ end
136
+ return accessor
137
+ end
138
+
139
+ --- One numeric comparison path for every shape, so no relational operator is ever
140
+ --- applied to a value read through an accessor.
141
+ local function compareNumbers(a: any, b: any): number
142
+ local message = `cannot compare "{tostring(a)}" and "{tostring(b)}" numerically`
143
+ local left = present(Big.from(a), message)
144
+ local right = present(Big.from(b), message)
145
+ return Big.compare(left, right)
146
+ end
147
+
148
+ --- Which container declarator a node is. ArrayOf and SetOf share Container "Array"
149
+ --- and are told apart by Unique.
150
+ local function containerKindOf(node: any): string
151
+ if node.Container == "Dict" then
152
+ return if node.KeyType ~= nil then "Map" else "Dict"
153
+ end
154
+ if node.Container == "Array" then
155
+ return if node.Unique == true then "Set" else "Array"
156
+ end
157
+ return "Leaf"
158
+ end
159
+
160
+ --- Reject a container key Scribe would reject deeper in, where the raise is harder to
161
+ --- attribute, and reject a nil key outright: Remove(nil) targets the CONTAINER.
162
+ local function assertUsableKey(key: any, node: any): ()
163
+ if node.KeyType == "integer" then
164
+ -- Scribe.MapOf("integer", ...) stores number keys and Node refuses any other
165
+ -- shape for one, so the string rules below would reject every legal key.
166
+ if type(key) ~= "number" or key ~= key or key % 1 ~= 0 then
167
+ fail(`container takes an integer key, got {typeof(key)}`)
168
+ end
169
+ return
170
+ end
171
+ if type(key) ~= "string" or #key == 0 then
172
+ fail(`container key must be a non-empty string, got {typeof(key)}`)
173
+ end
174
+ if string.find(key, "\31", 1, true) ~= nil or not Util.isUtf8(key) then
175
+ fail(`container key "{key}" is not storable`)
176
+ end
177
+ if node.MaxKeyLength ~= nil and #key > node.MaxKeyLength then
178
+ fail(`container key "{key}" is over MaxKeyLength {node.MaxKeyLength}`)
179
+ end
180
+ end
181
+
182
+ --- The element schema of a container node, or nil for a leaf.
183
+ local function elementOf(node: any): any
184
+ return node.AnyChild
185
+ end
186
+
187
+ --- True when the element is a record of declared fields rather than a bare scalar.
188
+ ---
189
+ --- `DictOf(Scribe.Int(0))` has an element that IS the stored number, so it has no field
190
+ --- to count and no residual a split could duplicate, and needs no Count and no Identity.
191
+ local function isRecordElement(element: any): boolean
192
+ return element ~= nil and element.Children ~= nil and element.ChildOrder ~= nil and #element.ChildOrder > 0
193
+ end
194
+
195
+ --- May this node hold a stack's count? The Qty leg rules applied to an element field,
196
+ --- same list and same reasons: a count is a quantity that lives inside an element.
197
+ local function assertCountable(field: any, name: any, label: string): ()
198
+ if field == nil then
199
+ fail(`exchangeable "{tostring(name)}" cannot resolve {label}`)
200
+ end
201
+ if field.Container ~= nil then
202
+ fail(`exchangeable "{tostring(name)}" names {label} as its count, but a container cannot be a count`)
203
+ end
204
+ if field.ValueType == "big" then
205
+ fail(`exchangeable "{tostring(name)}" counts with a Scribe.Big, whose arithmetic absorbs a small leg silently`)
206
+ end
207
+ if field.ValueType == "number" then
208
+ fail(
209
+ `exchangeable "{tostring(name)}" counts with a Scribe.Number, and a double debit is not exactly `
210
+ .. "conserved by the matching credit; hold the count in Scribe.Int"
211
+ )
212
+ end
213
+ if field.ValueType ~= "int" then
214
+ fail(`exchangeable "{tostring(name)}" counts with a {tostring(field.ValueType)} field, which is not a count`)
215
+ end
216
+ if field.Nullable == true then
217
+ fail(`exchangeable "{tostring(name)}" counts with a Scribe.Optional field, which has no count to credit`)
218
+ end
219
+ -- Without a floor a debit stores a negative and every assertion passes.
220
+ if field.Min == nil then
221
+ fail(`exchangeable "{tostring(name)}" counts with a field declaring no Min, so it has no floor`)
222
+ end
223
+ end
224
+
225
+ --- The rules declared for this leg's path and Kind, or nil when none were indexed.
226
+ --- Absent is not an error: a Key leg works without a plan, and only a Stack leg needs
227
+ --- one, which it says itself.
228
+ local function planFor(ctx: any, leg: Leg): Plan?
229
+ local plans = ctx.Plans
230
+ if type(plans) ~= "table" then
231
+ return nil
232
+ end
233
+ return plans[`{table.concat(leg.Path :: any, ".")}|{leg.Kind}`]
234
+ end
235
+
236
+ --- The stored element with the fields declared not to travel removed.
237
+ ---
238
+ --- Removed rather than defaulted. A whole-element Set fills every omitted declared field
239
+ --- from its default and stores it (ElementPartialSet.spec), so dropping the field here is
240
+ --- what makes the receiver start fresh and an Optional one stay absent.
241
+ local function travelPayload(held: any, plan: Plan?): any
242
+ local clone = Util.deepClone(held)
243
+ if plan == nil or type(clone) ~= "table" then
244
+ return clone
245
+ end
246
+ for field in plan.Ignore do
247
+ clone[field] = nil
248
+ end
249
+ return clone
250
+ end
251
+
252
+ --- Prove no ignored field is riding in the payload.
253
+ ---
254
+ --- Checked at both ends: escrow proves the drop happened, delivery proves the record has
255
+ --- not grown it back. Every other proof only asserts that what IS in the payload landed.
256
+ local function assertNotTravelling(leg: Leg, plan: Plan?, where: string): ()
257
+ if plan == nil or type(leg.Value) ~= "table" then
258
+ return
259
+ end
260
+ for field in plan.Ignore do
261
+ if leg.Value[field] ~= nil then
262
+ fail(`leg at "{Util.pathString(leg.Path)}" carries ignored field "{field}" {where}`)
263
+ end
264
+ end
265
+ end
266
+
267
+ --- How many the element at `key` holds, and the leaf accessor that counts it. One reader
268
+ --- for both element shapes, so no caller branches on `Count` being nil.
269
+ local function stackCount(ctx: any, leg: Leg, plan: Plan, stored: any): (number, any)
270
+ local entryAccessor = accessorAt(ctx, leg.Path)[leg.Key]
271
+ if entryAccessor == nil then
272
+ fail(`stack leg at "{Util.pathString(leg.Path)}" has no accessor at "{tostring(leg.Key)}"`)
273
+ end
274
+ local countField = plan.Count
275
+ local held = if countField == nil then stored else (if type(stored) == "table" then stored[countField] else nil)
276
+ if type(held) ~= "number" or held ~= held or held % 1 ~= 0 then
277
+ fail(`stack leg at "{Util.pathString(leg.Path)}" holds no integer count at "{tostring(leg.Key)}"`)
278
+ end
279
+ return held, if countField == nil then entryAccessor else entryAccessor[countField]
280
+ end
281
+
282
+ --- Reject a Stack amount before anything reads a balance against it.
283
+ local function assertStackAmount(leg: Leg): number
284
+ local raw = leg.Amount
285
+ if type(raw) ~= "number" or raw ~= raw or raw == math.huge or raw == -math.huge then
286
+ fail(`stack leg at "{Util.pathString(leg.Path)}" has no finite Amount`)
287
+ end
288
+ -- Cast for the same reason `present` exists: the guard above does not narrow.
289
+ local amount = raw :: number
290
+ if amount <= 0 then
291
+ fail(`stack leg at "{Util.pathString(leg.Path)}" must move a positive amount, got {amount}`)
292
+ end
293
+ if amount % 1 ~= 0 then
294
+ fail(`stack leg at "{Util.pathString(leg.Path)}" must move a whole number, got {amount}`)
295
+ end
296
+ return amount
297
+ end
298
+
299
+ --- Both halves of a split must be legal stacks. Skipping the moved half is a liveness
300
+ --- bug, not a conservation one: moving 2 off a stack of 10 with Min 3 escrows fine,
301
+ --- debits the giver, then never delivers, because Clamp rounds the credit to 3 and
302
+ --- giveKey refuses the mismatch. Nothing is lost, but it parks for ever.
303
+ ---
304
+ --- A full take is exempt: the element travels as it stands, so it is legal already.
305
+ local function assertSplitFits(leg: Leg, amount: number, have: number, low: any): ()
306
+ if amount >= have or low == nil then
307
+ return
308
+ end
309
+ if compareNumbers(amount, low) < 0 then
310
+ fail(
311
+ `stack leg at "{Util.pathString(leg.Path)}" would move {amount}, below the smallest legal stack `
312
+ .. `{tostring(low)}; move the whole {have} instead`
313
+ )
314
+ end
315
+ local remaining = have - amount
316
+ if compareNumbers(remaining, low) < 0 then
317
+ fail(
318
+ `stack leg at "{Util.pathString(leg.Path)}" would leave {remaining}, below the smallest legal stack `
319
+ .. `{tostring(low)}; move the whole {have} instead`
320
+ )
321
+ end
322
+ end
323
+
324
+ --- Every field of `expected` except the count must be byte-identical in `actual`. The
325
+ --- residual is what a split duplicates and what a merge would overwrite, so it is proved
326
+ --- on both. Ignored fields are already absent from the payload.
327
+ local function assertResidual(leg: Leg, plan: Plan, expected: any, actual: any, what: string): ()
328
+ if type(expected) ~= "table" then
329
+ return
330
+ end
331
+ if type(actual) ~= "table" then
332
+ fail(`stack leg at "{Util.pathString(leg.Path)}" {what} is not a record`)
333
+ end
334
+ for field, value in expected do
335
+ if field ~= plan.Count and not packedEquals(actual[field], value) then
336
+ fail(`stack leg at "{Util.pathString(leg.Path)}" {what} differs at "{tostring(field)}"`)
337
+ end
338
+ end
339
+ end
340
+
341
+ --------------------------------------------------------------------------------
342
+ -- Qty legs
343
+ --------------------------------------------------------------------------------
344
+
345
+ --- Move a numeric leaf by `amount`, proving the stored result is exactly the intent.
346
+ --- `sign` is -1 to debit and 1 to credit. Set only: Increment and Decrement return
347
+ --- nothing that distinguishes a clamp from a write.
348
+ local function applyQty(ctx: any, leg: Leg, node: any, sign: number): ()
349
+ local amount = leg.Amount :: number
350
+ if type(amount) ~= "number" or amount ~= amount or amount == math.huge or amount == -math.huge then
351
+ fail(`quantity leg at "{Util.pathString(leg.Path)}" has no finite Amount`)
352
+ end
353
+ if amount <= 0 then
354
+ fail(`quantity leg at "{Util.pathString(leg.Path)}" must move a positive amount, got {amount}`)
355
+ end
356
+
357
+ local leaf = accessorAt(ctx, leg.Path)
358
+ local before = leaf.Get()
359
+ if before == nil then
360
+ before = leaf.Default()
361
+ end
362
+ if type(before) ~= "number" then
363
+ fail(`quantity leg at "{Util.pathString(leg.Path)}" has no numeric balance`)
364
+ end
365
+
366
+ local target = before + sign * amount
367
+ -- I1. Equal intent and current state means applySet returns early, and then the
368
+ -- return check and the post-read both agree with an intent that never landed.
369
+ if target == before then
370
+ fail(`quantity leg at "{Util.pathString(leg.Path)}" would not change the balance (absorbed)`)
371
+ end
372
+ if target ~= target or target == math.huge or target == -math.huge then
373
+ fail(`quantity leg at "{Util.pathString(leg.Path)}" produces a non-finite balance`)
374
+ end
375
+ if math.abs(target) > MAX_SAFE then
376
+ fail(`quantity leg at "{Util.pathString(leg.Path)}" passes 2^53, where Node has no guard`)
377
+ end
378
+ -- An "int" leaf is ROUNDED by the default Clamp policy (Node.luau:1100-1104), not
379
+ -- refused. Refuse here so a fractional leg never becomes a rounded one.
380
+ if node.ValueType == "int" and target % 1 ~= 0 then
381
+ fail(`quantity leg at "{Util.pathString(leg.Path)}" is fractional on an integer field`)
382
+ end
383
+
384
+ -- I3 and the bounds pre-check. Never let Clamp be the thing that tells you.
385
+ local low, high = leaf.Min(), leaf.Max()
386
+ -- I3. A debit needs a floor to be refusable at all: without one, Set stores the
387
+ -- negative, returns it, and reads it back, so every proof below passes.
388
+ if sign < 0 and low == nil then
389
+ fail(`quantity leg at "{Util.pathString(leg.Path)}" has no declared Min, so it has no floor`)
390
+ end
391
+ if low ~= nil and compareNumbers(target, low) < 0 then
392
+ fail(`quantity leg at "{Util.pathString(leg.Path)}" would store below Min {low}`)
393
+ end
394
+ if high ~= nil and compareNumbers(target, high) > 0 then
395
+ fail(`quantity leg at "{Util.pathString(leg.Path)}" would store above Max {high}`)
396
+ end
397
+
398
+ local returned = leaf.Set(target)
399
+ if returned ~= target then
400
+ fail(
401
+ `quantity leg at "{Util.pathString(leg.Path)}" stored {tostring(returned)} but intended {tostring(target)}`
402
+ )
403
+ end
404
+ -- Not redundant with the return: a Changed listener dispatches synchronously inside
405
+ -- applySet (Node.luau:1863) and can overwrite the leaf before Set returns. No delta
406
+ -- clause, because `after == target` already pins the post-state and a delta re-derives
407
+ -- it through a second rounding that is red on correct Number legs.
408
+ local after = leaf.Get()
409
+ if after ~= target then
410
+ fail(`quantity leg at "{Util.pathString(leg.Path)}" reads back {tostring(after)}, not {tostring(target)}`)
411
+ end
412
+ end
413
+
414
+ --------------------------------------------------------------------------------
415
+ -- Key legs
416
+ --------------------------------------------------------------------------------
417
+
418
+ --- Take one keyed item off a declared container, proving it left.
419
+ local function takeKey(ctx: any, leg: Leg, node: any, kind: string): ()
420
+ local accessor = accessorAt(ctx, leg.Path)
421
+ local countBefore = accessor.Count()
422
+
423
+ if kind == "Set" then
424
+ if accessor.Has(leg.Key) ~= true then
425
+ fail(`set leg at "{Util.pathString(leg.Path)}" does not hold its member`)
426
+ end
427
+ -- Identity against true. Remove returns literal false on a miss, and
428
+ -- `~= nil` passes on false.
429
+ if accessor.Remove(leg.Key) ~= true then
430
+ fail(`set leg at "{Util.pathString(leg.Path)}" Remove reported a miss`)
431
+ end
432
+ if accessor.Has(leg.Key) ~= false then
433
+ fail(`set leg at "{Util.pathString(leg.Path)}" member survived Remove`)
434
+ end
435
+ elseif kind == "Array" then
436
+ -- The ragged detector: Count walks every key while the writers use `#`.
437
+ local snapshot = accessor.Clone()
438
+ if type(snapshot) ~= "table" or #snapshot ~= countBefore then
439
+ fail(`array leg at "{Util.pathString(leg.Path)}" is ragged`)
440
+ end
441
+ -- Assert on the INDEX, never the removed value: it passes through unpackRead
442
+ -- and may legitimately be false, a table, or a Big.
443
+ local _removed, index = accessor.RemoveValue(leg.Key)
444
+ if index == nil then
445
+ fail(`array leg at "{Util.pathString(leg.Path)}" matched nothing`)
446
+ end
447
+ if type(index) ~= "number" or index % 1 ~= 0 or index < 1 or index > countBefore then
448
+ fail(`array leg at "{Util.pathString(leg.Path)}" returned a nonsense index {tostring(index)}`)
449
+ end
450
+ else
451
+ assertUsableKey(leg.Key, node)
452
+ if accessor[leg.Key].Get() == nil then
453
+ fail(`key leg at "{Util.pathString(leg.Path)}" does not hold "{tostring(leg.Key)}"`)
454
+ end
455
+ -- Remove, never Set(nil): Set(nil) returns nil on a hit AND on a miss, so it
456
+ -- cannot prove its own effect.
457
+ if accessor.Remove(leg.Key) == nil then
458
+ fail(`key leg at "{Util.pathString(leg.Path)}" Remove reported a miss`)
459
+ end
460
+ if accessor[leg.Key].Get() ~= nil then
461
+ fail(`key leg at "{Util.pathString(leg.Path)}" key survived Remove`)
462
+ end
463
+ end
464
+
465
+ local countAfter = accessor.Count()
466
+ if countAfter ~= countBefore - 1 then
467
+ fail(`leg at "{Util.pathString(leg.Path)}" changed count {countBefore} to {countAfter}, not by one`)
468
+ end
469
+ end
470
+
471
+ --- Put one keyed item onto a declared container, proving it landed.
472
+ local function giveKey(ctx: any, leg: Leg, node: any, kind: string): ()
473
+ local accessor = accessorAt(ctx, leg.Path)
474
+ local countBefore = accessor.Count()
475
+
476
+ local cap = if kind == "Dict" or kind == "Map" then node.MaxKeys else node.MaxItems
477
+ -- Checked here rather than left to the write: the cap fires only when the key is
478
+ -- new, so without this the credit raises AFTER the debit already committed.
479
+ if cap ~= nil and countBefore >= cap then
480
+ fail(`leg at "{Util.pathString(leg.Path)}" destination is full ({countBefore}/{cap})`)
481
+ end
482
+
483
+ if kind == "Set" then
484
+ if accessor.Has(leg.Key) ~= false then
485
+ fail(`set leg at "{Util.pathString(leg.Path)}" destination already holds its member`)
486
+ end
487
+ if accessor.Add(leg.Key) ~= true then
488
+ fail(`set leg at "{Util.pathString(leg.Path)}" Add reported the member already present`)
489
+ end
490
+ -- Load-bearing. Add can return true, write, emit an op and fire Changed while
491
+ -- membership is unchanged, because validateWrite coerces the member into one
492
+ -- already stored. Count alone passes that case.
493
+ if accessor.Has(leg.Key) ~= true then
494
+ fail(`set leg at "{Util.pathString(leg.Path)}" member absent after Add (coerced into an existing one)`)
495
+ end
496
+ elseif kind == "Array" then
497
+ local snapshot = accessor.Clone()
498
+ if type(snapshot) ~= "table" or #snapshot ~= countBefore then
499
+ fail(`array leg at "{Util.pathString(leg.Path)}" destination is ragged`)
500
+ end
501
+ -- Set at an explicit index: Insert returns nothing and cannot self-prove.
502
+ local index = countBefore + 1
503
+ accessor[index].Set(leg.Value)
504
+ local parent, key = rawStore(ctx, leg.Path)
505
+ local landed = if parent ~= nil then parent[key] :: any else nil
506
+ if type(landed) ~= "table" or not packedEquals(landed[index], leg.Value) then
507
+ fail(`array leg at "{Util.pathString(leg.Path)}" did not store its payload at {index}`)
508
+ end
509
+ else
510
+ assertUsableKey(leg.Key, node)
511
+ -- I2. Vacancy is what makes both proofs bite: an occupied key either no-ops
512
+ -- (scalar element) or silently clobbers (record element).
513
+ if accessor[leg.Key].Get() ~= nil then
514
+ fail(`key leg at "{Util.pathString(leg.Path)}" destination key "{tostring(leg.Key)}" is occupied`)
515
+ end
516
+ -- The whole element at the key, never a leaf field: a leaf write materialises
517
+ -- the element from its defaults first and then no-ops if it equals the default.
518
+ local returned = accessor[leg.Key].Set(leg.Value)
519
+ -- Non-nil only. Set returns the UNPACKED form, a fresh table of real datatypes
520
+ -- for a packed element, so comparing it to a packed payload fails on exactly
521
+ -- the elements the packed payload exists to carry.
522
+ if returned == nil then
523
+ fail(`key leg at "{Util.pathString(leg.Path)}" Set returned nil`)
524
+ end
525
+ local parent, key = rawStore(ctx, leg.Path)
526
+ local landed = if parent ~= nil then parent[key] :: any else nil
527
+ if type(landed) ~= "table" or landed[leg.Key] == nil then
528
+ fail(`key leg at "{Util.pathString(leg.Path)}" key absent after Set`)
529
+ end
530
+ -- Content proved against the RAW re-read, which is still packed. The walk is
531
+ -- guarded on shape because a scalar element IS its payload: iterating a number
532
+ -- raises, and Deliver is retried for ever, so that raise repeats on every load.
533
+ local stored = landed[leg.Key]
534
+ if type(leg.Value) == "table" then
535
+ for field, value in leg.Value do
536
+ if not packedEquals(stored[field], value) then
537
+ fail(`key leg at "{Util.pathString(leg.Path)}" field "{tostring(field)}" did not store`)
538
+ end
539
+ end
540
+ elseif not packedEquals(stored, leg.Value) then
541
+ fail(`key leg at "{Util.pathString(leg.Path)}" did not store its payload`)
542
+ end
543
+ end
544
+
545
+ local countAfter = accessor.Count()
546
+ if countAfter ~= countBefore + 1 then
547
+ fail(`leg at "{Util.pathString(leg.Path)}" changed count {countBefore} to {countAfter}, not by one`)
548
+ end
549
+ end
550
+
551
+ --------------------------------------------------------------------------------
552
+ -- Stack legs
553
+ --------------------------------------------------------------------------------
554
+
555
+ --- Take `Amount` off one stacked entry, proving what left and what stayed. A full take
556
+ --- delegates to takeKey rather than decrementing to zero: a zero-count entry is an item
557
+ --- the player still appears to own and can name in a later basket.
558
+ local function takeStack(ctx: any, leg: Leg, node: any, plan: Plan, kind: string, expected: number): ()
559
+ local amount = assertStackAmount(leg)
560
+ local accessor = accessorAt(ctx, leg.Path)
561
+ local countBefore = accessor.Count()
562
+
563
+ assertUsableKey(leg.Key, node)
564
+ local parent, key = rawStore(ctx, leg.Path)
565
+ local container = if parent ~= nil then parent[key] else nil
566
+ if type(container) ~= "table" then
567
+ fail(`stack leg at "{Util.pathString(leg.Path)}" has no stored container`)
568
+ end
569
+ local stored = container[leg.Key]
570
+ if stored == nil then
571
+ fail(`stack leg at "{Util.pathString(leg.Path)}" does not hold "{tostring(leg.Key)}"`)
572
+ end
573
+
574
+ local have, counter = stackCount(ctx, leg, plan, stored)
575
+ -- The payload was built before the escrow record was written, and writing it
576
+ -- dispatches listeners. If one moved this balance the payload no longer describes
577
+ -- what is here.
578
+ if have ~= expected then
579
+ fail(`stack leg at "{Util.pathString(leg.Path)}" moved from {expected} to {have} before it could be staked`)
580
+ end
581
+ if amount > have then
582
+ fail(`stack leg at "{Util.pathString(leg.Path)}" moves {amount} of {have} held`)
583
+ end
584
+ if amount == have then
585
+ takeKey(ctx, leg, node, kind)
586
+ return
587
+ end
588
+
589
+ -- `stored` is the live table, so snapshot before the write or the residual check
590
+ -- below compares it to itself.
591
+ local before = Util.deepClone(stored)
592
+ local remaining = have - amount
593
+ -- Checked here as well as in Escrow: this primitive is callable on its own.
594
+ assertSplitFits(leg, amount, have, counter.Min())
595
+ local returned = counter.Set(remaining)
596
+ if returned ~= remaining then
597
+ fail(`stack leg at "{Util.pathString(leg.Path)}" stored {tostring(returned)} but intended {remaining}`)
598
+ end
599
+ local readBack = counter.Get()
600
+ if readBack ~= remaining then
601
+ fail(`stack leg at "{Util.pathString(leg.Path)}" reads back {tostring(readBack)}, not {remaining}`)
602
+ end
603
+ -- A split must not change the key set: the entry stays, holding less.
604
+ local countAfter = accessor.Count()
605
+ if countAfter ~= countBefore then
606
+ fail(`stack leg at "{Util.pathString(leg.Path)}" changed count {countBefore} to {countAfter} on a split`)
607
+ end
608
+ local parentAfter, keyAfter = rawStore(ctx, leg.Path)
609
+ local containerAfter = if parentAfter ~= nil then parentAfter[keyAfter] else nil
610
+ local after = if type(containerAfter) == "table" then containerAfter[leg.Key] else nil
611
+ assertResidual(leg, plan, before, after, "remainder")
612
+ end
613
+
614
+ --- Credit `Amount` onto the destination, whether or not it already holds the stack.
615
+ local function giveStack(ctx: any, leg: Leg, node: any, plan: Plan, kind: string): ()
616
+ local amount = assertStackAmount(leg)
617
+ assertNotTravelling(leg, plan, "into delivery")
618
+ local accessor = accessorAt(ctx, leg.Path)
619
+ assertUsableKey(leg.Key, node)
620
+
621
+ local parent, key = rawStore(ctx, leg.Path)
622
+ local container = if parent ~= nil then parent[key] else nil
623
+ local stored = if type(container) == "table" then container[leg.Key] else nil
624
+ if stored == nil then
625
+ -- A vacant key is the ordinary whole-entry credit, and the payload already
626
+ -- carries Count = Amount. giveKey proves vacancy, cap, content and count.
627
+ giveKey(ctx, leg, node, kind)
628
+ return
629
+ end
630
+
631
+ -- The residual is what says these two stacks are the same thing. A mismatch parks
632
+ -- rather than picking a winner, so an operator can redirect it.
633
+ assertResidual(leg, plan, leg.Value, stored, "destination")
634
+
635
+ local countBefore = accessor.Count()
636
+ local have, counter = stackCount(ctx, leg, plan, stored)
637
+ local before = Util.deepClone(stored)
638
+ local target = have + amount
639
+ if target ~= target or target == math.huge or math.abs(target) > MAX_SAFE then
640
+ fail(`stack leg at "{Util.pathString(leg.Path)}" produces an unstorable count {tostring(target)}`)
641
+ end
642
+ -- Checked before the write: Clamp would round the overflow away and report success.
643
+ local high = counter.Max()
644
+ if high ~= nil and compareNumbers(target, high) > 0 then
645
+ fail(`stack leg at "{Util.pathString(leg.Path)}" would store {target}, above Max {tostring(high)}`)
646
+ end
647
+ local returned = counter.Set(target)
648
+ if returned ~= target then
649
+ fail(`stack leg at "{Util.pathString(leg.Path)}" stored {tostring(returned)} but intended {target}`)
650
+ end
651
+ local readBack = counter.Get()
652
+ if readBack ~= target then
653
+ fail(`stack leg at "{Util.pathString(leg.Path)}" reads back {tostring(readBack)}, not {target}`)
654
+ end
655
+ local countAfter = accessor.Count()
656
+ if countAfter ~= countBefore then
657
+ fail(`stack leg at "{Util.pathString(leg.Path)}" changed count {countBefore} to {countAfter} on a merge`)
658
+ end
659
+ local parentAfter, keyAfter = rawStore(ctx, leg.Path)
660
+ local containerAfter = if parentAfter ~= nil then parentAfter[keyAfter] else nil
661
+ local after = if type(containerAfter) == "table" then containerAfter[leg.Key] else nil
662
+ assertResidual(leg, plan, before, after, "destination after merge")
663
+ end
664
+
665
+ --------------------------------------------------------------------------------
666
+ -- Public
667
+ --------------------------------------------------------------------------------
668
+
669
+ --- Move every leg out of game data and into this player's own reserved escrow, in one
670
+ --- transaction.
671
+ ---
672
+ --- The reserved record is written BEFORE the removals. That does not change what commits,
673
+ --- but it orders the failure modes: anything escaping a clean rollback strands value
674
+ --- under `_Scribe`, where the gate can see it and the resolver can return it.
675
+ function ExchangeLeg.Escrow(ctx: any, exchangeId: string, legs: { Leg }): (boolean, string?)
676
+ if type(exchangeId) ~= "string" or #exchangeId == 0 then
677
+ fail("Escrow needs an exchange id")
678
+ end
679
+ if type(legs) ~= "table" or #legs == 0 then
680
+ fail("Escrow needs at least one leg")
681
+ end
682
+
683
+ return ctx.Tree:RunTransaction(function()
684
+ -- A claim with no value in it is the expected precursor; anything further
685
+ -- along already holds value and must not be overwritten.
686
+ local existing = ctx.Tree.Reserved.Exchange[exchangeId].Get()
687
+ if existing ~= nil and existing.Phase ~= "Claimed" then
688
+ fail(`exchange "{exchangeId}" is already staked on this profile`)
689
+ end
690
+
691
+ local recorded: { Leg } = {}
692
+ -- What each Stack leg held when its payload was built, so the removal pass can
693
+ -- refuse a balance that moved in between.
694
+ local observed: { [number]: number } = {}
695
+ for position, leg in legs do
696
+ local node = resolveStrict(ctx.Compiled, leg.Path)
697
+ local entry: Leg = { Path = leg.Path, Kind = leg.Kind, Key = leg.Key, Amount = leg.Amount }
698
+ if leg.Kind == "Stack" then
699
+ local plan = present(
700
+ planFor(ctx, leg),
701
+ `stack leg at "{Util.pathString(leg.Path)}" has no declared Stack rules on this bundle`
702
+ )
703
+ local kind = containerKindOf(node)
704
+ if kind ~= "Dict" and kind ~= "Map" then
705
+ fail(`stack leg at "{Util.pathString(leg.Path)}" is a {kind}, which has no keyed stack to split`)
706
+ end
707
+ assertUsableKey(leg.Key, node)
708
+ local parent, key = rawStore(ctx, leg.Path)
709
+ local container = if parent ~= nil then parent[key] else nil
710
+ if type(container) ~= "table" then
711
+ fail(`stack leg at "{Util.pathString(leg.Path)}" has no stored container`)
712
+ end
713
+ local held = container[leg.Key]
714
+ if held == nil then
715
+ fail(`stack leg at "{Util.pathString(leg.Path)}" holds nothing to stake`)
716
+ end
717
+ local amount = assertStackAmount(leg)
718
+ local have, counter = stackCount(ctx, leg, plan, held)
719
+ if amount > have then
720
+ fail(`stack leg at "{Util.pathString(leg.Path)}" moves {amount} of {have} held`)
721
+ end
722
+ assertSplitFits(leg, amount, have, counter.Min())
723
+ observed[position] = have
724
+ if plan.Count == nil then
725
+ -- A scalar element is its own count.
726
+ entry.Value = amount
727
+ else
728
+ local payload = travelPayload(held, plan)
729
+ if type(payload) ~= "table" then
730
+ fail(`stack leg at "{Util.pathString(leg.Path)}" holds a scalar where a record was declared`)
731
+ end
732
+ payload[plan.Count] = amount
733
+ entry.Value = payload
734
+ end
735
+ assertNotTravelling(entry, plan, "into escrow")
736
+ elseif leg.Kind == "Key" then
737
+ -- Read the STORED form before anything moves it. Remove's return is the
738
+ -- live former table by reference for an unpacked element.
739
+ local parent, key = rawStore(ctx, leg.Path)
740
+ local container = if parent ~= nil then parent[key] else nil
741
+ local kind = containerKindOf(node)
742
+ if kind == "Set" then
743
+ entry.Value = leg.Key
744
+ elseif type(container) == "table" then
745
+ local held
746
+ if kind == "Array" then
747
+ -- Resolve the needle to an INDEX and read what the STORE holds
748
+ -- there, not the caller's own value: a packed element is live
749
+ -- datatypes in the needle and a buffer in the store, and only the
750
+ -- buffer can be recorded under the reserved root. It also proves
751
+ -- the container holds the entry; a nil test on the needle did not.
752
+ local index = accessorAt(ctx, leg.Path).Find(leg.Key)
753
+ held = if index ~= nil then container[index] else nil
754
+ -- The needle was an ADDRESS, spent once the entry is read. Keeping
755
+ -- it would put the same unstorable live datatypes under `Key` that
756
+ -- `Value` just avoided, and delivery appends by index anyway.
757
+ -- takeKey below still gets the caller's own leg.
758
+ entry.Key = nil
759
+ else
760
+ -- Checked here as well as inside takeKey: the lookup below misses
761
+ -- on a wrong-typed key and would report "holds nothing to stake",
762
+ -- which on an integer-keyed map reads as an empty container.
763
+ assertUsableKey(leg.Key, node)
764
+ held = container[leg.Key]
765
+ end
766
+ if held == nil then
767
+ fail(`key leg at "{Util.pathString(leg.Path)}" holds nothing to stake`)
768
+ end
769
+ -- Dropped here, the one point where the giver's copy is still
770
+ -- readable, so nothing downstream needs to know about them.
771
+ local plan = planFor(ctx, leg)
772
+ entry.Value = travelPayload(held, plan)
773
+ assertNotTravelling(entry, plan, "into escrow")
774
+ else
775
+ fail(`key leg at "{Util.pathString(leg.Path)}" has no stored container`)
776
+ end
777
+ end
778
+ table.insert(recorded, entry)
779
+ end
780
+
781
+ local written = ctx.Tree.Reserved.Exchange[exchangeId].Set({
782
+ Id = exchangeId,
783
+ Owner = ctx.UserId,
784
+ Digest = if existing ~= nil then existing.Digest else nil,
785
+ Role = if existing ~= nil then existing.Role else nil,
786
+ Partner = if existing ~= nil then existing.Partner else nil,
787
+ StakedAt = Clock.Now(),
788
+ Phase = "Staked",
789
+ Escrow = recorded,
790
+ })
791
+ -- An untyped Set hands back the live stored table, so identity is a true proof
792
+ -- here and is available on no other shape.
793
+ if type(written) ~= "table" or ctx.Tree.Reserved.Exchange[exchangeId].Get() ~= written then
794
+ fail(`escrow record for "{exchangeId}" is not the live stored table`)
795
+ end
796
+
797
+ for index, leg in legs do
798
+ local node = resolveStrict(ctx.Compiled, leg.Path)
799
+ if leg.Kind == "Qty" then
800
+ applyQty(ctx, leg, node, -1)
801
+ elseif leg.Kind == "Stack" then
802
+ takeStack(
803
+ ctx,
804
+ leg,
805
+ node,
806
+ present(planFor(ctx, leg), `stack leg at "{Util.pathString(leg.Path)}" lost its declared rules`),
807
+ containerKindOf(node),
808
+ present(observed[index], `stack leg at "{Util.pathString(leg.Path)}" was never measured`)
809
+ )
810
+ else
811
+ takeKey(ctx, leg, node, containerKindOf(node))
812
+ end
813
+ end
814
+ end)
815
+ end
816
+
817
+ --- Apply every leg of this player's inbox entry onto game data and clear the entry, in
818
+ --- one transaction, so delivery and removal are atomic.
819
+ function ExchangeLeg.Deliver(ctx: any, exchangeId: string): (boolean, string?)
820
+ if type(exchangeId) ~= "string" or #exchangeId == 0 then
821
+ fail("Deliver needs an exchange id")
822
+ end
823
+
824
+ return ctx.Tree:RunTransaction(function()
825
+ local record = ctx.Tree.Reserved.ExchangeInbox[exchangeId].Get()
826
+ if type(record) ~= "table" then
827
+ fail(`no inbox entry for "{exchangeId}"`)
828
+ end
829
+ local legs = record.Legs
830
+ if type(legs) ~= "table" or #legs == 0 then
831
+ fail(`inbox entry "{exchangeId}" carries no legs`)
832
+ end
833
+
834
+ for _, leg in legs do
835
+ local node = resolveStrict(ctx.Compiled, leg.Path)
836
+ if leg.Kind == "Qty" then
837
+ applyQty(ctx, leg, node, 1)
838
+ elseif leg.Kind == "Stack" then
839
+ giveStack(
840
+ ctx,
841
+ leg,
842
+ node,
843
+ present(planFor(ctx, leg), `stack leg at "{Util.pathString(leg.Path)}" lost its declared rules`),
844
+ containerKindOf(node)
845
+ )
846
+ else
847
+ assertNotTravelling(leg, planFor(ctx, leg), "into delivery")
848
+ giveKey(ctx, leg, node, containerKindOf(node))
849
+ end
850
+ end
851
+
852
+ if ctx.Tree.Reserved.ExchangeInbox.Remove(exchangeId) == nil then
853
+ fail(`inbox entry "{exchangeId}" vanished before it could be cleared`)
854
+ end
855
+ if ctx.Tree.Reserved.ExchangeInbox[exchangeId].Get() ~= nil then
856
+ fail(`inbox entry "{exchangeId}" survived its removal`)
857
+ end
858
+ end)
859
+ end
860
+
861
+ --------------------------------------------------------------------------------
862
+ -- Reserved-root record lifecycle
863
+ --
864
+ -- Everything below writes ONLY under the reserved root. After the verdict no
865
+ -- operation may remain that a declared shape, a cap, a bound, a Closed record or a
866
+ -- seed path can refuse: a write outside `_Scribe` in Settle would put a
867
+ -- data-dependent refusal after the point of no return. ExchangeLegSettle.spec
868
+ -- records every emitted op and asserts it.
869
+ --------------------------------------------------------------------------------
870
+
871
+ --- How many exchanges this profile has in flight.
872
+ local function openExchangeCount(ctx: any): number
873
+ local exchange = ctx.Tree.Reserved.Exchange.Get()
874
+ if type(exchange) ~= "table" then
875
+ return 0
876
+ end
877
+ local count = 0
878
+ for _ in exchange do
879
+ count += 1
880
+ end
881
+ return count
882
+ end
883
+
884
+ --- Take this profile's single exchange slot, holding no value yet. The emptiness test
885
+ --- runs INSIDE the transaction, so there is no instant at which a participant of an
886
+ --- in-flight exchange advertises a free slot.
887
+ function ExchangeLeg.Claim(ctx: any, exchangeId: string, spec: any): (boolean, string?)
888
+ if type(exchangeId) ~= "string" or #exchangeId == 0 then
889
+ fail("Claim needs an exchange id")
890
+ end
891
+ if type(spec) ~= "table" or type(spec.Digest) ~= "string" then
892
+ fail("Claim needs a spec carrying a Digest")
893
+ end
894
+
895
+ return ctx.Tree:RunTransaction(function()
896
+ local open = openExchangeCount(ctx)
897
+ if open ~= 0 then
898
+ fail(`profile already has {open} exchange(s) in flight`)
899
+ end
900
+ ctx.Tree.Reserved.Exchange[exchangeId].Set({
901
+ Id = exchangeId,
902
+ Owner = ctx.UserId,
903
+ Digest = spec.Digest,
904
+ Role = spec.Role,
905
+ Partner = spec.Partner,
906
+ Phase = "Claimed",
907
+ StakedAt = Clock.Now(),
908
+ })
909
+ if ctx.Tree.Reserved.Exchange[exchangeId].Get() == nil then
910
+ fail(`claim for "{exchangeId}" did not land`)
911
+ end
912
+ end)
913
+ end
914
+
915
+ --- Release a slot that never took value. Restricted to Phase "Claimed" on purpose: once
916
+ --- any escrow has committed the only exit is the verdict-gated abort, and dropping a
917
+ --- staked record here would destroy the value it holds with nothing left to say where it
918
+ --- went. A take is refused for the same reason: it is the only pointer to value owed.
919
+ function ExchangeLeg.Unclaim(ctx: any, exchangeId: string): (boolean, string?)
920
+ if type(exchangeId) ~= "string" or #exchangeId == 0 then
921
+ fail("Unclaim needs an exchange id")
922
+ end
923
+
924
+ return ctx.Tree:RunTransaction(function()
925
+ local record = ctx.Tree.Reserved.Exchange[exchangeId].Get()
926
+ if record == nil then
927
+ return
928
+ end
929
+ if record.Phase ~= "Claimed" then
930
+ fail(`exchange "{exchangeId}" is {tostring(record.Phase)}, not Claimed; only the verdict may release it`)
931
+ end
932
+ if type(record.Escrow) == "table" and next(record.Escrow) ~= nil then
933
+ fail(`exchange "{exchangeId}" holds escrowed value and cannot be unclaimed`)
934
+ end
935
+ if type(record.Take) == "table" and next(record.Take) ~= nil then
936
+ fail(`exchange "{exchangeId}" records a take and cannot be unclaimed; only the verdict may release it`)
937
+ end
938
+ if ctx.Tree.Reserved.Exchange.Remove(exchangeId) == nil then
939
+ fail(`claim for "{exchangeId}" vanished before it could be released`)
940
+ end
941
+ end)
942
+ end
943
+
944
+ --- Record what this profile is OWED, copied from the counterparty's escrow.
945
+ ---
946
+ --- The payload comes from the counterparty's escrow rather than their live game data, so
947
+ --- what a taker is promised is provably what the giver gave up. Game code cannot write
948
+ --- the reserved root, so that copy cannot have drifted.
949
+ function ExchangeLeg.FillTake(ctx: any, exchangeId: string, legs: { Leg }): (boolean, string?)
950
+ if type(exchangeId) ~= "string" or #exchangeId == 0 then
951
+ fail("FillTake needs an exchange id")
952
+ end
953
+ if type(legs) ~= "table" then
954
+ fail("FillTake needs a leg list")
955
+ end
956
+
957
+ return ctx.Tree:RunTransaction(function()
958
+ local record = ctx.Tree.Reserved.Exchange[exchangeId].Get()
959
+ if record == nil then
960
+ fail(`exchange "{exchangeId}" has no record to fill`)
961
+ end
962
+ -- Filling twice would replace what the profile is owed with a second copy of
963
+ -- it, which reads as success and moves the wrong basket.
964
+ if record.Take ~= nil then
965
+ fail(`exchange "{exchangeId}" already has a take recorded`)
966
+ end
967
+ ctx.Tree.Reserved.Exchange[exchangeId].Take.Set(Util.deepClone(legs))
968
+ local after = ctx.Tree.Reserved.Exchange[exchangeId].Get()
969
+ if after == nil or type(after.Take) ~= "table" then
970
+ fail(`take for "{exchangeId}" did not land`)
971
+ end
972
+ end)
973
+ end
974
+
975
+ --- Apply a verdict to this profile's record, in one transaction, touching nothing
976
+ --- outside the reserved root.
977
+ ---
978
+ --- Commit moves this profile's Take into its inbox and DROPS its escrow: the
979
+ --- counterparty's copy was made durable before any verdict could exist, so the drop
980
+ --- cannot destroy the only copy. Abort moves the escrow back into this profile's own
981
+ --- inbox and drops the Take. The record's removal is fused with the move, so a replay
982
+ --- from the same verdict is a no-op rather than a second move.
983
+ function ExchangeLeg.Settle(ctx: any, exchangeId: string, verdict: any): (boolean, string?)
984
+ if type(exchangeId) ~= "string" or #exchangeId == 0 then
985
+ fail("Settle needs an exchange id")
986
+ end
987
+ if type(verdict) ~= "table" or (verdict.V ~= "Commit" and verdict.V ~= "Abort") then
988
+ fail("Settle needs a verdict of Commit or Abort")
989
+ end
990
+
991
+ return ctx.Tree:RunTransaction(function()
992
+ local record = ctx.Tree.Reserved.Exchange[exchangeId].Get()
993
+ -- Absence IS the already-settled bit, and it is atomic with the settle because
994
+ -- the removal below happens in this same transaction.
995
+ if record == nil then
996
+ return
997
+ end
998
+ -- A corruption check, not an expected branch. Refusing here leaves both records
999
+ -- in place for an operator rather than settling against the wrong basket.
1000
+ if verdict.D ~= nil and record.Digest ~= nil and verdict.D ~= record.Digest then
1001
+ fail(`exchange "{exchangeId}" digest does not match the verdict`)
1002
+ end
1003
+
1004
+ -- The ordering premise, asserted rather than assumed. With no Take the drop has
1005
+ -- no counterpart: nothing is written to the inbox, control falls through to the
1006
+ -- removal below, and the escrow and the record of what it held are deleted
1007
+ -- together while the call reports success. Attempt writes exactly this state
1008
+ -- between Escrow and FillTake and leaves it there whenever no verdict can be
1009
+ -- established, so it is reachable with no crash at all.
1010
+ local escrow = record.Escrow
1011
+ if
1012
+ verdict.V == "Commit"
1013
+ and type(record.Take) ~= "table"
1014
+ and type(escrow) == "table"
1015
+ and next(escrow) ~= nil
1016
+ then
1017
+ fail(`exchange "{exchangeId}" holds escrow with no take recorded; a Commit here would destroy it`)
1018
+ end
1019
+
1020
+ local moved = if verdict.V == "Commit" then record.Take else record.Escrow
1021
+ if type(moved) == "table" and next(moved) ~= nil then
1022
+ ctx.Tree.Reserved.ExchangeInbox[exchangeId].Set({
1023
+ Id = exchangeId,
1024
+ Verdict = verdict.V,
1025
+ Legs = moved,
1026
+ SettledAt = Clock.Now(),
1027
+ })
1028
+ if ctx.Tree.Reserved.ExchangeInbox[exchangeId].Get() == nil then
1029
+ fail(`inbox entry for "{exchangeId}" did not land`)
1030
+ end
1031
+ end
1032
+
1033
+ -- Fused with the move. If the removal were a separate transaction, a revert
1034
+ -- between them would replay the move and the inbox would hold it twice.
1035
+ if ctx.Tree.Reserved.Exchange.Remove(exchangeId) == nil then
1036
+ fail(`record for "{exchangeId}" vanished before it could be removed`)
1037
+ end
1038
+ end)
1039
+ end
1040
+
1041
+ --- May a parked key leg at this path be re-pointed at a different key?
1042
+ ---
1043
+ --- Only where the key is a slot and the payload is separate from it. In a Set the key IS
1044
+ --- the member, so re-keying substitutes a different item rather than relocating the
1045
+ --- delivery, and the delivery reports success. An Array has no key to move at all.
1046
+ function ExchangeLeg.Rekeyable(compiled: any, path: any): (boolean, string?)
1047
+ if type(path) ~= "table" or #path == 0 then
1048
+ return false, "a leg with no Path cannot be redirected"
1049
+ end
1050
+ local ok, node = pcall(resolveStrict, compiled, path)
1051
+ if not ok or node == nil then
1052
+ return false, `"{Util.pathString(path)}" is not a declared container`
1053
+ end
1054
+ local kind = containerKindOf(node)
1055
+ if kind == "Dict" or kind == "Map" then
1056
+ if node.KeyType == "integer" then
1057
+ return false, `"{Util.pathString(path)}" is keyed by integer, and a redirect names its key as a string`
1058
+ end
1059
+ return true, nil
1060
+ end
1061
+ if kind == "Set" then
1062
+ return false,
1063
+ `"{Util.pathString(path)}" is a set, where the key is the value; re-keying it would deliver a different item`
1064
+ end
1065
+ return false, `"{Util.pathString(path)}" is a {kind} and has no destination key to move`
1066
+ end
1067
+
1068
+ --- The runtime allowlist, indexed once from the declared specs.
1069
+ ---
1070
+ --- Refuse, below, proves the DECLARATIONS are safe to move; this proves a basket only
1071
+ --- names them. Keyed on the path AND the Kind, because the same path moved as a Key and
1072
+ --- moved as a Qty reaches two different primitives and registration vetted one of them.
1073
+ function ExchangeLeg.Approve(exchangeable: any): { [string]: Plan }
1074
+ local approved: { [string]: Plan } = {}
1075
+ if type(exchangeable) ~= "table" then
1076
+ return approved
1077
+ end
1078
+ for _, spec in exchangeable do
1079
+ if
1080
+ type(spec) == "table"
1081
+ and type(spec.Path) == "table"
1082
+ and (spec.Kind == "Key" or spec.Kind == "Qty" or spec.Kind == "Stack")
1083
+ then
1084
+ -- A set, not the list: every read is a membership test.
1085
+ local ignore: { [string]: true } = {}
1086
+ if type(spec.Ignore) == "table" then
1087
+ for _, field in spec.Ignore do
1088
+ if type(field) == "string" then
1089
+ ignore[field] = true
1090
+ end
1091
+ end
1092
+ end
1093
+ approved[`{table.concat(spec.Path, ".")}|{spec.Kind}`] = {
1094
+ Count = if type(spec.Count) == "string" then spec.Count else nil,
1095
+ Ignore = ignore,
1096
+ }
1097
+ end
1098
+ end
1099
+ return approved
1100
+ end
1101
+
1102
+ --- Is this leg one the game declared exchangeable? Returns the reason when it is not.
1103
+ ---
1104
+ --- Every malformed shape is answered with a refusal rather than a raise: this runs on a
1105
+ --- basket that may have been built from client-influenced input, where a raise reaches
1106
+ --- game code as a stack trace from inside Scribe. The shape checks come first because the
1107
+ --- lookup has to read Path to build its key.
1108
+ function ExchangeLeg.ApprovedLeg(approved: any, leg: any): (boolean, string?)
1109
+ if type(leg) ~= "table" or type(leg.Path) ~= "table" or #leg.Path == 0 then
1110
+ return false, "a leg with no Path is not exchangeable"
1111
+ end
1112
+ for _, segment in leg.Path do
1113
+ if type(segment) ~= "string" then
1114
+ return false, "a leg whose Path is not a list of names is not exchangeable"
1115
+ end
1116
+ end
1117
+ if leg.Kind ~= "Key" and leg.Kind ~= "Qty" and leg.Kind ~= "Stack" then
1118
+ return false, `the leg at "{Util.pathString(leg.Path)}" declares no Kind, so it is not exchangeable`
1119
+ end
1120
+ if type(approved) ~= "table" or not approved[`{table.concat(leg.Path, ".")}|{leg.Kind}`] then
1121
+ return false,
1122
+ `"{Util.pathString(leg.Path)}" is not exchangeable as a {leg.Kind} leg; declare it in the Exchangeable option`
1123
+ end
1124
+ return true, nil
1125
+ end
1126
+
1127
+ --- Refuse every unsafe exchangeable path at startup, by name, so a misconfigured game
1128
+ --- fails to boot instead of discovering it mid-exchange.
1129
+ function ExchangeLeg.Refuse(compiled: any, exchangeable: any): ()
1130
+ if exchangeable == nil then
1131
+ return
1132
+ end
1133
+ if type(exchangeable) ~= "table" then
1134
+ fail("Exchangeable must be a table of leg specs")
1135
+ end
1136
+
1137
+ for name, spec in exchangeable do
1138
+ if type(spec) ~= "table" or type(spec.Path) ~= "table" or #spec.Path == 0 then
1139
+ fail(`exchangeable "{tostring(name)}" must declare a Path`)
1140
+ end
1141
+ local kind = spec.Kind
1142
+ if kind ~= "Key" and kind ~= "Qty" and kind ~= "Stack" then
1143
+ fail(`exchangeable "{tostring(name)}" must declare Kind "Key", "Qty" or "Stack"`)
1144
+ end
1145
+
1146
+ local root = spec.Path[1]
1147
+ if string.sub(root, 1, #RESERVED) == RESERVED then
1148
+ fail(`exchangeable "{tostring(name)}" names the reserved "{RESERVED}" root, which is Scribe's own ledger`)
1149
+ end
1150
+ local node = resolveStrict(compiled, spec.Path)
1151
+ local container = containerKindOf(node)
1152
+
1153
+ -- A leg may name a top-level field or a container, but may NOT reach through
1154
+ -- one: a write under a key the receiver does not hold materialises that whole
1155
+ -- element from its declared defaults, so the credit mints everything the element
1156
+ -- declares and every per-leg proof still passes, the moved term being exact.
1157
+ local ancestor = node.Parent
1158
+ while ancestor ~= nil do
1159
+ if ancestor.Container ~= nil then
1160
+ fail(
1161
+ `exchangeable "{tostring(name)}" reaches through a container; name the container itself, `
1162
+ .. "because crediting a key the receiver does not hold would seed the whole element"
1163
+ )
1164
+ end
1165
+ ancestor = ancestor.Parent
1166
+ end
1167
+
1168
+ -- Derived and Flags are named BEFORE the persistence test. A derived field is
1169
+ -- legitimately non-persisted, so testing persistence first blames the wrong
1170
+ -- rule and sends the reader hunting for a Session marker that is not there.
1171
+ if node.Derived ~= nil then
1172
+ fail(`exchangeable "{tostring(name)}" is a Scribe.Derived field; it is computed, never written`)
1173
+ end
1174
+ if node.ValueType == "flags" then
1175
+ fail(`exchangeable "{tostring(name)}" is a Scribe.Flags; membership is not movable`)
1176
+ end
1177
+ -- A session root is rebuilt from declared defaults on every load, so a credit
1178
+ -- is wiped on the next join and a debit is undone while the escrow persists.
1179
+ if not Template.PersistOf(compiled, { root }) then
1180
+ fail(
1181
+ `exchangeable "{tostring(name)}" names the non-persisted root "{root}"; session state cannot be exchanged`
1182
+ )
1183
+ end
1184
+
1185
+ if kind == "Qty" then
1186
+ if container ~= "Leaf" then
1187
+ fail(`exchangeable "{tostring(name)}" is a quantity leg on a container`)
1188
+ end
1189
+ if node.ValueType == "big" then
1190
+ fail(`exchangeable "{tostring(name)}" is a Scribe.Big, whose arithmetic absorbs a small leg silently`)
1191
+ end
1192
+ if node.ValueType == "number" then
1193
+ fail(
1194
+ `exchangeable "{tostring(name)}" is a Scribe.Number, and a double debit is not exactly `
1195
+ .. "conserved by the matching credit; hold the quantity in Scribe.Int minor units"
1196
+ )
1197
+ end
1198
+ if node.ValueType ~= "int" and node.ValueType ~= "number" then
1199
+ fail(`exchangeable "{tostring(name)}" is a quantity leg on a {tostring(node.ValueType)} field`)
1200
+ end
1201
+ if node.Nullable == true then
1202
+ fail(
1203
+ `exchangeable "{tostring(name)}" is a Scribe.Optional field, which has no balance to `
1204
+ .. "credit until something writes it, so the receiving half would park for ever"
1205
+ )
1206
+ end
1207
+ -- Without a floor a debit stores a negative and every assertion passes.
1208
+ if node.Min == nil then
1209
+ fail(`exchangeable "{tostring(name)}" declares no Min, so it has no floor and cannot be a quantity`)
1210
+ end
1211
+ elseif container == "Leaf" then
1212
+ fail(`exchangeable "{tostring(name)}" is a {kind} leg on a field that is not a container`)
1213
+ end
1214
+
1215
+ -- Ignore and the Stack rules are about the element, not the container.
1216
+ local element = elementOf(node)
1217
+ local isRecord = isRecordElement(element)
1218
+
1219
+ --- One resolver for every option naming an element field. A typo in Ignore that
1220
+ --- silently ignored nothing would look stripped and travel anyway.
1221
+ local function declaredField(field: any, option: string): any
1222
+ if type(field) ~= "string" then
1223
+ fail(`exchangeable "{tostring(name)}" lists a non-string name in {option}`)
1224
+ end
1225
+ if string.find(field, ".", 1, true) ~= nil then
1226
+ fail(
1227
+ `exchangeable "{tostring(name)}" names "{field}" in {option}; only top-level element fields are `
1228
+ .. "supported, not a path into one"
1229
+ )
1230
+ end
1231
+ local child = if isRecord then element.Children[field] else nil
1232
+ if child == nil then
1233
+ fail(`exchangeable "{tostring(name)}" names "{field}" in {option}, which the element does not declare`)
1234
+ end
1235
+ return child
1236
+ end
1237
+
1238
+ local ignored: { [string]: true } = {}
1239
+ if spec.Ignore ~= nil then
1240
+ if kind == "Qty" then
1241
+ fail(`exchangeable "{tostring(name)}" declares Ignore on a quantity leg, which has no fields`)
1242
+ end
1243
+ if type(spec.Ignore) ~= "table" then
1244
+ fail(`exchangeable "{tostring(name)}" declares Ignore that is not a list of field names`)
1245
+ end
1246
+ if not isRecord then
1247
+ fail(
1248
+ `exchangeable "{tostring(name)}" declares Ignore, but its element is a single value with no `
1249
+ .. "fields to ignore"
1250
+ )
1251
+ end
1252
+ for _, field in spec.Ignore do
1253
+ declaredField(field, "Ignore")
1254
+ ignored[field] = true
1255
+ end
1256
+ end
1257
+
1258
+ if spec.Count ~= nil and kind ~= "Stack" then
1259
+ fail(`exchangeable "{tostring(name)}" declares Count on a {kind} leg; it is only meaningful for a Stack`)
1260
+ end
1261
+ if spec.Identity ~= nil and kind ~= "Stack" then
1262
+ fail(`exchangeable "{tostring(name)}" declares Identity on a {kind} leg; it is only meaningful for a Stack`)
1263
+ end
1264
+
1265
+ if kind == "Stack" then
1266
+ if container ~= "Dict" and container ~= "Map" then
1267
+ fail(
1268
+ `exchangeable "{tostring(name)}" is a stack leg on a {container}; only a DictOf or MapOf has a `
1269
+ .. "keyed stack to split"
1270
+ )
1271
+ end
1272
+ if not isRecord then
1273
+ -- The element IS the count, so nothing rides alongside it to declare.
1274
+ if spec.Count ~= nil then
1275
+ fail(
1276
+ `exchangeable "{tostring(name)}" declares Count, but its element is a single value which IS `
1277
+ .. "the count"
1278
+ )
1279
+ end
1280
+ if spec.Identity ~= nil then
1281
+ fail(
1282
+ `exchangeable "{tostring(name)}" declares Identity, but its element is a single value with no `
1283
+ .. "other fields"
1284
+ )
1285
+ end
1286
+ assertCountable(element, name, "its element")
1287
+ else
1288
+ if type(spec.Count) ~= "string" then
1289
+ fail(
1290
+ `exchangeable "{tostring(name)}" must declare Count, naming the element field that holds how many`
1291
+ )
1292
+ end
1293
+ assertCountable(declaredField(spec.Count, "Count"), name, `"{spec.Count}"`)
1294
+ if ignored[spec.Count] then
1295
+ fail(`exchangeable "{tostring(name)}" ignores "{spec.Count}", which is the field being moved`)
1296
+ end
1297
+
1298
+ local identified: { [string]: true } = {}
1299
+ if spec.Identity ~= nil then
1300
+ if type(spec.Identity) ~= "table" then
1301
+ fail(`exchangeable "{tostring(name)}" declares Identity that is not a list of field names`)
1302
+ end
1303
+ for _, field in spec.Identity do
1304
+ declaredField(field, "Identity")
1305
+ if ignored[field] then
1306
+ fail(`exchangeable "{tostring(name)}" lists "{field}" in BOTH Identity and Ignore`)
1307
+ end
1308
+ identified[field] = true
1309
+ end
1310
+ end
1311
+
1312
+ -- A split duplicates whatever it does not drop, and no per-leg proof can
1313
+ -- see it because the count is exact either way. Boot is the only place
1314
+ -- an unclassified field is visible, so every one must be accounted for.
1315
+ for _, field in element.ChildOrder do
1316
+ if field == spec.Count then
1317
+ continue
1318
+ end
1319
+ if not identified[field] and not ignored[field] then
1320
+ fail(
1321
+ `exchangeable "{tostring(name)}" does not account for element field "{field}"; list it in `
1322
+ .. "Identity to travel with the split, or in Ignore to reset on the receiver"
1323
+ )
1324
+ end
1325
+ if identified[field] and element.Children[field].Container ~= nil then
1326
+ fail(
1327
+ `exchangeable "{tostring(name)}" lists container field "{field}" in Identity; a split would `
1328
+ .. "duplicate the whole collection"
1329
+ )
1330
+ end
1331
+ end
1332
+ end
1333
+ end
1334
+
1335
+ local seen = {}
1336
+ local function walk(current: any)
1337
+ if current == nil or seen[current] then
1338
+ return
1339
+ end
1340
+ seen[current] = true
1341
+ if current.Timed == true then
1342
+ fail(
1343
+ `exchangeable "{tostring(name)}" has a Scribe.Timed field in its subtree; timed state is keyed by path`
1344
+ )
1345
+ end
1346
+ if current.Evict ~= nil then
1347
+ fail(`exchangeable "{tostring(name)}" has an Evict container in its subtree, which destroys silently`)
1348
+ end
1349
+ if current.Derived ~= nil then
1350
+ fail(`exchangeable "{tostring(name)}" has a derived field in its subtree`)
1351
+ end
1352
+ if current.ValueType == "flags" then
1353
+ fail(`exchangeable "{tostring(name)}" has a Scribe.Flags in its subtree`)
1354
+ end
1355
+ if current.ChildOrder and current.Children then
1356
+ for _, key in current.ChildOrder do
1357
+ walk(current.Children[key])
1358
+ end
1359
+ end
1360
+ if current.AnyChild and current.AnyChild.IsElement then
1361
+ walk(current.AnyChild)
1362
+ end
1363
+ end
1364
+ walk(node)
1365
+ end
1366
+ end
1367
+
1368
+ return ExchangeLeg