@silverprotocol/core 0.12.5 → 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 (51) 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 +25 -14
  5. package/dist/agjson.js.map +1 -1
  6. package/dist/atomic-push.js.map +1 -1
  7. package/dist/copy-json.d.ts +27 -4
  8. package/dist/copy-json.d.ts.map +1 -1
  9. package/dist/copy-json.js +111 -1
  10. package/dist/copy-json.js.map +1 -1
  11. package/dist/depth.d.ts +0 -8
  12. package/dist/depth.d.ts.map +1 -1
  13. package/dist/depth.js +0 -9
  14. package/dist/depth.js.map +1 -1
  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 +2 -2
  20. package/dist/ingest.js +4 -4
  21. package/dist/ingest.js.map +1 -1
  22. package/dist/json-patch.d.ts.map +1 -1
  23. package/dist/json-patch.js +5 -1
  24. package/dist/json-patch.js.map +1 -1
  25. package/dist/persist.js.map +1 -1
  26. package/dist/record.js +2 -2
  27. package/dist/record.js.map +1 -1
  28. package/dist/reduce.d.ts +1 -1
  29. package/dist/reduce.d.ts.map +1 -1
  30. package/dist/reduce.js +277 -113
  31. package/dist/reduce.js.map +1 -1
  32. package/dist/stream-assembler.d.ts +6 -7
  33. package/dist/stream-assembler.d.ts.map +1 -1
  34. package/dist/stream-assembler.js +21 -18
  35. package/dist/stream-assembler.js.map +1 -1
  36. package/dist/wire.d.ts +21 -3
  37. package/dist/wire.d.ts.map +1 -1
  38. package/dist/wire.js +34 -5
  39. package/dist/wire.js.map +1 -1
  40. package/package.json +1 -1
  41. package/src/agjson.ts +36 -25
  42. package/src/atomic-push.ts +2 -2
  43. package/src/copy-json.ts +107 -4
  44. package/src/depth.ts +0 -10
  45. package/src/index.ts +1 -0
  46. package/src/ingest.ts +4 -4
  47. package/src/json-patch.ts +5 -1
  48. package/src/record.ts +2 -2
  49. package/src/reduce.ts +256 -112
  50. package/src/stream-assembler.ts +21 -18
  51. package/src/wire.ts +36 -6
package/dist/reduce.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { REMOVE_ALL } from "./agjson.js";
2
2
  import { applyPatch } from "./json-patch.js";
3
- import { AG_EVENT_MAX_DEPTH, exceedsDepth, scanDepth } from "./depth.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";
4
6
  // ─────────────────────────────────────────────────────────────────────────────
5
7
  // Reducer — the normative event→state fold (spec §5).
6
8
  //
