@silverprotocol/core 0.12.4 → 1.0.0-rc.1

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 (57) hide show
  1. package/README.md +17 -9
  2. package/dist/agjson.d.ts +594 -594
  3. package/dist/agjson.d.ts.map +1 -1
  4. package/dist/agjson.js +132 -17
  5. package/dist/agjson.js.map +1 -1
  6. package/dist/atomic-push.js.map +1 -1
  7. package/dist/copy-json.d.ts +31 -4
  8. package/dist/copy-json.d.ts.map +1 -1
  9. package/dist/copy-json.js +147 -15
  10. package/dist/copy-json.js.map +1 -1
  11. package/dist/depth.d.ts +34 -0
  12. package/dist/depth.d.ts.map +1 -0
  13. package/dist/depth.js +141 -0
  14. package/dist/depth.js.map +1 -0
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1 -0
  18. package/dist/index.js.map +1 -1
  19. package/dist/ingest.d.ts +7 -2
  20. package/dist/ingest.d.ts.map +1 -1
  21. package/dist/ingest.js +36 -4
  22. package/dist/ingest.js.map +1 -1
  23. package/dist/input-check.d.ts.map +1 -1
  24. package/dist/input-check.js +17 -3
  25. package/dist/input-check.js.map +1 -1
  26. package/dist/json-patch.d.ts.map +1 -1
  27. package/dist/json-patch.js +17 -9
  28. package/dist/json-patch.js.map +1 -1
  29. package/dist/persist.js.map +1 -1
  30. package/dist/record.d.ts.map +1 -1
  31. package/dist/record.js +25 -6
  32. package/dist/record.js.map +1 -1
  33. package/dist/reduce.d.ts +1 -1
  34. package/dist/reduce.d.ts.map +1 -1
  35. package/dist/reduce.js +293 -112
  36. package/dist/reduce.js.map +1 -1
  37. package/dist/stream-assembler.d.ts +6 -7
  38. package/dist/stream-assembler.d.ts.map +1 -1
  39. package/dist/stream-assembler.js +21 -18
  40. package/dist/stream-assembler.js.map +1 -1
  41. package/dist/wire.d.ts +21 -3
  42. package/dist/wire.d.ts.map +1 -1
  43. package/dist/wire.js +34 -5
  44. package/dist/wire.js.map +1 -1
  45. package/package.json +1 -1
  46. package/src/agjson.ts +128 -28
  47. package/src/atomic-push.ts +2 -2
  48. package/src/copy-json.ts +143 -17
  49. package/src/depth.ts +138 -0
  50. package/src/index.ts +1 -0
  51. package/src/ingest.ts +35 -4
  52. package/src/input-check.ts +15 -3
  53. package/src/json-patch.ts +21 -8
  54. package/src/record.ts +25 -6
  55. package/src/reduce.ts +273 -111
  56. package/src/stream-assembler.ts +21 -18
  57. package/src/wire.ts +36 -6
package/dist/reduce.js CHANGED
@@ -1,5 +1,8 @@
1
1
  import { REMOVE_ALL } from "./agjson.js";
2
2
  import { applyPatch } from "./json-patch.js";
3
+ import { deleteOwnProtoMember, withoutOwnProtoMember } from "./copy-json.js";
4
+ import { exceedsDepth, scanDepth } from "./depth.js";
5
+ import { AG_EVENT_MAX_DEPTH } from "./wire.js";
3
6
  // ─────────────────────────────────────────────────────────────────────────────
4
7
  // Reducer — the normative event→state fold (spec §5).
5
8
  //
@@ -85,6 +88,12 @@ function isClosedEvent(ev) {
85
88
  */
86
89
  const HELD_TURNS_CAP = 64;
87
90
  const HELD_LANDINGS_CAP = 1024;
91
+ /**
92
+ * The deepest node of a state or memory value a patch may leave, counted from
93
+ * the value's root: the depth at which a state.snapshot's `snapshot` or a
94
+ * memory.write's `value` sits below its event root is 1.
95
+ */
96
+ const STORED_VALUE_MAX_DEPTH = AG_EVENT_MAX_DEPTH - 1;
88
97
  export class Reducer {
89
98
  // ── keyed accumulators ──────────────────────────────────────────────────────
90
99
  // Messages, keyed by message id (insertion-ordered).
@@ -103,10 +112,10 @@ export class Reducer {
103
112
  // Message ids sealed by message.end.
104
113
  #sealed = new Set();
105
114
  // turnIds legitimately opened via turn.start / subagent.start (or restored
106
- // by a messages.snapshot's turns?) — Task 8c leg 3 (guuey capstone finding
107
- // B). Distinguishes "a real turn genuinely exists" from a turn the fold only
108
- // knows by name, so the tool.done adoption CREATE path degrades loudly
109
- // (resync) instead of creating a message for a turn that was never opened.
115
+ // by a messages.snapshot's turns?). Distinguishes "a real turn genuinely
116
+ // exists" from a turn the fold only knows by name, so the tool.done adoption
117
+ // CREATE path degrades loudly (resync) instead of creating a message for a
118
+ // turn that was never opened.
110
119
  #openedTurns = new Set();
111
120
  // draft.4 §5.0 INV-OWNER: every
112
121
  // turnId the fold has seen opened — by turn.start, by subagent.start, or by a
@@ -118,15 +127,28 @@ export class Reducer {
118
127
  // #openedTurns (tool.done adoption) and never rebuilt from #turns, whose
119
128
  // records non-terminal arms may have minted as stubs.
120
129
  #seenOpened = new Map();
130
+ // §5 `subagent.start` row (rc.1): the fold's root thread — the first threadId a
131
+ // folded turn.start, message.start, artifact.start or messages.snapshot carried.
132
+ // A nested turn whose parent's thread is not known takes it.
133
+ #rootThread;
134
+ // Nested turns a `subagent.start` opened while neither the parent's thread nor
135
+ // the root thread was known: turnId → parentTurnId. Each one's record is held in
136
+ // #held (result() omits it) until one of the two becomes known (#releaseHeldNested).
137
+ #heldNested = new Map();
121
138
  // draft.5 §5.0 INV-OWNER (a held record lands on its own turn's thread): the landings of
122
139
  // the six record events (source, handoff, prompt.blocked, guardrail.result,
123
140
  // display.required, agent.capabilities) for a turn whose thread the fold does
124
141
  // not know yet. Each is a turn record result() never shows; it moves into
125
142
  // #turns on the turn's thread once a turn.start, subagent.start, message.start
126
143
  // or messages.snapshot makes that thread known (#adoptHeld). `landings` counts
127
- // the events held on it, for the implementation bound below.
144
+ // the record events held on it other than display.required, `dr` the
145
+ // display.required ones, each against its own implementation bound below: a
146
+ // display.required is never discarded, so it survives a turns-carrying
147
+ // snapshot, and counting it apart keeps it from filling the bound the other
148
+ // five landings recover through that snapshot.
128
149
  #held = new Map();
129
150
  #heldLandings = 0;
151
+ #heldDrLandings = 0;
130
152
  // draft.5 §5.0 INV-MSG (the paused refresh): closed turns a turn.start has
131
153
  // named since their last terminal folded. Only such a turn, closed paused,
132
154
  // takes a turn.done{paused}; every terminal that folds removes its id. A
@@ -157,6 +179,13 @@ export class Reducer {
157
179
  * R3–R10 fill remaining content types.
158
180
  */
159
181
  push(ev) {
182
+ // One pass before anything reads the event: whether a node sits deeper
183
+ // than AG_EVENT_MAX_DEPTH, and whether an own `__proto__` member is held
184
+ // (the delete walk below runs only on an event that holds one). A
185
+ // too-deep event occupies its seq slot like any other and is folded no
186
+ // further: copying it, or patching the state with it, would overflow the
187
+ // stack. A consuming ingest never yields one; it stubs such a frame.
188
+ const scan = scanDepth(ev, AG_EVENT_MAX_DEPTH);
160
189
  // ── Seq-gap detection (R9) ────────────────────────────────────────────────
161
190
  // Seq accounting is UNIVERSAL (INV-SEQ: "gap-free ordinal" over the whole
162
191
  // per-invoke stream) — EVERY well-formed event with a numeric seq advances
@@ -164,7 +193,7 @@ export class Reducer {
164
193
  // other live-only events). This must run BEFORE the isClosedEvent skip
165
194
  // below: an ext/live-only event between two closed events still occupies a
166
195
  // seq slot, so skipping it here would let the NEXT closed event look like
167
- // a forward gap that never happened (found by M46 review — the false-park
196
+ // a forward gap that never happened (found in review — the false-park
168
197
  // this fixes voided every fold with an ext emission between closed events).
169
198
  // After the first event (#lastSeq >= 0), a forward gap sets #resync (park)
170
199
  // — including when an ext/live-only event is the one revealing the gap.
@@ -197,6 +226,8 @@ export class Reducer {
197
226
  this.#invokeBlockIds.clear();
198
227
  this.#finalToolDone.clear();
199
228
  }
229
+ if (scan.tooDeep)
230
+ return;
200
231
  // Store-time isolation: the handlers below keep references into the event
201
232
  // (a block, a providerMetadata or _meta bag, a tool result, an outcome, a
202
233
  // state snapshot, a patch value, a memory value), so the fold works on its
@@ -205,11 +236,24 @@ export class Reducer {
205
236
  // It runs before the ext guard below, which then narrows the copy. An event
206
237
  // structuredClone cannot copy (a function-valued field) folds as pushed, as
207
238
  // it always did, rather than throwing out of push().
239
+ //
240
+ // §13.7: the fold omits an own `__proto__` member at every depth of every
241
+ // event it folds. On the clone the walk deletes in place, when the scan
242
+ // above found one; an event that cannot be cloned gets a rebuilt copy, so
243
+ // the host's object is never mutated. Neither walk throws out of push().
208
244
  try {
209
245
  ev = structuredClone(ev);
246
+ if (scan.hasOwnProto)
247
+ deleteOwnProtoMember(ev);
210
248
  }
211
249
  catch {
212
- // not cloneable: fold the event as pushed
250
+ // not cloneable: fold the event as pushed, less the member
251
+ try {
252
+ ev = withoutOwnProtoMember(ev);
253
+ }
254
+ catch {
255
+ // a host getter that throws: fold the event as pushed
256
+ }
213
257
  }
214
258
  // Ext events (`ext.<vendor>.<key>`) are live-only / non-folding (§4/§12).
215
259
  // Rule them out HERE — after seq accounting above, so an ext event still
@@ -224,7 +268,7 @@ export class Reducer {
224
268
  // draft.5 INV-MSG: a turn.start naming a closed turn opens its paused refresh.
225
269
  if (this.#isClosedTurn(ev.turnId))
226
270
  this.#restartedSinceClose.add(ev.turnId);
227
- // Task 8c leg 3: a turn.start always counts as a legitimately opened turn.
271
+ // A turn.start always counts as a legitimately opened turn.
228
272
  this.#openedTurns.add(ev.turnId);
229
273
  this.#seenOpened.set(ev.turnId, ev.threadId);
230
274
  // Idempotent: if the turn already exists, merge defined fields only. A
@@ -245,17 +289,29 @@ export class Reducer {
245
289
  existing.trigger = ev.trigger;
246
290
  }
247
291
  }
292
+ this.#rootThread ??= ev.threadId;
293
+ this.#releaseHeldNested();
248
294
  break;
249
295
  }
250
296
  // ── MESSAGE lifecycle ──────────────────────────────────────────────────
251
297
  case "message.start": {
298
+ // INV-MSG (rc.1): a message.start naming an id the fold already holds as a
299
+ // message — open or sealed, carried by a folded messages.snapshot, or
300
+ // adopted by a tool.done — parks and the fold is unchanged. The message
301
+ // set is fold-wide, so a later invoke reusing a held id parks too; a
302
+ // folded message.remove, or a snapshot that omits the id, releases it.
303
+ // Checked before any write below, so a parked repeat registers nothing.
304
+ if (this.#messages.has(ev.id)) {
305
+ this.#resync = true;
306
+ break;
307
+ }
252
308
  // INV-MSG: a message.start for a turn that already closed parks.
253
309
  if (this.#isClosedTurn(this.#resolveTurnId(ev.turnId) ?? ev.turnId)) {
254
310
  this.#resync = true;
255
311
  break;
256
312
  }
257
313
  // draft.5 INV-OWNER: a live message.start makes its turn's thread
258
- // known and joins D9's seen-opened set (a turn.start's thread wins; else
314
+ // known and joins the seen-opened set (§5.0 INV-OWNER) (a turn.start's thread wins; else
259
315
  // the first one folded), and a record held for the turn is adopted onto it.
260
316
  if (this.#seenOpened.get(ev.turnId) === undefined)
261
317
  this.#seenOpened.set(ev.turnId, ev.threadId);
@@ -279,6 +335,8 @@ export class Reducer {
279
335
  this.#messages.set(ev.id, msg);
280
336
  // Register partition pointer: (turnId, candidateIndex ?? 0) → message id.
281
337
  this.#openMsg.set(partKey(ev.turnId, ev.candidateIndex ?? 0), ev.id);
338
+ this.#rootThread ??= ev.threadId;
339
+ this.#releaseHeldNested();
282
340
  break;
283
341
  }
284
342
  case "message.end": {
@@ -299,36 +357,39 @@ export class Reducer {
299
357
  }
300
358
  // ── SUBAGENT lifecycle ─────────────────────────────────────────────────
301
359
  case "subagent.start": {
302
- // Task 8c leg 3: a subagent.start always counts as a legitimately
360
+ // A subagent.start always counts as a legitimately
303
361
  // opened turn, even on the idempotent-duplicate early return below.
304
362
  this.#openedTurns.add(ev.turnId);
305
- // Idempotent: if the nested turn already exists, skip (never duplicate).
363
+ // Idempotent: a second open of a turn the fold already holds merges fields and never duplicates it (§5
364
+ // turn-open idempotency): a record with no parentTurnId takes this one; a record that has one keeps it, and
365
+ // a known thread stays.
306
366
  const existingNested = this.#turns.get(ev.turnId);
307
367
  if (existingNested !== undefined) {
368
+ if (existingNested.parentTurnId === undefined)
369
+ existingNested.parentTurnId = ev.parentTurnId;
308
370
  this.#seenOpened.set(ev.turnId, existingNested.threadId);
309
371
  break;
310
372
  }
311
- // threadId is required on AgTurnRecord; inherit from the parent turn.
312
- // subagent.start does not carry threadId on the wire, so we look it up.
313
- const parentTurn = this.#turns.get(ev.parentTurnId);
314
- let threadId;
315
- if (parentTurn !== undefined) {
316
- threadId = parentTurn.threadId;
317
- }
318
- else {
319
- // Task 8c leg 2 (SPEC §1.2 + guuey capstone finding A): a parent
320
- // lookup miss means ev.parentTurnId is a wire label that was never
321
- // opened as a real turn (e.g. claude's synthetic `turn_${toolCallId}`
322
- // Task-tool cross-ref) — NOT a legitimate cross-thread reference.
323
- // Every entity in a fold shares one root threadId (SPEC §1.2), so
324
- // fall back to any ALREADY-OPENED real turn's threadId instead of
325
- // adopting the unresolvable label as this subagent's own threadId.
326
- // A "real" turn is identified by threadId !== turnId: through draft.4
327
- // a defensive stub used its own turnId as a placeholder thread. draft.5
328
- // retires the stubs, and the check stays as a guard.
329
- // `ev.parentTurnId` remains the last resort when no real turn exists yet.
330
- const realTurn = [...this.#turns.values()].find((t) => t.threadId !== t.turnId);
331
- threadId = realTurn?.threadId ?? ev.parentTurnId;
373
+ // §5 `subagent.start` row (rc.1): the nested turn's thread is the parent
374
+ // turn's thread when that thread is known (INV-OWNER), else the fold's root
375
+ // thread; until one of the two is known the record is held, result() omits
376
+ // it, and the first that becomes known gives its thread (#releaseHeldNested).
377
+ const threadId = this.#threadOfTurn(ev.parentTurnId) ?? this.#rootThread;
378
+ if (threadId === undefined) {
379
+ if (!this.#heldNested.has(ev.turnId) && this.#heldNested.size >= HELD_TURNS_CAP) {
380
+ this.#resync = true; // degrade loudly past the implementation bound
381
+ break;
382
+ }
383
+ let held = this.#held.get(ev.turnId);
384
+ if (held === undefined) {
385
+ held = { record: { turnId: ev.turnId, threadId: "" }, landings: 0, dr: 0 };
386
+ this.#held.set(ev.turnId, held);
387
+ }
388
+ held.record.parentTurnId ??= ev.parentTurnId;
389
+ this.#heldNested.set(ev.turnId, held.record.parentTurnId ?? ev.parentTurnId);
390
+ // Seen opened, its thread not known yet: a terminal for it lands on the held record.
391
+ this.#seenOpened.set(ev.turnId, undefined);
392
+ break;
332
393
  }
333
394
  // A record held for this nested turn takes the thread and the
334
395
  // parentTurnId here; otherwise a new record opens.
@@ -340,6 +401,7 @@ export class Reducer {
340
401
  });
341
402
  }
342
403
  this.#seenOpened.set(ev.turnId, threadId);
404
+ this.#releaseHeldNested();
343
405
  break;
344
406
  }
345
407
  case "subagent.done": {
@@ -405,12 +467,12 @@ export class Reducer {
405
467
  const msg = this.#messages.get(pos.messageId);
406
468
  if (msg === undefined)
407
469
  break;
408
- // INV-MSG (SPEC.md:745, draft.4 E5): a block-finalizing event into a sealed
470
+ // INV-MSG (SPEC.md:745, draft.4): a block-finalizing event into a sealed
409
471
  // message, or into any message of a closed turn, parks like a delta.
410
472
  if (this.#isClosedTarget(msg.id)) {
411
473
  this.#resync = true;
412
474
  break;
413
- } // INV-MSG finalizer guard (E5)
475
+ } // INV-MSG finalizer guard
414
476
  const block = msg.content[pos.index];
415
477
  if (block === undefined || block.type !== "text")
416
478
  break;
@@ -419,7 +481,7 @@ export class Reducer {
419
481
  if (ev.phase !== undefined && !this.#sealed.has(msg.id))
420
482
  block.phase = ev.phase;
421
483
  setProviderMeta(block, ev.providerMetadata);
422
- // STREAMED-text citations carrier (audit M22): attach citations to the
484
+ // STREAMED-text citations carrier: attach citations to the
423
485
  // sealed block named by `ev.id` — never re-emitted as a duplicate
424
486
  // supplement block.
425
487
  if (ev.citations !== undefined)
@@ -476,12 +538,12 @@ export class Reducer {
476
538
  const msg = this.#messages.get(pos.messageId);
477
539
  if (msg === undefined)
478
540
  break;
479
- // INV-MSG (SPEC.md:745, draft.4 E5): a block-finalizing event into a sealed
541
+ // INV-MSG (SPEC.md:745, draft.4): a block-finalizing event into a sealed
480
542
  // message, or into any message of a closed turn, parks like a delta.
481
543
  if (this.#isClosedTarget(msg.id)) {
482
544
  this.#resync = true;
483
545
  break;
484
- } // INV-MSG finalizer guard (E5)
546
+ } // INV-MSG finalizer guard
485
547
  const block = msg.content[pos.index];
486
548
  if (block === undefined || block.type !== "reasoning")
487
549
  break;
@@ -516,12 +578,12 @@ export class Reducer {
516
578
  const msg = this.#messages.get(pos.messageId);
517
579
  if (msg === undefined)
518
580
  break;
519
- // INV-MSG (SPEC.md:745, draft.4 E5): a block-finalizing event into a sealed
581
+ // INV-MSG (SPEC.md:745, draft.4): a block-finalizing event into a sealed
520
582
  // message, or into any message of a closed turn, parks like a delta.
521
583
  if (this.#isClosedTarget(msg.id)) {
522
584
  this.#resync = true;
523
585
  break;
524
- } // INV-MSG finalizer guard (E5)
586
+ } // INV-MSG finalizer guard
525
587
  const block = msg.content[pos.index];
526
588
  if (block === undefined || block.type !== "reasoning")
527
589
  break;
@@ -587,12 +649,12 @@ export class Reducer {
587
649
  const msg = this.#messages.get(pos.messageId);
588
650
  if (msg === undefined)
589
651
  break;
590
- // INV-MSG (SPEC.md:745, draft.4 E5): a block-finalizing event into a sealed
652
+ // INV-MSG (SPEC.md:745, draft.4): a block-finalizing event into a sealed
591
653
  // message, or into any message of a closed turn, parks like a delta.
592
654
  if (this.#isClosedTarget(msg.id)) {
593
655
  this.#resync = true;
594
656
  break;
595
- } // INV-MSG finalizer guard (E5)
657
+ } // INV-MSG finalizer guard
596
658
  const block = msg.content[pos.index];
597
659
  if (block === undefined || block.type !== "tool-call")
598
660
  break;
@@ -614,12 +676,12 @@ export class Reducer {
614
676
  // ── TOOL-RESULT blocks ────────────────────────────────────────────────────
615
677
  case "tool.done": {
616
678
  // INV-BLOCK: a second FINAL (more-less) tool.done for one call parks.
617
- if (ev.more !== true) {
618
- if (this.#finalToolDone.has(ev.toolCallId)) {
619
- this.#resync = true;
620
- break;
621
- }
622
- this.#finalToolDone.add(ev.toolCallId);
679
+ // INV-BLOCK (rc.1): a more:true after the call's final (more-less) result
680
+ // landed in this invoke parks; a final result is never re-opened within its
681
+ // invoke. #finalToolDone is invoke-scoped (reset at seq 0).
682
+ if (this.#finalToolDone.has(ev.toolCallId)) {
683
+ this.#resync = true;
684
+ break;
623
685
  }
624
686
  const resultKey = `result:${ev.toolCallId}`;
625
687
  const existingPos = this.#blockPos.get(resultKey);
@@ -638,8 +700,7 @@ export class Reducer {
638
700
  // published content. Resolve the block's owning turn via the
639
701
  // #blockPos → messageId → message.turnId chain and park instead of mutating
640
702
  // (mirrors the adoption path's closed-turn/sealed guard above).
641
- const ownerTurnKey = msg.turnId ?? "unknown-turn";
642
- if (this.#sealed.has(msg.id) || this.#isClosedTurn(ownerTurnKey)) {
703
+ if (this.#sealed.has(msg.id) || this.#isClosedTurn(msg.turnId)) {
643
704
  this.#resync = true;
644
705
  break;
645
706
  }
@@ -675,7 +736,7 @@ export class Reducer {
675
736
  if (ev._meta !== undefined)
676
737
  block._meta = ev._meta;
677
738
  setProviderMeta(block, ev.providerMetadata);
678
- // Typed preliminary flag mirrors the block's `more` state (audit M20):
739
+ // Typed preliminary flag mirrors the block's `more` state:
679
740
  // more:true keeps it set (kept open); the final more-less tool.done
680
741
  // clears it and closes the result (removed from open tracking).
681
742
  if (ev.more) {
@@ -684,6 +745,7 @@ export class Reducer {
684
745
  else {
685
746
  delete block.preliminary;
686
747
  this.#blockPos.delete(resultKey);
748
+ this.#finalToolDone.add(ev.toolCallId);
687
749
  }
688
750
  }
689
751
  else {
@@ -691,7 +753,7 @@ export class Reducer {
691
753
  let msg;
692
754
  if (ev.messageId !== undefined) {
693
755
  // SPEC §5 tool.done row: the landed tool-result message ADOPTS
694
- // ev.messageId as its own id (stable ToolMessage identity; audit B10).
756
+ // ev.messageId as its own id (stable ToolMessage identity).
695
757
  const existing = this.#messages.get(ev.messageId);
696
758
  // INV-MSG enforcement: a sealed message, or ANY message of a closed
697
759
  // turn — including one that would need to be freshly created — is
@@ -699,16 +761,18 @@ export class Reducer {
699
761
  // would land in (the existing message's own turnId, or the turn a
700
762
  // new message would take) BEFORE either sub-path runs, and park
701
763
  // instead of silently attaching/creating past the seal or the
702
- // turn's binding window. "unknown-turn" is only a key that names no
703
- // record, so an unresolvable owner parks below.
764
+ // turn's binding window. A message with no turnId, or a new one whose
765
+ // turn resolves to none, has no turn open to adoption and parks below,
766
+ // whatever the fold's turns are named.
704
767
  const targetTurnKey = existing !== undefined
705
- ? (existing.turnId ?? "unknown-turn")
706
- : (this.#resolveTurnId(ev.turnId) ?? ev.turnId ?? "unknown-turn");
707
- // Task 8c leg 3 (guuey capstone finding B): a turn that was never
708
- // legitimately opened (turn.start / subagent.start / a snapshot's
709
- // turns?) is just as invalid an adoption target as a sealed
710
- // message or a closed turn: park rather than create a message for it.
711
- if (this.#sealed.has(ev.messageId) ||
768
+ ? existing.turnId
769
+ : (this.#resolveTurnId(ev.turnId) ?? ev.turnId);
770
+ // A turn that was never legitimately opened (turn.start /
771
+ // subagent.start / a snapshot's turns?) is just as invalid an
772
+ // adoption target as a sealed message or a closed turn: park rather
773
+ // than create a message for it.
774
+ if (targetTurnKey === undefined ||
775
+ this.#sealed.has(ev.messageId) ||
712
776
  this.#isClosedTurn(targetTurnKey) ||
713
777
  !this.#openedTurns.has(targetTurnKey)) {
714
778
  this.#resync = true;
@@ -769,6 +833,9 @@ export class Reducer {
769
833
  if (ev.more) {
770
834
  this.#blockPos.set(resultKey, { messageId: msg.id, index });
771
835
  }
836
+ else {
837
+ this.#finalToolDone.add(ev.toolCallId);
838
+ }
772
839
  }
773
840
  break;
774
841
  }
@@ -821,7 +888,7 @@ export class Reducer {
821
888
  }
822
889
  // ── TURN-RECORD events (R5) ───────────────────────────────────────────────
823
890
  case "turn.done": {
824
- // D9 (draft.4 §5.0 INV-OWNER): a terminal for a turn this fold never saw
891
+ // INV-OWNER (draft.4 §5.0): a terminal for a turn this fold never saw
825
892
  // opened is not an unresolvable owner: it folds onto no turn record and
826
893
  // does not park. A CORE client that ignores subagent.*, or a fold whose
827
894
  // opener was dropped, sees exactly this; a producer's lone terminal fails
@@ -853,7 +920,7 @@ export class Reducer {
853
920
  }
854
921
  // messageMetadata: REPLACE the whole messageMetadata bag of the message named
855
922
  // by turn.done.messageId when present, else of the open message of this turn
856
- // (audit M20; §5 turn.done row, §13.10). No per-key merge.
923
+ // (§5 turn.done row, §13.10). No per-key merge.
857
924
  // (Read happens BEFORE the binding window closes below.)
858
925
  if (ev.messageMetadata !== undefined) {
859
926
  const msg = ev.messageId !== undefined ? this.#messages.get(ev.messageId) : this.openMessage(ev.turnId, 0);
@@ -868,17 +935,19 @@ export class Reducer {
868
935
  }
869
936
  case "turn.error": {
870
937
  // Non-folding into content; sets outcome={type:"error",...} on the turn record.
871
- // D9, as turn.done, for a NAMED turnId. A turnId-less terminal resolves to
938
+ // INV-OWNER, as turn.done, for a NAMED turnId. A turnId-less terminal resolves to
872
939
  // the sole OPEN turn, never a closed one; with none or several open its
873
940
  // owner is unresolvable and the fold parks (INV-OWNER, draft.5).
874
941
  if (ev.turnId !== undefined && !this.#seenOpened.has(ev.turnId))
875
942
  break;
876
- const turn = ev.turnId !== undefined ? this.#seenTurnRecord(ev.turnId) : this.#soleOpenRecord();
877
- if (turn === undefined) {
878
- if (ev.turnId === undefined)
879
- this.#resync = true;
943
+ const owner = ev.turnId ?? this.#soleOpenTurn();
944
+ if (owner === undefined) {
945
+ this.#resync = true;
880
946
  break;
881
947
  }
948
+ const turn = this.#seenTurnRecord(owner);
949
+ if (turn === undefined)
950
+ break;
882
951
  // draft.5 INV-MSG: a turn.error for a closed turn parks, writing nothing.
883
952
  if (!this.#terminalMayFold(turn, false))
884
953
  break;
@@ -902,18 +971,20 @@ export class Reducer {
902
971
  case "turn.abort": {
903
972
  // Non-folding into content; sets a dedicated aborted outcome on the turn record
904
973
  // (symmetric with turn.error). taskState is verbatim-A2A only and is NEVER
905
- // reducer-invented (audit M29) — it stays whatever a prior turn.done left it as.
906
- // D9, as turn.done, for a NAMED turnId. A turnId-less terminal resolves to
974
+ // reducer-invented — it stays whatever a prior turn.done left it as.
975
+ // INV-OWNER, as turn.done, for a NAMED turnId. A turnId-less terminal resolves to
907
976
  // the sole OPEN turn, never a closed one; with none or several open its
908
977
  // owner is unresolvable and the fold parks (INV-OWNER, draft.5).
909
978
  if (ev.turnId !== undefined && !this.#seenOpened.has(ev.turnId))
910
979
  break;
911
- const turn = ev.turnId !== undefined ? this.#seenTurnRecord(ev.turnId) : this.#soleOpenRecord();
912
- if (turn === undefined) {
913
- if (ev.turnId === undefined)
914
- this.#resync = true;
980
+ const owner = ev.turnId ?? this.#soleOpenTurn();
981
+ if (owner === undefined) {
982
+ this.#resync = true;
915
983
  break;
916
984
  }
985
+ const turn = this.#seenTurnRecord(owner);
986
+ if (turn === undefined)
987
+ break;
917
988
  // draft.5 INV-MSG: a turn.abort for a closed turn parks, writing nothing.
918
989
  if (!this.#terminalMayFold(turn, false))
919
990
  break;
@@ -926,7 +997,7 @@ export class Reducer {
926
997
  case "source": {
927
998
  // Append sourceId to the turn's sourceIds[] in order (preserve groundingChunks order),
928
999
  // AND land the FULL record (payload/chunkIndex/providerMetadata) on sources[] so
929
- // citations can resolve post-fold (audit M23) — sourceIds[] stays as the derived index.
1000
+ // citations can resolve post-fold — sourceIds[] stays as the derived index.
930
1001
  const turn = this.#landingRecord(ev.turnId);
931
1002
  if (turn === undefined)
932
1003
  break;
@@ -966,7 +1037,7 @@ export class Reducer {
966
1037
  // Record safety[] on the turn (merge — append to existing safety, or create) AND
967
1038
  // land the dedicated promptBlocked record {reason, safety?} so the REQUIRED reason
968
1039
  // and the blockedness itself survive the fold — a bare-reason block used to fold to
969
- // ZERO trace (audit M28).
1040
+ // ZERO trace.
970
1041
  const turn = this.#landingRecord(ev.turnId);
971
1042
  if (turn === undefined)
972
1043
  break;
@@ -1005,7 +1076,7 @@ export class Reducer {
1005
1076
  }
1006
1077
  case "display.required": {
1007
1078
  // MUST NOT drop (ToS). Push {provider, html} onto turn's displayRequired[].
1008
- const turn = this.#landingRecord(ev.turnId);
1079
+ const turn = this.#landingRecord(ev.turnId, true);
1009
1080
  if (turn === undefined)
1010
1081
  break;
1011
1082
  if (turn.displayRequired === undefined) {
@@ -1037,6 +1108,8 @@ export class Reducer {
1037
1108
  ...(ev.extensions !== undefined ? { extensions: ev.extensions } : {}),
1038
1109
  };
1039
1110
  this.#artifacts.set(ev.artifactId, artifact);
1111
+ this.#rootThread ??= ev.threadId;
1112
+ this.#releaseHeldNested();
1040
1113
  break;
1041
1114
  }
1042
1115
  case "artifact.delta": {
@@ -1093,14 +1166,19 @@ export class Reducer {
1093
1166
  if (Array.isArray(patch)) {
1094
1167
  // RFC-6902 path: requires an existing document to patch against.
1095
1168
  if (this.#state === undefined) {
1169
+ // An empty patch applies no operation: nothing to resync, and the
1170
+ // state stays absent.
1171
+ if (patch.length === 0)
1172
+ break;
1096
1173
  // No document to apply the patch to — signal resync (same semantics
1097
1174
  // as memory.write patch against a never-seeded record).
1098
1175
  this.#resync = true;
1099
1176
  break;
1100
1177
  }
1101
1178
  const result = applyPatch(this.#state, patch);
1102
- if (!result.ok) {
1103
- // applyPatch failed — signal resync; leave #state unchanged.
1179
+ if (!result.ok || exceedsDepth(result.value, STORED_VALUE_MAX_DEPTH)) {
1180
+ // applyPatch failed, or its result nests deeper than a
1181
+ // state.snapshot could carry — signal resync; leave #state unchanged.
1104
1182
  this.#resync = true;
1105
1183
  break;
1106
1184
  }
@@ -1155,13 +1233,17 @@ export class Reducer {
1155
1233
  // PATCH path: mutate an existing record via R6 applyPatch.
1156
1234
  const existing = this.#memory.get(memKey);
1157
1235
  if (existing === undefined) {
1236
+ // An empty patch applies no operation: no record, no resync.
1237
+ if (Array.isArray(ev.patch) && ev.patch.length === 0)
1238
+ break;
1158
1239
  // NEVER seed from {} — set resync flag and bail.
1159
1240
  this.#resync = true;
1160
1241
  break;
1161
1242
  }
1162
1243
  const result = applyPatch(existing.value, ev.patch);
1163
- if (!result.ok) {
1164
- // applyPatch failed — set resync flag and leave record unchanged.
1244
+ if (!result.ok || exceedsDepth(result.value, STORED_VALUE_MAX_DEPTH)) {
1245
+ // applyPatch failed, or its result nests deeper than a memory.write
1246
+ // value could — set resync flag and leave record unchanged.
1165
1247
  this.#resync = true;
1166
1248
  break;
1167
1249
  }
@@ -1212,9 +1294,25 @@ export class Reducer {
1212
1294
  // CONDITIONALLY replace #turns (only if turns? present in event).
1213
1295
  if (ev.turns !== undefined) {
1214
1296
  this.#turns = new Map(structuredClone(ev.turns).map((t) => [t.turnId, t]));
1215
- // The snapshot's turns are authoritative: a landing held before it goes too.
1216
- this.#held = new Map();
1297
+ // The snapshot's turns are authoritative for a landing held before it,
1298
+ // except a display.required: it MUST NOT be dropped by a reducer and is
1299
+ // held, never discarded, until its turn's thread is known (§5, §13.3).
1300
+ // Only those entries stay held; the other landings go.
1301
+ const kept = new Map();
1302
+ let keptLandings = 0;
1303
+ for (const [turnId, held] of this.#held) {
1304
+ const entries = held.record.displayRequired;
1305
+ if (entries === undefined || entries.length === 0)
1306
+ continue;
1307
+ kept.set(turnId, { record: { turnId, threadId: "", displayRequired: entries }, landings: 0, dr: entries.length });
1308
+ keptLandings += entries.length;
1309
+ }
1310
+ this.#held = kept;
1217
1311
  this.#heldLandings = 0;
1312
+ this.#heldDrLandings = keptLandings;
1313
+ // ...and a held nested record goes with them, keeping only its
1314
+ // display.required landings, placed below.
1315
+ this.#heldNested.clear();
1218
1316
  }
1219
1317
  // CONDITIONALLY replace #artifacts (only if artifacts? present in event).
1220
1318
  if (ev.artifacts !== undefined) {
@@ -1248,10 +1346,9 @@ export class Reducer {
1248
1346
  this.#sealed = new Set();
1249
1347
  this.#blockPos = new Map();
1250
1348
  // #restartedSinceClose is NOT cleared: a snapshot folds no terminal (draft.5 INV-MSG).
1251
- // Task 8c leg 3: a snapshot-restored turn counts as opened (guuey
1252
- // capstone finding B) — reseed #openedTurns from the replaced turns in
1253
- // lockstep with #turns above; a turns-omitting snapshot re-seeds it from
1254
- // the records it keeps.
1349
+ // A snapshot-restored turn counts as opened: reseed #openedTurns from
1350
+ // the replaced turns in lockstep with #turns above; a turns-omitting
1351
+ // snapshot re-seeds it from the records it keeps.
1255
1352
  this.#openedTurns = ev.turns !== undefined
1256
1353
  ? new Set(ev.turns.map((t) => t.turnId))
1257
1354
  : new Set(this.#turns.keys());
@@ -1278,11 +1375,38 @@ export class Reducer {
1278
1375
  // draft.5 INV-OWNER: a held record whose thread this snapshot taught is adopted onto
1279
1376
  // it. #openedTurns was seeded above from records with a known thread
1280
1377
  // only, so an adopted record is not an adoption target by this snapshot.
1378
+ // A held record for a turn the snapshot itself carries joins that record
1379
+ // instead of replacing it: only display.required entries survive a
1380
+ // turns-carrying snapshot. Each held entry matches at most one entry the
1381
+ // snapshot's record already carried (the same landing, folded by the
1382
+ // snapshot's producer); an unmatched one is appended, so repeated entries
1383
+ // keep their count.
1281
1384
  for (const turnId of [...this.#held.keys()]) {
1282
1385
  const threadId = this.#seenOpened.get(turnId);
1283
- if (threadId !== undefined)
1386
+ if (threadId === undefined || this.#heldNested.has(turnId))
1387
+ continue;
1388
+ const present = this.#turns.get(turnId);
1389
+ if (present === undefined) {
1284
1390
  this.#adoptHeld(turnId, threadId);
1391
+ continue;
1392
+ }
1393
+ const held = this.#held.get(turnId);
1394
+ this.#held.delete(turnId);
1395
+ this.#heldLandings -= held.landings;
1396
+ this.#heldDrLandings -= held.dr;
1397
+ const list = (present.displayRequired ??= []);
1398
+ const unmatched = [...list];
1399
+ for (const entry of held.record.displayRequired ?? []) {
1400
+ const i = unmatched.findIndex((e) => e.provider === entry.provider && e.html === entry.html);
1401
+ if (i >= 0)
1402
+ unmatched.splice(i, 1);
1403
+ else
1404
+ list.push(entry);
1405
+ }
1285
1406
  }
1407
+ // The root thread: the first threadId the snapshot carried, in its turns, else its messages.
1408
+ this.#rootThread ??= ev.turns?.find((t) => t.threadId !== undefined)?.threadId ?? ev.messages.find((m) => m.threadId !== undefined)?.threadId;
1409
+ this.#releaseHeldNested();
1286
1410
  // Un-park.
1287
1411
  this.#resync = false;
1288
1412
  break;
@@ -1330,7 +1454,7 @@ export class Reducer {
1330
1454
  // Clear the per-block scratch buffers too (same block-id / toolCallId key),
1331
1455
  // else a stale opaque-signature / arg buffer leaks into a LATER message that
1332
1456
  // reuses the same id (cross-task scratch leak — byte-identity can't catch it
1333
- // because it corrupts batch AND incremental identically). (final-review M1)
1457
+ // because it corrupts batch AND incremental identically).
1334
1458
  this.#toolArgs.delete(blockId);
1335
1459
  this.#opaque.delete(blockId);
1336
1460
  // INV-BLOCK is about ids PRESENT in the fold (SPEC INV-BLOCK): a removed
@@ -1412,8 +1536,8 @@ export class Reducer {
1412
1536
  }
1413
1537
  }
1414
1538
  /**
1415
- * Evict dangling per-block streaming scratch owned by a closed turn
1416
- * (audit M51): #toolArgs/#opaque entries are otherwise reclaimed only on
1539
+ * Evict dangling per-block streaming scratch owned by a closed turn:
1540
+ * #toolArgs/#opaque entries are otherwise reclaimed only on
1417
1541
  * assembled/seal/snapshot — an errored/aborted turn leaks them and a reused
1418
1542
  * per-invoke block id in a LATER turn would concatenate stale scratch.
1419
1543
  */
@@ -1449,11 +1573,11 @@ export class Reducer {
1449
1573
  * folds onto no record closes nothing; a messages.snapshot changes closure
1450
1574
  * only through the records its §5 per-container rule leaves in the fold. No
1451
1575
  * message of a closed turn (sealed or not, existing or not yet created) is a
1452
- * valid attach or adoption target. `key` is a resolved turnId, or the
1453
- * "unknown-turn" key of a message with no turnId, which names no record.
1576
+ * valid attach or adoption target. `key` is a resolved turnId, or undefined
1577
+ * for a message with no turnId, which names no record.
1454
1578
  */
1455
1579
  #isClosedTurn(key) {
1456
- return key !== undefined && this.#turns.get(key)?.outcome !== undefined;
1580
+ return key !== undefined && (this.#turns.get(key) ?? this.#held.get(key)?.record)?.outcome !== undefined;
1457
1581
  }
1458
1582
  /**
1459
1583
  * draft.5 §5.0 INV-MSG / INV-TURN: may a terminal fold onto `turn`? A turn
@@ -1493,20 +1617,62 @@ export class Reducer {
1493
1617
  // §4 per-turn routing / INV-OWNER (draft.5): an omitted turnId
1494
1618
  // resolves to the sole OPEN turn, never to a closed one (through draft.4
1495
1619
  // this counted records, so a lone closed turn or a stub could be picked).
1496
- return this.#soleOpenRecord()?.turnId;
1620
+ return this.#soleOpenTurn();
1497
1621
  }
1498
- /** The sole OPEN turn record (no `outcome` yet), or undefined when none or several are open. */
1499
- #soleOpenRecord() {
1622
+ /**
1623
+ * The sole OPEN turn (§4 per-turn routing, INV-OWNER): one the reducer has seen
1624
+ * opened (or holds a record for) that is not closed. Undefined when none or
1625
+ * several are open.
1626
+ */
1627
+ #soleOpenTurn() {
1500
1628
  let found;
1501
- for (const t of this.#turns.values()) {
1502
- if (t.outcome !== undefined)
1629
+ for (const turnId of new Set([...this.#seenOpened.keys(), ...this.#turns.keys()])) {
1630
+ if (this.#isClosedTurn(turnId))
1503
1631
  continue;
1504
1632
  if (found !== undefined)
1505
1633
  return undefined;
1506
- found = t;
1634
+ found = turnId;
1507
1635
  }
1508
1636
  return found;
1509
1637
  }
1638
+ /** A turn's known thread: its record's, else the one it was seen opened on. */
1639
+ #threadOfTurn(turnId) {
1640
+ if (this.#heldNested.has(turnId))
1641
+ return undefined;
1642
+ return this.#turns.get(turnId)?.threadId ?? this.#seenOpened.get(turnId);
1643
+ }
1644
+ /**
1645
+ * Release every held nested record whose parent's thread or the root thread is
1646
+ * now known onto that thread (the parent's first). Repeats until none moves, so
1647
+ * a chain of held nested turns releases in one pass.
1648
+ */
1649
+ #releaseHeldNested() {
1650
+ const release = (turnId, parentTurnId, threadId) => {
1651
+ this.#heldNested.delete(turnId);
1652
+ this.#adoptHeld(turnId, threadId, parentTurnId);
1653
+ this.#seenOpened.set(turnId, threadId);
1654
+ };
1655
+ let moved = true;
1656
+ while (moved && this.#heldNested.size > 0) {
1657
+ moved = false;
1658
+ for (const [turnId, parentTurnId] of [...this.#heldNested]) {
1659
+ const threadId = this.#threadOfTurn(parentTurnId);
1660
+ if (threadId === undefined)
1661
+ continue;
1662
+ release(turnId, parentTurnId, threadId);
1663
+ moved = true;
1664
+ }
1665
+ if (moved || this.#rootThread === undefined)
1666
+ continue;
1667
+ let heads = [...this.#heldNested].filter(([, p]) => !this.#heldNested.has(p));
1668
+ if (heads.length === 0)
1669
+ heads = [...this.#heldNested].slice(0, 1);
1670
+ for (const [turnId, parentTurnId] of heads) {
1671
+ release(turnId, parentTurnId, this.#rootThread);
1672
+ moved = true;
1673
+ }
1674
+ }
1675
+ }
1510
1676
  /**
1511
1677
  * Where a record event lands (draft.5 INV-OWNER). A named turn with a
1512
1678
  * record lands on it; one whose thread is known gets a new record on that
@@ -1515,12 +1681,13 @@ export class Reducer {
1515
1681
  * event lands on the sole open turn's record, else its owner is unresolvable
1516
1682
  * and the fold parks.
1517
1683
  */
1518
- #landingRecord(turnId) {
1684
+ #landingRecord(turnId, displayRequired = false) {
1519
1685
  if (turnId === undefined) {
1520
- const sole = this.#soleOpenRecord();
1521
- if (sole === undefined)
1686
+ turnId = this.#soleOpenTurn();
1687
+ if (turnId === undefined) {
1522
1688
  this.#resync = true;
1523
- return sole;
1689
+ return undefined;
1690
+ }
1524
1691
  }
1525
1692
  const existing = this.#turns.get(turnId);
1526
1693
  if (existing !== undefined)
@@ -1529,17 +1696,27 @@ export class Reducer {
1529
1696
  if (threadId !== undefined)
1530
1697
  return this.#seenTurnRecord(turnId);
1531
1698
  let held = this.#held.get(turnId);
1532
- if ((held === undefined && this.#held.size >= HELD_TURNS_CAP) || this.#heldLandings >= HELD_LANDINGS_CAP) {
1699
+ // The bound counts display.required landings and the other five apart (#held).
1700
+ const newTurn = held === undefined || (displayRequired ? held.dr === 0 : held.landings === 0);
1701
+ const heldTurns = newTurn ? [...this.#held.values()].filter((h) => (displayRequired ? h.dr : h.landings) > 0).length : 0;
1702
+ const heldLandings = displayRequired ? this.#heldDrLandings : this.#heldLandings;
1703
+ if ((newTurn && heldTurns >= HELD_TURNS_CAP) || heldLandings >= HELD_LANDINGS_CAP) {
1533
1704
  this.#resync = true; // degrade loudly past the bound
1534
1705
  return undefined;
1535
1706
  }
1536
1707
  if (held === undefined) {
1537
1708
  // threadId is set on adoption; a held record is never emitted.
1538
- held = { record: { turnId, threadId: "" }, landings: 0 };
1709
+ held = { record: { turnId, threadId: "" }, landings: 0, dr: 0 };
1539
1710
  this.#held.set(turnId, held);
1540
1711
  }
1541
- held.landings++;
1542
- this.#heldLandings++;
1712
+ if (displayRequired) {
1713
+ held.dr++;
1714
+ this.#heldDrLandings++;
1715
+ }
1716
+ else {
1717
+ held.landings++;
1718
+ this.#heldLandings++;
1719
+ }
1543
1720
  return held.record;
1544
1721
  }
1545
1722
  /**
@@ -1552,7 +1729,9 @@ export class Reducer {
1552
1729
  if (held === undefined)
1553
1730
  return undefined;
1554
1731
  this.#held.delete(turnId);
1732
+ this.#heldNested.delete(turnId);
1555
1733
  this.#heldLandings -= held.landings;
1734
+ this.#heldDrLandings -= held.dr;
1556
1735
  const { turnId: _turnId, threadId: _placeholder, ...landings } = held.record;
1557
1736
  const record = {
1558
1737
  turnId,
@@ -1564,11 +1743,11 @@ export class Reducer {
1564
1743
  return record;
1565
1744
  }
1566
1745
  /**
1567
- * D9: the record a terminal for a SEEN turn folds onto — the existing one,
1746
+ * INV-OWNER: the record a terminal for a SEEN turn folds onto — the existing one,
1568
1747
  * else one created on the thread the fold saw the turn opened on. With no
1569
1748
  * thread known it returns undefined and the terminal folds onto no record.
1570
1749
  * No other turn's thread is borrowed (that could adopt a subagent's parent
1571
- * label as a threadId), and a D9 path never writes a threadId equal to its
1750
+ * label as a threadId), and an INV-OWNER path never writes a threadId equal to its
1572
1751
  * turnId.
1573
1752
  */
1574
1753
  #seenTurnRecord(turnId) {
@@ -1576,8 +1755,10 @@ export class Reducer {
1576
1755
  if (existing !== undefined)
1577
1756
  return existing;
1578
1757
  const threadId = this.#seenOpened.get(turnId);
1579
- if (threadId === undefined)
1580
- return undefined;
1758
+ if (threadId === undefined) {
1759
+ // A nested turn whose record is held: a terminal lands on that record (INV-OWNER).
1760
+ return this.#heldNested.has(turnId) ? this.#held.get(turnId)?.record : undefined;
1761
+ }
1581
1762
  const adopted = this.#adoptHeld(turnId, threadId);
1582
1763
  if (adopted !== undefined)
1583
1764
  return adopted;
@@ -1619,7 +1800,7 @@ export class Reducer {
1619
1800
  }
1620
1801
  /**
1621
1802
  * Batch fold. Returns the folded result AND the resync signal — a parked fold
1622
- * is never a silent truncation (audit M50; INV-SEQ: "a conformant reducer MUST
1803
+ * is never a silent truncation (INV-SEQ: "a conformant reducer MUST
1623
1804
  * expose its resync condition to the caller").
1624
1805
  */
1625
1806
  export function reduce(events) {