@@ -110,10 +112,10 @@ export class Reducer {
110
112
  // Message ids sealed by message.end.
111
113
  #sealed = new Set();
112
114
  // turnIds legitimately opened via turn.start / subagent.start (or restored
113
- // by a messages.snapshot's turns?) — Task 8c leg 3 (guuey capstone finding
114
- // B). Distinguishes "a real turn genuinely exists" from a turn the fold only
115
- // knows by name, so the tool.done adoption CREATE path degrades loudly
116
- // (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.
117
119
  #openedTurns = new Set();
118
120
  // draft.4 §5.0 INV-OWNER: every
119
121
  // turnId the fold has seen opened — by turn.start, by subagent.start, or by a
@@ -125,15 +127,28 @@ export class Reducer {
125
127
  // #openedTurns (tool.done adoption) and never rebuilt from #turns, whose
126
128
  // records non-terminal arms may have minted as stubs.
127
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();
128
138
  // draft.5 §5.0 INV-OWNER (a held record lands on its own turn's thread): the landings of
129
139
  // the six record events (source, handoff, prompt.blocked, guardrail.result,
130
140
  // display.required, agent.capabilities) for a turn whose thread the fold does
131
141
  // not know yet. Each is a turn record result() never shows; it moves into
132
142
  // #turns on the turn's thread once a turn.start, subagent.start, message.start
133
143
  // or messages.snapshot makes that thread known (#adoptHeld). `landings` counts
134
- // 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.
135
149
  #held = new Map();
136
150
  #heldLandings = 0;
151
+ #heldDrLandings = 0;
137
152
  // draft.5 §5.0 INV-MSG (the paused refresh): closed turns a turn.start has
138
153
  // named since their last terminal folded. Only such a turn, closed paused,
139
154
  // takes a turn.done{paused}; every terminal that folds removes its id. A
@@ -165,10 +180,11 @@ export class Reducer {
165
180
  */
166
181
  push(ev) {
167
182
  // One pass before anything reads the event: whether a node sits deeper
168
- // than AG_EVENT_MAX_DEPTH. A too-deep event occupies its seq slot like any
169
- // other and is folded no further: copying it, or patching the state with
170
- // it, would overflow the stack. A consuming ingest never yields one; it
171
- // stubs such a frame.
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.
172
188
  const scan = scanDepth(ev, AG_EVENT_MAX_DEPTH);
173
189
  // ── Seq-gap detection (R9) ────────────────────────────────────────────────
174
190
  // Seq accounting is UNIVERSAL (INV-SEQ: "gap-free ordinal" over the whole
@@ -177,7 +193,7 @@ export class Reducer {
177
193
  // other live-only events). This must run BEFORE the isClosedEvent skip
178
194
  // below: an ext/live-only event between two closed events still occupies a
179
195
  // seq slot, so skipping it here would let the NEXT closed event look like
180
- // 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
181
197
  // this fixes voided every fold with an ext emission between closed events).
182
198
  // After the first event (#lastSeq >= 0), a forward gap sets #resync (park)
183
199
  // — including when an ext/live-only event is the one revealing the gap.
@@ -220,11 +236,24 @@ export class Reducer {
220
236
  // It runs before the ext guard below, which then narrows the copy. An event
221
237
  // structuredClone cannot copy (a function-valued field) folds as pushed, as
222
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().
223
244
  try {
224
245
  ev = structuredClone(ev);
246
+ if (scan.hasOwnProto)
247
+ deleteOwnProtoMember(ev);
225
248
  }
226
249
  catch {
227
- // 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
+ }
228
257
  }
229
258
  // Ext events (`ext.<vendor>.<key>`) are live-only / non-folding (§4/§12).
230
259
  // Rule them out HERE — after seq accounting above, so an ext event still
@@ -239,7 +268,7 @@ export class Reducer {
239
268
  // draft.5 INV-MSG: a turn.start naming a closed turn opens its paused refresh.
240
269
  if (this.#isClosedTurn(ev.turnId))
241
270
  this.#restartedSinceClose.add(ev.turnId);
242
- // 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.
243
272
  this.#openedTurns.add(ev.turnId);
244
273
  this.#seenOpened.set(ev.turnId, ev.threadId);
245
274
  // Idempotent: if the turn already exists, merge defined fields only. A
@@ -260,17 +289,29 @@ export class Reducer {
260
289
  existing.trigger = ev.trigger;
261
290
  }
262
291
  }
292
+ this.#rootThread ??= ev.threadId;
293
+ this.#releaseHeldNested();
263
294
  break;
264
295
  }
265
296
  // ── MESSAGE lifecycle ──────────────────────────────────────────────────
266
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
+ }
267
308
  // INV-MSG: a message.start for a turn that already closed parks.
268
309
  if (this.#isClosedTurn(this.#resolveTurnId(ev.turnId) ?? ev.turnId)) {
269
310
  this.#resync = true;
270
311
  break;
271
312
  }
272
313
  // draft.5 INV-OWNER: a live message.start makes its turn's thread
273
- // 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
274
315
  // the first one folded), and a record held for the turn is adopted onto it.
275
316
  if (this.#seenOpened.get(ev.turnId) === undefined)
276
317
  this.#seenOpened.set(ev.turnId, ev.threadId);
@@ -294,6 +335,8 @@ export class Reducer {
294
335
  this.#messages.set(ev.id, msg);
295
336
  // Register partition pointer: (turnId, candidateIndex ?? 0) → message id.
296
337
  this.#openMsg.set(partKey(ev.turnId, ev.candidateIndex ?? 0), ev.id);
338
+ this.#rootThread ??= ev.threadId;
339
+ this.#releaseHeldNested();
297
340
  break;
298
341
  }
299
342
  case "message.end": {
@@ -314,36 +357,39 @@ export class Reducer {
314
357
  }
315
358
  // ── SUBAGENT lifecycle ─────────────────────────────────────────────────
316
359
  case "subagent.start": {
317
- // Task 8c leg 3: a subagent.start always counts as a legitimately
360
+ // A subagent.start always counts as a legitimately
318
361
  // opened turn, even on the idempotent-duplicate early return below.
319
362
  this.#openedTurns.add(ev.turnId);
320
- // 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.
321
366
  const existingNested = this.#turns.get(ev.turnId);
322
367
  if (existingNested !== undefined) {
368
+ if (existingNested.parentTurnId === undefined)
369
+ existingNested.parentTurnId = ev.parentTurnId;
323
370
  this.#seenOpened.set(ev.turnId, existingNested.threadId);
324
371
  break;
325
372
  }
326
- // threadId is required on AgTurnRecord; inherit from the parent turn.
327
- // subagent.start does not carry threadId on the wire, so we look it up.
328
- const parentTurn = this.#turns.get(ev.parentTurnId);
329
- let threadId;
330
- if (parentTurn !== undefined) {
331
- threadId = parentTurn.threadId;
332
- }
333
- else {
334
- // Task 8c leg 2 (SPEC §1.2 + guuey capstone finding A): a parent
335
- // lookup miss means ev.parentTurnId is a wire label that was never
336
- // opened as a real turn (e.g. claude's synthetic `turn_${toolCallId}`
337
- // Task-tool cross-ref) — NOT a legitimate cross-thread reference.
338
- // Every entity in a fold shares one root threadId (SPEC §1.2), so
339
- // fall back to any ALREADY-OPENED real turn's threadId instead of
340
- // adopting the unresolvable label as this subagent's own threadId.
341
- // A "real" turn is identified by threadId !== turnId: through draft.4
342
- // a defensive stub used its own turnId as a placeholder thread. draft.5
343
- // retires the stubs, and the check stays as a guard.
344
- // `ev.parentTurnId` remains the last resort when no real turn exists yet.
345
- const realTurn = [...this.#turns.values()].find((t) => t.threadId !== t.turnId);
346
- 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;
347
393
  }
348
394
  // A record held for this nested turn takes the thread and the
349
395
  // parentTurnId here; otherwise a new record opens.
@@ -355,6 +401,7 @@ export class Reducer {
355
401
  });
356
402
  }
357
403
  this.#seenOpened.set(ev.turnId, threadId);
404
+ this.#releaseHeldNested();
358
405
  break;
359
406
  }
360
407
  case "subagent.done": {
@@ -420,12 +467,12 @@ export class Reducer {
420
467
  const msg = this.#messages.get(pos.messageId);
421
468
  if (msg === undefined)
422
469
  break;
423
- // 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
424
471
  // message, or into any message of a closed turn, parks like a delta.
425
472
  if (this.#isClosedTarget(msg.id)) {
426
473
  this.#resync = true;
427
474
  break;
428
- } // INV-MSG finalizer guard (E5)
475
+ } // INV-MSG finalizer guard
429
476
  const block = msg.content[pos.index];
430
477
  if (block === undefined || block.type !== "text")
431
478
  break;
@@ -434,7 +481,7 @@ export class Reducer {
434
481
  if (ev.phase !== undefined && !this.#sealed.has(msg.id))
435
482
  block.phase = ev.phase;
436
483
  setProviderMeta(block, ev.providerMetadata);
437
- // STREAMED-text citations carrier (audit M22): attach citations to the
484
+ // STREAMED-text citations carrier: attach citations to the
438
485
  // sealed block named by `ev.id` — never re-emitted as a duplicate
439
486
  // supplement block.
440
487
  if (ev.citations !== undefined)
@@ -491,12 +538,12 @@ export class Reducer {
491
538
  const msg = this.#messages.get(pos.messageId);
492
539
  if (msg === undefined)
493
540
  break;
494
- // 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
495
542
  // message, or into any message of a closed turn, parks like a delta.
496
543
  if (this.#isClosedTarget(msg.id)) {
497
544
  this.#resync = true;
498
545
  break;
499
- } // INV-MSG finalizer guard (E5)
546
+ } // INV-MSG finalizer guard
500
547
  const block = msg.content[pos.index];
501
548
  if (block === undefined || block.type !== "reasoning")
502
549
  break;
@@ -531,12 +578,12 @@ export class Reducer {
531
578
  const msg = this.#messages.get(pos.messageId);
532
579
  if (msg === undefined)
533
580
  break;
534
- // 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
535
582
  // message, or into any message of a closed turn, parks like a delta.
536
583
  if (this.#isClosedTarget(msg.id)) {
537
584
  this.#resync = true;
538
585
  break;
539
- } // INV-MSG finalizer guard (E5)
586
+ } // INV-MSG finalizer guard
540
587
  const block = msg.content[pos.index];
541
588
  if (block === undefined || block.type !== "reasoning")
542
589
  break;
@@ -602,12 +649,12 @@ export class Reducer {
602
649
  const msg = this.#messages.get(pos.messageId);
603
650
  if (msg === undefined)
604
651
  break;
605
- // 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
606
653
  // message, or into any message of a closed turn, parks like a delta.
607
654
  if (this.#isClosedTarget(msg.id)) {
608
655
  this.#resync = true;
609
656
  break;
610
- } // INV-MSG finalizer guard (E5)
657
+ } // INV-MSG finalizer guard
611
658
  const block = msg.content[pos.index];
612
659
  if (block === undefined || block.type !== "tool-call")
613
660
  break;
@@ -629,12 +676,12 @@ export class Reducer {
629
676
  // ── TOOL-RESULT blocks ────────────────────────────────────────────────────
630
677
  case "tool.done": {
631
678
  // INV-BLOCK: a second FINAL (more-less) tool.done for one call parks.
632
- if (ev.more !== true) {
633
- if (this.#finalToolDone.has(ev.toolCallId)) {
634
- this.#resync = true;
635
- break;
636
- }
637
- 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;
638
685
  }
639
686
  const resultKey = `result:${ev.toolCallId}`;
640
687
  const existingPos = this.#blockPos.get(resultKey);
@@ -653,8 +700,7 @@ export class Reducer {
653
700
  // published content. Resolve the block's owning turn via the
654
701
  // #blockPos → messageId → message.turnId chain and park instead of mutating
655
702
  // (mirrors the adoption path's closed-turn/sealed guard above).
656
- const ownerTurnKey = msg.turnId ?? "unknown-turn";
657
- if (this.#sealed.has(msg.id) || this.#isClosedTurn(ownerTurnKey)) {
703
+ if (this.#sealed.has(msg.id) || this.#isClosedTurn(msg.turnId)) {
658
704
  this.#resync = true;
659
705
  break;
660
706
  }
@@ -690,7 +736,7 @@ export class Reducer {
690
736
  if (ev._meta !== undefined)
691
737
  block._meta = ev._meta;
692
738
  setProviderMeta(block, ev.providerMetadata);
693
- // Typed preliminary flag mirrors the block's `more` state (audit M20):
739
+ // Typed preliminary flag mirrors the block's `more` state:
694
740
  // more:true keeps it set (kept open); the final more-less tool.done
695
741
  // clears it and closes the result (removed from open tracking).
696
742
  if (ev.more) {
@@ -699,6 +745,7 @@ export class Reducer {
699
745
  else {
700
746
  delete block.preliminary;
701
747
  this.#blockPos.delete(resultKey);
748
+ this.#finalToolDone.add(ev.toolCallId);
702
749
  }
703
750
  }
704
751
  else {
@@ -706,7 +753,7 @@ export class Reducer {
706
753
  let msg;
707
754
  if (ev.messageId !== undefined) {
708
755
  // SPEC §5 tool.done row: the landed tool-result message ADOPTS
709
- // ev.messageId as its own id (stable ToolMessage identity; audit B10).
756
+ // ev.messageId as its own id (stable ToolMessage identity).
710
757
  const existing = this.#messages.get(ev.messageId);
711
758
  // INV-MSG enforcement: a sealed message, or ANY message of a closed
712
759
  // turn — including one that would need to be freshly created — is
@@ -714,16 +761,18 @@ export class Reducer {
714
761
  // would land in (the existing message's own turnId, or the turn a
715
762
  // new message would take) BEFORE either sub-path runs, and park
716
763
  // instead of silently attaching/creating past the seal or the
717
- // turn's binding window. "unknown-turn" is only a key that names no
718
- // 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.
719
767
  const targetTurnKey = existing !== undefined
720
- ? (existing.turnId ?? "unknown-turn")
721
- : (this.#resolveTurnId(ev.turnId) ?? ev.turnId ?? "unknown-turn");
722
- // Task 8c leg 3 (guuey capstone finding B): a turn that was never
723
- // legitimately opened (turn.start / subagent.start / a snapshot's
724
- // turns?) is just as invalid an adoption target as a sealed
725
- // message or a closed turn: park rather than create a message for it.
726
- 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) ||
727
776
  this.#isClosedTurn(targetTurnKey) ||
728
777
  !this.#openedTurns.has(targetTurnKey)) {
729
778
  this.#resync = true;
@@ -784,6 +833,9 @@ export class Reducer {
784
833
  if (ev.more) {
785
834
  this.#blockPos.set(resultKey, { messageId: msg.id, index });
786
835
  }
836
+ else {
837
+ this.#finalToolDone.add(ev.toolCallId);
838
+ }
787
839
  }
788
840
  break;
789
841
  }
@@ -836,7 +888,7 @@ export class Reducer {
836
888
  }
837
889
  // ── TURN-RECORD events (R5) ───────────────────────────────────────────────
838
890
  case "turn.done": {
839
- // 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
840
892
  // opened is not an unresolvable owner: it folds onto no turn record and
841
893
  // does not park. A CORE client that ignores subagent.*, or a fold whose
842
894
  // opener was dropped, sees exactly this; a producer's lone terminal fails
@@ -868,7 +920,7 @@ export class Reducer {
868
920
  }
869
921
  // messageMetadata: REPLACE the whole messageMetadata bag of the message named
870
922
  // by turn.done.messageId when present, else of the open message of this turn
871
- // (audit M20; §5 turn.done row, §13.10). No per-key merge.
923
+ // (§5 turn.done row, §13.10). No per-key merge.
872
924
  // (Read happens BEFORE the binding window closes below.)
873
925
  if (ev.messageMetadata !== undefined) {
874
926
  const msg = ev.messageId !== undefined ? this.#messages.get(ev.messageId) : this.openMessage(ev.turnId, 0);
@@ -883,17 +935,19 @@ export class Reducer {
883
935
  }
884
936
  case "turn.error": {
885
937
  // Non-folding into content; sets outcome={type:"error",...} on the turn record.
886
- // 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
887
939
  // the sole OPEN turn, never a closed one; with none or several open its
888
940
  // owner is unresolvable and the fold parks (INV-OWNER, draft.5).
889
941
  if (ev.turnId !== undefined && !this.#seenOpened.has(ev.turnId))
890
942
  break;
891
- const turn = ev.turnId !== undefined ? this.#seenTurnRecord(ev.turnId) : this.#soleOpenRecord();
892
- if (turn === undefined) {
893
- if (ev.turnId === undefined)
894
- this.#resync = true;
943
+ const owner = ev.turnId ?? this.#soleOpenTurn();
944
+ if (owner === undefined) {
945
+ this.#resync = true;
895
946
  break;
896
947
  }
948
+ const turn = this.#seenTurnRecord(owner);
949
+ if (turn === undefined)
950
+ break;
897
951
  // draft.5 INV-MSG: a turn.error for a closed turn parks, writing nothing.
898
952
  if (!this.#terminalMayFold(turn, false))
899
953
  break;
@@ -917,18 +971,20 @@ export class Reducer {
917
971
  case "turn.abort": {
918
972
  // Non-folding into content; sets a dedicated aborted outcome on the turn record
919
973
  // (symmetric with turn.error). taskState is verbatim-A2A only and is NEVER
920
- // reducer-invented (audit M29) — it stays whatever a prior turn.done left it as.
921
- // 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
922
976
  // the sole OPEN turn, never a closed one; with none or several open its
923
977
  // owner is unresolvable and the fold parks (INV-OWNER, draft.5).
924
978
  if (ev.turnId !== undefined && !this.#seenOpened.has(ev.turnId))
925
979
  break;
926
- const turn = ev.turnId !== undefined ? this.#seenTurnRecord(ev.turnId) : this.#soleOpenRecord();
927
- if (turn === undefined) {
928
- if (ev.turnId === undefined)
929
- this.#resync = true;
980
+ const owner = ev.turnId ?? this.#soleOpenTurn();
981
+ if (owner === undefined) {
982
+ this.#resync = true;
930
983
  break;
931
984
  }
985
+ const turn = this.#seenTurnRecord(owner);
986
+ if (turn === undefined)
987
+ break;
932
988
  // draft.5 INV-MSG: a turn.abort for a closed turn parks, writing nothing.
933
989
  if (!this.#terminalMayFold(turn, false))
934
990
  break;
@@ -941,7 +997,7 @@ export class Reducer {
941
997
  case "source": {
942
998
  // Append sourceId to the turn's sourceIds[] in order (preserve groundingChunks order),
943
999
  // AND land the FULL record (payload/chunkIndex/providerMetadata) on sources[] so
944
- // 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.
945
1001
  const turn = this.#landingRecord(ev.turnId);
946
1002
  if (turn === undefined)
947
1003
  break;
@@ -981,7 +1037,7 @@ export class Reducer {
981
1037
  // Record safety[] on the turn (merge — append to existing safety, or create) AND
982
1038
  // land the dedicated promptBlocked record {reason, safety?} so the REQUIRED reason
983
1039
  // and the blockedness itself survive the fold — a bare-reason block used to fold to
984
- // ZERO trace (audit M28).
1040
+ // ZERO trace.
985
1041
  const turn = this.#landingRecord(ev.turnId);
986
1042
  if (turn === undefined)
987
1043
  break;
@@ -1020,7 +1076,7 @@ export class Reducer {
1020
1076
  }
1021
1077
  case "display.required": {
1022
1078
  // MUST NOT drop (ToS). Push {provider, html} onto turn's displayRequired[].
1023
- const turn = this.#landingRecord(ev.turnId);
1079
+ const turn = this.#landingRecord(ev.turnId, true);
1024
1080
  if (turn === undefined)
1025
1081
  break;
1026
1082
  if (turn.displayRequired === undefined) {
@@ -1052,6 +1108,8 @@ export class Reducer {
1052
1108
  ...(ev.extensions !== undefined ? { extensions: ev.extensions } : {}),
1053
1109
  };
1054
1110
  this.#artifacts.set(ev.artifactId, artifact);
1111
+ this.#rootThread ??= ev.threadId;
1112
+ this.#releaseHeldNested();
1055
1113
  break;
1056
1114
  }
1057
1115
  case "artifact.delta": {
@@ -1108,6 +1166,10 @@ export class Reducer {
1108
1166
  if (Array.isArray(patch)) {
1109
1167
  // RFC-6902 path: requires an existing document to patch against.
1110
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;
1111
1173
  // No document to apply the patch to — signal resync (same semantics
1112
1174
  // as memory.write patch against a never-seeded record).
1113
1175
  this.#resync = true;
@@ -1171,6 +1233,9 @@ export class Reducer {
1171
1233
  // PATCH path: mutate an existing record via R6 applyPatch.
1172
1234
  const existing = this.#memory.get(memKey);
1173
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;
1174
1239
  // NEVER seed from {} — set resync flag and bail.
1175
1240
  this.#resync = true;
1176
1241
  break;
@@ -1229,9 +1294,25 @@ export class Reducer {
1229
1294
  // CONDITIONALLY replace #turns (only if turns? present in event).
1230
1295
  if (ev.turns !== undefined) {
1231
1296
  this.#turns = new Map(structuredClone(ev.turns).map((t) => [t.turnId, t]));
1232
- // The snapshot's turns are authoritative: a landing held before it goes too.
1233
- 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;
1234
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();
1235
1316
  }
1236
1317
  // CONDITIONALLY replace #artifacts (only if artifacts? present in event).
1237
1318
  if (ev.artifacts !== undefined) {
@@ -1265,10 +1346,9 @@ export class Reducer {
1265
1346
  this.#sealed = new Set();
1266
1347
  this.#blockPos = new Map();
1267
1348
  // #restartedSinceClose is NOT cleared: a snapshot folds no terminal (draft.5 INV-MSG).
1268
- // Task 8c leg 3: a snapshot-restored turn counts as opened (guuey
1269
- // capstone finding B) — reseed #openedTurns from the replaced turns in
1270
- // lockstep with #turns above; a turns-omitting snapshot re-seeds it from
1271
- // 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.
1272
1352
  this.#openedTurns = ev.turns !== undefined
1273
1353
  ? new Set(ev.turns.map((t) => t.turnId))
1274
1354
  : new Set(this.#turns.keys());
@@ -1295,11 +1375,38 @@ export class Reducer {
1295
1375
  // draft.5 INV-OWNER: a held record whose thread this snapshot taught is adopted onto
1296
1376
  // it. #openedTurns was seeded above from records with a known thread
1297
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.
1298
1384
  for (const turnId of [...this.#held.keys()]) {
1299
1385
  const threadId = this.#seenOpened.get(turnId);
1300
- if (threadId !== undefined)
1386
+ if (threadId === undefined || this.#heldNested.has(turnId))
1387
+ continue;
1388
+ const present = this.#turns.get(turnId);
1389
+ if (present === undefined) {
1301
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
+ }
1302
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();
1303
1410
  // Un-park.
1304
1411
  this.#resync = false;
1305
1412
  break;
@@ -1347,7 +1454,7 @@ export class Reducer {
1347
1454
  // Clear the per-block scratch buffers too (same block-id / toolCallId key),
1348
1455
  // else a stale opaque-signature / arg buffer leaks into a LATER message that
1349
1456
  // reuses the same id (cross-task scratch leak — byte-identity can't catch it
1350
- // because it corrupts batch AND incremental identically). (final-review M1)
1457
+ // because it corrupts batch AND incremental identically).
1351
1458
  this.#toolArgs.delete(blockId);
1352
1459
  this.#opaque.delete(blockId);
1353
1460
  // INV-BLOCK is about ids PRESENT in the fold (SPEC INV-BLOCK): a removed
@@ -1429,8 +1536,8 @@ export class Reducer {
1429
1536
  }
1430
1537
  }
1431
1538
  /**
1432
- * Evict dangling per-block streaming scratch owned by a closed turn
1433
- * (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
1434
1541
  * assembled/seal/snapshot — an errored/aborted turn leaks them and a reused
1435
1542
  * per-invoke block id in a LATER turn would concatenate stale scratch.
1436
1543
  */
@@ -1466,11 +1573,11 @@ export class Reducer {
1466
1573
  * folds onto no record closes nothing; a messages.snapshot changes closure
1467
1574
  * only through the records its §5 per-container rule leaves in the fold. No
1468
1575
  * message of a closed turn (sealed or not, existing or not yet created) is a
1469
- * valid attach or adoption target. `key` is a resolved turnId, or the
1470
- * "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.
1471
1578
  */
1472
1579
  #isClosedTurn(key) {
1473
- return key !== undefined && this.#turns.get(key)?.outcome !== undefined;
1580
+ return key !== undefined && (this.#turns.get(key) ?? this.#held.get(key)?.record)?.outcome !== undefined;
1474
1581
  }
1475
1582
  /**
1476
1583
  * draft.5 §5.0 INV-MSG / INV-TURN: may a terminal fold onto `turn`? A turn
@@ -1510,20 +1617,62 @@ export class Reducer {
1510
1617
  // §4 per-turn routing / INV-OWNER (draft.5): an omitted turnId
1511
1618
  // resolves to the sole OPEN turn, never to a closed one (through draft.4
1512
1619
  // this counted records, so a lone closed turn or a stub could be picked).
1513
- return this.#soleOpenRecord()?.turnId;
1620
+ return this.#soleOpenTurn();
1514
1621
  }
1515
- /** The sole OPEN turn record (no `outcome` yet), or undefined when none or several are open. */
1516
- #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() {
1517
1628
  let found;
1518
- for (const t of this.#turns.values()) {
1519
- if (t.outcome !== undefined)
1629
+ for (const turnId of new Set([...this.#seenOpened.keys(), ...this.#turns.keys()])) {
1630
+ if (this.#isClosedTurn(turnId))
1520
1631
  continue;
1521
1632
  if (found !== undefined)
1522
1633
  return undefined;
1523
- found = t;
1634
+ found = turnId;
1524
1635
  }
1525
1636
  return found;
1526
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
+ }
1527
1676
  /**
1528
1677
  * Where a record event lands (draft.5 INV-OWNER). A named turn with a
1529
1678
  * record lands on it; one whose thread is known gets a new record on that
@@ -1532,12 +1681,13 @@ export class Reducer {
1532
1681
  * event lands on the sole open turn's record, else its owner is unresolvable
1533
1682
  * and the fold parks.
1534
1683
  */
1535
- #landingRecord(turnId) {
1684
+ #landingRecord(turnId, displayRequired = false) {
1536
1685
  if (turnId === undefined) {
1537
- const sole = this.#soleOpenRecord();
1538
- if (sole === undefined)
1686
+ turnId = this.#soleOpenTurn();
1687
+ if (turnId === undefined) {
1539
1688
  this.#resync = true;
1540
- return sole;
1689
+ return undefined;
1690
+ }
1541
1691
  }
1542
1692
  const existing = this.#turns.get(turnId);
1543
1693
  if (existing !== undefined)
@@ -1546,17 +1696,27 @@ export class Reducer {
1546
1696
  if (threadId !== undefined)
1547
1697
  return this.#seenTurnRecord(turnId);
1548
1698
  let held = this.#held.get(turnId);
1549
- 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) {
1550
1704
  this.#resync = true; // degrade loudly past the bound
1551
1705
  return undefined;
1552
1706
  }
1553
1707
  if (held === undefined) {
1554
1708
  // threadId is set on adoption; a held record is never emitted.
1555
- held = { record: { turnId, threadId: "" }, landings: 0 };
1709
+ held = { record: { turnId, threadId: "" }, landings: 0, dr: 0 };
1556
1710
  this.#held.set(turnId, held);
1557
1711
  }
1558
- held.landings++;
1559
- this.#heldLandings++;
1712
+ if (displayRequired) {
1713
+ held.dr++;
1714
+ this.#heldDrLandings++;
1715
+ }
1716
+ else {
1717
+ held.landings++;
1718
+ this.#heldLandings++;
1719
+ }
1560
1720
  return held.record;
1561
1721
  }
1562
1722
  /**
@@ -1569,7 +1729,9 @@ export class Reducer {
1569
1729
  if (held === undefined)
1570
1730
  return undefined;
1571
1731
  this.#held.delete(turnId);
1732
+ this.#heldNested.delete(turnId);
1572
1733
  this.#heldLandings -= held.landings;
1734
+ this.#heldDrLandings -= held.dr;
1573
1735
  const { turnId: _turnId, threadId: _placeholder, ...landings } = held.record;
1574
1736
  const record = {
1575
1737
  turnId,
@@ -1581,11 +1743,11 @@ export class Reducer {
1581
1743
  return record;
1582
1744
  }
1583
1745
  /**
1584
- * 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,
1585
1747
  * else one created on the thread the fold saw the turn opened on. With no
1586
1748
  * thread known it returns undefined and the terminal folds onto no record.
1587
1749
  * No other turn's thread is borrowed (that could adopt a subagent's parent
1588
- * 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
1589
1751
  * turnId.
1590
1752
  */
1591
1753
  #seenTurnRecord(turnId) {
@@ -1593,8 +1755,10 @@ export class Reducer {
1593
1755
  if (existing !== undefined)
1594
1756
  return existing;
1595
1757
  const threadId = this.#seenOpened.get(turnId);
1596
- if (threadId === undefined)
1597
- 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
+ }
1598
1762
  const adopted = this.#adoptHeld(turnId, threadId);
1599
1763
  if (adopted !== undefined)
1600
1764
  return adopted;
@@ -1636,7 +1800,7 @@ export class Reducer {
1636
1800
  }
1637
1801
  /**
1638
1802
  * Batch fold. Returns the folded result AND the resync signal — a parked fold
1639
- * 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
1640
1804
  * expose its resync condition to the caller").
1641
1805
  */
1642
1806
  export function reduce(events) {