@silverprotocol/core 0.7.2 → 0.8.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.
package/dist/reduce.js CHANGED
@@ -76,6 +76,15 @@ function partKey(turnId, candidateIndex) {
76
76
  function isClosedEvent(ev) {
77
77
  return !ev.type.startsWith("ext.");
78
78
  }
79
+ /**
80
+ * Implementation bound on held landings (CB-7; cto's note, not normative). No
81
+ * reference producer emits a record event before its turn's opener, so a
82
+ * conformant stream holds nothing; the bound only stops a hostile or broken
83
+ * stream from growing state result() never shows. Past either cap the landing
84
+ * is not held and the fold parks (needsResync): the loud degradation.
85
+ */
86
+ const HELD_TURNS_CAP = 64;
87
+ const HELD_LANDINGS_CAP = 1024;
79
88
  export class Reducer {
80
89
  // ── keyed accumulators ──────────────────────────────────────────────────────
81
90
  // Messages, keyed by message id (insertion-ordered).
@@ -93,16 +102,11 @@ export class Reducer {
93
102
  #openMsg = new Map();
94
103
  // Message ids sealed by message.end.
95
104
  #sealed = new Set();
96
- // Resolved turnIds closed by turn.done/turn.error/turn.abort (INV-MSG: no
97
- // message of a closed turn — sealed or not, existing or not-yet-created —
98
- // is ever a valid attach/adoption target).
99
- #closedTurns = new Set();
100
105
  // turnIds legitimately opened via turn.start / subagent.start (or restored
101
106
  // by a messages.snapshot's turns?) — Task 8c leg 3 (guuey capstone finding
102
- // B). Distinguishes "a real turn genuinely exists" from "ensureTurn() would
103
- // happily fabricate a stub for this key" so the tool.done adoption CREATE
104
- // path can degrade loudly (resync) instead of silently minting a phantom
105
- // turn for a key that was never actually opened.
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.
106
110
  #openedTurns = new Set();
107
111
  // D9 (draft.4 §5.0 INV-OWNER; bar wf_08cf78ac-c30, A tightened): every
108
112
  // turnId the fold has seen opened — by turn.start, by subagent.start, or by a
@@ -114,6 +118,22 @@ export class Reducer {
114
118
  // #openedTurns (tool.done adoption) and never rebuilt from #turns, whose
115
119
  // records non-terminal arms may have minted as stubs.
116
120
  #seenOpened = new Map();
121
+ // CB-7 (draft.5 §5.0 INV-OWNER, "same-turn thread, hold"): the landings of
122
+ // the six record events (source, handoff, prompt.blocked, guardrail.result,
123
+ // display.required, agent.capabilities) for a turn whose thread the fold does
124
+ // not know yet. Each is a turn record result() never shows; it moves into
125
+ // #turns on the turn's thread once a turn.start, subagent.start, message.start
126
+ // or messages.snapshot makes that thread known (#adoptHeld). `landings` counts
127
+ // the events held on it, for the implementation bound below.
128
+ #held = new Map();
129
+ #heldLandings = 0;
130
+ // draft.5 §5.0 INV-MSG (the paused refresh): closed turns a turn.start has
131
+ // named since their last terminal folded. Only such a turn, closed paused,
132
+ // takes a turn.done{paused}; every terminal that folds removes its id. A
133
+ // messages.snapshot folds no terminal, so the set survives it (a refresh
134
+ // split by a reconnect still folds); whether the turn is closed paused is
135
+ // read from the records the snapshot leaves (CB-8).
136
+ #restartedSinceClose = new Set();
117
137
  // block/tool-call id → position in its owning message's content[], for REPLACE.
118
138
  #blockPos = new Map();
119
139
  // ── streaming scratch ──────────────────────────────────────────────────────
@@ -201,11 +221,15 @@ export class Reducer {
201
221
  switch (ev.type) {
202
222
  // ── TURN lifecycle ─────────────────────────────────────────────────────
203
223
  case "turn.start": {
224
+ // draft.5 INV-MSG: a turn.start naming a closed turn opens its paused refresh.
225
+ if (this.#isClosedTurn(ev.turnId))
226
+ this.#restartedSinceClose.add(ev.turnId);
204
227
  // Task 8c leg 3: a turn.start always counts as a legitimately opened turn.
205
228
  this.#openedTurns.add(ev.turnId);
206
229
  this.#seenOpened.set(ev.turnId, ev.threadId);
207
- // Idempotent: if the turn already exists, merge defined fields only.
208
- const existing = this.#turns.get(ev.turnId);
230
+ // Idempotent: if the turn already exists, merge defined fields only. A
231
+ // record held for this turn (CB-7) is adopted onto this thread first.
232
+ const existing = this.#turns.get(ev.turnId) ?? this.#adoptHeld(ev.turnId, ev.threadId);
209
233
  if (existing === undefined) {
210
234
  this.#turns.set(ev.turnId, {
211
235
  turnId: ev.turnId,
@@ -214,7 +238,9 @@ export class Reducer {
214
238
  });
215
239
  }
216
240
  else {
217
- // Merge — only overwrite with defined values (idempotent re-delivery).
241
+ // Merge (INV-TURN) — a turn.start gives the thread; other fields only
242
+ // overwrite with defined values (idempotent re-delivery).
243
+ existing.threadId = ev.threadId;
218
244
  if (ev.trigger !== undefined) {
219
245
  existing.trigger = ev.trigger;
220
246
  }
@@ -224,10 +250,18 @@ export class Reducer {
224
250
  // ── MESSAGE lifecycle ──────────────────────────────────────────────────
225
251
  case "message.start": {
226
252
  // rd-14 INV-MSG: a message.start for a turn that already closed parks.
227
- if (this.#closedTurns.has(this.#resolveTurnId(ev.turnId) ?? ev.turnId)) {
253
+ if (this.#isClosedTurn(this.#resolveTurnId(ev.turnId) ?? ev.turnId)) {
228
254
  this.#resync = true;
229
255
  break;
230
256
  }
257
+ // CB-7 (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
259
+ // the first one folded), and a record held for the turn is adopted onto it.
260
+ if (this.#seenOpened.get(ev.turnId) === undefined)
261
+ this.#seenOpened.set(ev.turnId, ev.threadId);
262
+ const knownThread = this.#seenOpened.get(ev.turnId);
263
+ if (knownThread !== undefined)
264
+ this.#adoptHeld(ev.turnId, knownThread);
231
265
  const msg = {
232
266
  id: ev.id,
233
267
  role: ev.role,
@@ -289,18 +323,22 @@ export class Reducer {
289
323
  // Every entity in a fold shares one root threadId (SPEC §1.2), so
290
324
  // fall back to any ALREADY-OPENED real turn's threadId instead of
291
325
  // adopting the unresolvable label as this subagent's own threadId.
292
- // A "real" turn is identified by threadId !== turnId — a defensive
293
- // ensureTurn() stub uses its own turnId as a threadId placeholder
294
- // and must never be picked here. `ev.parentTurnId` remains the last
295
- // resort when no real turn exists yet.
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 (CB-7), and the check stays as a guard.
329
+ // `ev.parentTurnId` remains the last resort when no real turn exists yet.
296
330
  const realTurn = [...this.#turns.values()].find((t) => t.threadId !== t.turnId);
297
331
  threadId = realTurn?.threadId ?? ev.parentTurnId;
298
332
  }
299
- this.#turns.set(ev.turnId, {
300
- turnId: ev.turnId,
301
- parentTurnId: ev.parentTurnId,
302
- threadId,
303
- });
333
+ // A record held for this nested turn (CB-7) takes the thread and the
334
+ // parentTurnId here; otherwise a new record opens.
335
+ if (this.#adoptHeld(ev.turnId, threadId, ev.parentTurnId) === undefined) {
336
+ this.#turns.set(ev.turnId, {
337
+ turnId: ev.turnId,
338
+ parentTurnId: ev.parentTurnId,
339
+ threadId,
340
+ });
341
+ }
304
342
  this.#seenOpened.set(ev.turnId, threadId);
305
343
  break;
306
344
  }
@@ -601,7 +639,7 @@ export class Reducer {
601
639
  // #blockPos → messageId → message.turnId chain and park instead of mutating
602
640
  // (mirrors the adoption path's closed-turn/sealed guard above).
603
641
  const ownerTurnKey = msg.turnId ?? "unknown-turn";
604
- if (this.#sealed.has(msg.id) || this.#closedTurns.has(ownerTurnKey)) {
642
+ if (this.#sealed.has(msg.id) || this.#isClosedTurn(ownerTurnKey)) {
605
643
  this.#resync = true;
606
644
  break;
607
645
  }
@@ -658,20 +696,20 @@ export class Reducer {
658
696
  // INV-MSG enforcement: a sealed message, or ANY message of a closed
659
697
  // turn — including one that would need to be freshly created — is
660
698
  // never a valid adoption target. Resolve the turn this adoption
661
- // would land in (the existing message's own turnId, or the turnId
662
- // ensureTurn() would assign a new message) BEFORE either sub-path
663
- // runs, and park instead of silently attaching/creating past the
664
- // seal or the turn's binding window.
699
+ // would land in (the existing message's own turnId, or the turn a
700
+ // new message would take) BEFORE either sub-path runs, and park
701
+ // 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.
665
704
  const targetTurnKey = existing !== undefined
666
705
  ? (existing.turnId ?? "unknown-turn")
667
706
  : (this.#resolveTurnId(ev.turnId) ?? ev.turnId ?? "unknown-turn");
668
707
  // Task 8c leg 3 (guuey capstone finding B): a turn that was never
669
708
  // legitimately opened (turn.start / subagent.start / a snapshot's
670
709
  // turns?) is just as invalid an adoption target as a sealed
671
- // message or a closed turn — without this, ensureTurn() below
672
- // would happily fabricate a phantom turn stub instead of parking.
710
+ // message or a closed turn: park rather than create a message for it.
673
711
  if (this.#sealed.has(ev.messageId) ||
674
- this.#closedTurns.has(targetTurnKey) ||
712
+ this.#isClosedTurn(targetTurnKey) ||
675
713
  !this.#openedTurns.has(targetTurnKey)) {
676
714
  this.#resync = true;
677
715
  break;
@@ -680,7 +718,13 @@ export class Reducer {
680
718
  msg = existing;
681
719
  }
682
720
  else {
683
- const turn = this.ensureTurn(ev.turnId);
721
+ // An opened turn always has its record (turn.start / subagent.start /
722
+ // a snapshot's turns); a held record is never an adoption target.
723
+ const turn = this.#turns.get(targetTurnKey);
724
+ if (turn === undefined) {
725
+ this.#resync = true;
726
+ break;
727
+ }
684
728
  // Create new tool-result message with the adopted messageId.
685
729
  msg = {
686
730
  id: ev.messageId,
@@ -787,6 +831,10 @@ export class Reducer {
787
831
  const turn = this.#seenTurnRecord(ev.turnId);
788
832
  if (turn === undefined)
789
833
  break;
834
+ // draft.5 INV-MSG: a turn.done for a closed turn parks, writing nothing,
835
+ // unless it is the paused refresh.
836
+ if (!this.#terminalMayFold(turn, ev.outcome.type === "paused"))
837
+ break;
790
838
  turn.finishReason = ev.finishReason;
791
839
  // draft.4: the native finish value, verbatim, beside its mapped reason.
792
840
  if (ev.finishReasonRaw !== undefined)
@@ -803,8 +851,9 @@ export class Reducer {
803
851
  if (ev.outcome.type === "paused") {
804
852
  turn.asks = ev.outcome.asks;
805
853
  }
806
- // messageMetadata: REPLACE-merge onto the message named by turn.done.messageId
807
- // when present, else the open message of this turn (audit M20).
854
+ // messageMetadata: REPLACE the whole messageMetadata bag of the message named
855
+ // 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.
808
857
  // (Read happens BEFORE the binding window closes below.)
809
858
  if (ev.messageMetadata !== undefined) {
810
859
  const msg = ev.messageId !== undefined ? this.#messages.get(ev.messageId) : this.openMessage(ev.turnId, 0);
@@ -819,48 +868,68 @@ export class Reducer {
819
868
  }
820
869
  case "turn.error": {
821
870
  // Non-folding into content; sets outcome={type:"error",...} on the turn record.
822
- // D9, as turn.done; only for a NAMED turnId (a turnId-less terminal keeps
823
- // the INV-OWNER backfill below).
871
+ // D9, as turn.done, for a NAMED turnId. A turnId-less terminal resolves to
872
+ // the sole OPEN turn, never a closed one; with none or several open its
873
+ // owner is unresolvable and the fold parks (INV-OWNER, draft.5 CB-7).
824
874
  if (ev.turnId !== undefined && !this.#seenOpened.has(ev.turnId))
825
875
  break;
826
- const turn = ev.turnId !== undefined ? this.#seenTurnRecord(ev.turnId) : this.ensureTurn(ev.turnId);
827
- if (turn === undefined)
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;
880
+ break;
881
+ }
882
+ // draft.5 INV-MSG: a turn.error for a closed turn parks, writing nothing.
883
+ if (!this.#terminalMayFold(turn, false))
828
884
  break;
885
+ // draft.5: `code` and `retriable` are recorded when turn.error carries them.
886
+ // `retriable` is the producer's judgement; an absent one stays absent
887
+ // (unstated, never coerced to false). A non-terminal `error` never folds it.
829
888
  turn.outcome = {
830
889
  type: "error",
831
890
  message: ev.message,
832
891
  ...(ev.code !== undefined ? { code: ev.code } : {}),
892
+ ...(ev.retriable !== undefined ? { retriable: ev.retriable } : {}),
833
893
  };
834
894
  // Usage is recorded VERBATIM — NO de-cumulation (mirrors turn.done; normalizer duty).
835
895
  if (ev.usage !== undefined)
836
896
  turn.usage = ev.usage;
837
897
  // INV-MSG binding window: no blocks attach to a closed turn's messages.
838
- this.#closeTurnWindow(ev.turnId);
839
- this.#evictTurnScratch(ev.turnId);
898
+ this.#closeTurnWindow(turn.turnId);
899
+ this.#evictTurnScratch(turn.turnId);
840
900
  break;
841
901
  }
842
902
  case "turn.abort": {
843
903
  // Non-folding into content; sets a dedicated aborted outcome on the turn record
844
904
  // (symmetric with turn.error). taskState is verbatim-A2A only and is NEVER
845
905
  // reducer-invented (audit M29) — it stays whatever a prior turn.done left it as.
846
- // D9, as turn.done; only for a NAMED turnId (a turnId-less terminal keeps
847
- // the INV-OWNER backfill below).
906
+ // D9, as turn.done, for a NAMED turnId. A turnId-less terminal resolves to
907
+ // the sole OPEN turn, never a closed one; with none or several open its
908
+ // owner is unresolvable and the fold parks (INV-OWNER, draft.5 CB-7).
848
909
  if (ev.turnId !== undefined && !this.#seenOpened.has(ev.turnId))
849
910
  break;
850
- const turn = ev.turnId !== undefined ? this.#seenTurnRecord(ev.turnId) : this.ensureTurn(ev.turnId);
851
- if (turn === undefined)
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;
915
+ break;
916
+ }
917
+ // draft.5 INV-MSG: a turn.abort for a closed turn parks, writing nothing.
918
+ if (!this.#terminalMayFold(turn, false))
852
919
  break;
853
920
  turn.outcome = { type: "aborted", ...(ev.reason !== undefined ? { reason: ev.reason } : {}) };
854
921
  // INV-MSG binding window: no blocks attach to a closed turn's messages.
855
- this.#closeTurnWindow(ev.turnId);
856
- this.#evictTurnScratch(ev.turnId);
922
+ this.#closeTurnWindow(turn.turnId);
923
+ this.#evictTurnScratch(turn.turnId);
857
924
  break;
858
925
  }
859
926
  case "source": {
860
927
  // Append sourceId to the turn's sourceIds[] in order (preserve groundingChunks order),
861
928
  // AND land the FULL record (payload/chunkIndex/providerMetadata) on sources[] so
862
929
  // citations can resolve post-fold (audit M23) — sourceIds[] stays as the derived index.
863
- const turn = this.ensureTurn(ev.turnId);
930
+ const turn = this.#landingRecord(ev.turnId);
931
+ if (turn === undefined)
932
+ break;
864
933
  if (turn.sourceIds === undefined) {
865
934
  turn.sourceIds = [];
866
935
  }
@@ -878,7 +947,9 @@ export class Reducer {
878
947
  }
879
948
  case "handoff": {
880
949
  // Push an AgHandoffRecord onto the turn's handoffs[].
881
- const turn = this.ensureTurn(ev.turnId);
950
+ const turn = this.#landingRecord(ev.turnId);
951
+ if (turn === undefined)
952
+ break;
882
953
  if (turn.handoffs === undefined) {
883
954
  turn.handoffs = [];
884
955
  }
@@ -896,7 +967,9 @@ export class Reducer {
896
967
  // land the dedicated promptBlocked record {reason, safety?} so the REQUIRED reason
897
968
  // and the blockedness itself survive the fold — a bare-reason block used to fold to
898
969
  // ZERO trace (audit M28).
899
- const turn = this.ensureTurn(ev.turnId);
970
+ const turn = this.#landingRecord(ev.turnId);
971
+ if (turn === undefined)
972
+ break;
900
973
  if (ev.safety !== undefined) {
901
974
  if (turn.safety === undefined) {
902
975
  turn.safety = [...ev.safety];
@@ -913,7 +986,9 @@ export class Reducer {
913
986
  }
914
987
  case "guardrail.result": {
915
988
  // Push a guardrail evaluation record onto the turn's guardrails[].
916
- const turn = this.ensureTurn(ev.turnId);
989
+ const turn = this.#landingRecord(ev.turnId);
990
+ if (turn === undefined)
991
+ break;
917
992
  if (turn.guardrails === undefined) {
918
993
  turn.guardrails = [];
919
994
  }
@@ -929,7 +1004,9 @@ export class Reducer {
929
1004
  }
930
1005
  case "display.required": {
931
1006
  // MUST NOT drop (ToS). Push {provider, html} onto turn's displayRequired[].
932
- const turn = this.ensureTurn(ev.turnId);
1007
+ const turn = this.#landingRecord(ev.turnId);
1008
+ if (turn === undefined)
1009
+ break;
933
1010
  if (turn.displayRequired === undefined) {
934
1011
  turn.displayRequired = [];
935
1012
  }
@@ -940,7 +1017,9 @@ export class Reducer {
940
1017
  case "agent.capabilities": {
941
1018
  // SPEC §5: "Record the agent's AgCapabilities on the turn (first-turn negotiation)."
942
1019
  // Fold ev.capabilities onto the AgTurnRecord for the owning turn.
943
- const turn = this.ensureTurn(ev.turnId);
1020
+ const turn = this.#landingRecord(ev.turnId);
1021
+ if (turn === undefined)
1022
+ break;
944
1023
  turn.capabilities = ev.capabilities;
945
1024
  break;
946
1025
  }
@@ -1129,6 +1208,9 @@ export class Reducer {
1129
1208
  // CONDITIONALLY replace #turns (only if turns? present in event).
1130
1209
  if (ev.turns !== undefined) {
1131
1210
  this.#turns = new Map(structuredClone(ev.turns).map((t) => [t.turnId, t]));
1211
+ // The snapshot's turns are authoritative: a landing held before it goes too.
1212
+ this.#held = new Map();
1213
+ this.#heldLandings = 0;
1132
1214
  }
1133
1215
  // CONDITIONALLY replace #artifacts (only if artifacts? present in event).
1134
1216
  if (ev.artifacts !== undefined) {
@@ -1148,17 +1230,24 @@ export class Reducer {
1148
1230
  .map((rec) => [`${rec.scope}${rec.key ?? ""}`, rec]);
1149
1231
  this.#memory = new Map([...nonThread, ...snapshotThread]);
1150
1232
  }
1151
- // Clear ALL transient scratch.
1233
+ // Clear the transient scratch (draft.5 §5 messages.snapshot row): per-
1234
+ // toolCallId arg scratch, reasoning signature scratch, open-message
1235
+ // pointers, message seals and block positions; open/un-sealed blocks go
1236
+ // with the #messages REPLACE above. INV-BLOCK's invoke-scoped id sets are
1237
+ // NOT cleared (only a 0-restart resets them). Turn closure is not
1238
+ // scratch: it follows the turn records this arm leaves in the fold
1239
+ // (INV-MSG, #isClosedTurn), so carried turns bring their outcomes and a
1240
+ // turns-omitting snapshot keeps every record, and with it every closure.
1152
1241
  this.#toolArgs = new Map();
1153
1242
  this.#opaque = new Map();
1154
1243
  this.#openMsg = new Map();
1155
1244
  this.#sealed = new Set();
1156
- this.#closedTurns = new Set();
1157
1245
  this.#blockPos = new Map();
1246
+ // #restartedSinceClose is NOT cleared: a snapshot folds no terminal (draft.5 INV-MSG).
1158
1247
  // Task 8c leg 3: a snapshot-restored turn counts as opened (guuey
1159
1248
  // capstone finding B) — reseed #openedTurns from the replaced turns in
1160
- // lockstep with #turns above; no turns replaced ⇒ no fresh legitimacy
1161
- // to assert (mirrors the unconditional #closedTurns reset above).
1249
+ // lockstep with #turns above; a turns-omitting snapshot re-seeds it from
1250
+ // the records it keeps.
1162
1251
  this.#openedTurns = ev.turns !== undefined
1163
1252
  ? new Set(ev.turns.map((t) => t.turnId))
1164
1253
  : new Set(this.#turns.keys());
@@ -1182,6 +1271,14 @@ export class Reducer {
1182
1271
  }
1183
1272
  for (const [turnId, threadId] of messageThread)
1184
1273
  this.#seenOpened.set(turnId, threadId);
1274
+ // CB-7: a held record whose thread this snapshot taught is adopted onto
1275
+ // it. #openedTurns was seeded above from records with a known thread
1276
+ // only, so an adopted record is not an adoption target by this snapshot.
1277
+ for (const turnId of [...this.#held.keys()]) {
1278
+ const threadId = this.#seenOpened.get(turnId);
1279
+ if (threadId !== undefined)
1280
+ this.#adoptHeld(turnId, threadId);
1281
+ }
1185
1282
  // Un-park.
1186
1283
  this.#resync = false;
1187
1284
  break;
@@ -1296,12 +1393,15 @@ export class Reducer {
1296
1393
  return undefined;
1297
1394
  return this.#messages.get(msgId);
1298
1395
  }
1299
- /** Delete every open-message pointer belonging to a closed turn (INV-MSG). */
1396
+ /**
1397
+ * Delete every open-message pointer belonging to a closed turn (INV-MSG).
1398
+ * Closure itself is the record's `outcome`, set by the terminal arm before
1399
+ * this runs (#isClosedTurn); this only evicts the turn's open-message pointers.
1400
+ */
1300
1401
  #closeTurnWindow(turnId) {
1301
1402
  const resolved = this.#resolveTurnId(turnId);
1302
1403
  if (resolved === undefined)
1303
1404
  return;
1304
- this.#closedTurns.add(resolved);
1305
1405
  for (const [pk] of this.#openMsg) {
1306
1406
  if (pk.startsWith(`${resolved} `))
1307
1407
  this.#openMsg.delete(pk);
@@ -1336,8 +1436,43 @@ export class Reducer {
1336
1436
  #isClosedTarget(messageId) {
1337
1437
  if (this.#sealed.has(messageId))
1338
1438
  return true;
1339
- const turnId = this.#messages.get(messageId)?.turnId;
1340
- return turnId !== undefined && this.#closedTurns.has(turnId);
1439
+ return this.#isClosedTurn(this.#messages.get(messageId)?.turnId);
1440
+ }
1441
+ /**
1442
+ * INV-MSG (draft.5, CB-8 A′: closure follows the records): a turn is closed
1443
+ * while the fold holds a turn record for it that carries an `outcome`. Only a
1444
+ * folded turn.done / turn.error / turn.abort sets one, so a terminal that
1445
+ * folds onto no record closes nothing; a messages.snapshot changes closure
1446
+ * only through the records its §5 per-container rule leaves in the fold. No
1447
+ * message of a closed turn (sealed or not, existing or not yet created) is a
1448
+ * valid attach or adoption target. `key` is a resolved turnId, or the
1449
+ * "unknown-turn" key of a message with no turnId, which names no record.
1450
+ */
1451
+ #isClosedTurn(key) {
1452
+ return key !== undefined && this.#turns.get(key)?.outcome !== undefined;
1453
+ }
1454
+ /**
1455
+ * draft.5 §5.0 INV-MSG / INV-TURN: may a terminal fold onto `turn`? A turn
1456
+ * whose record carries an outcome is closed (#isClosedTurn), and a
1457
+ * turn.done, turn.error or turn.abort for it is a reduce()-error: the fold
1458
+ * parks and nothing is written, whatever the outcome and whether or not it
1459
+ * repeats the recorded one. The one exception is the paused refresh: a
1460
+ * turn.done{paused} (`pausedDone`) for a turn whose recorded outcome is
1461
+ * paused and which a turn.start has named since its last terminal folded. It
1462
+ * folds through the arm's ordinary writes (outcome and asks replace; a field
1463
+ * it omits keeps its recorded value), and the turn stays closed. A terminal
1464
+ * that folds consumes that turn.start.
1465
+ */
1466
+ #terminalMayFold(turn, pausedDone) {
1467
+ if (turn.outcome !== undefined) {
1468
+ const refresh = pausedDone && turn.outcome.type === "paused" && this.#restartedSinceClose.has(turn.turnId);
1469
+ if (!refresh) {
1470
+ this.#resync = true;
1471
+ return false;
1472
+ }
1473
+ }
1474
+ this.#restartedSinceClose.delete(turn.turnId);
1475
+ return true;
1341
1476
  }
1342
1477
  /** rd-14 INV-BLOCK: a block-creating id seen twice in one invoke parks; else records it. */
1343
1478
  #dupBlock(id) {
@@ -1351,29 +1486,79 @@ export class Reducer {
1351
1486
  #resolveTurnId(turnId) {
1352
1487
  if (turnId !== undefined)
1353
1488
  return turnId;
1354
- // Single-turn default: if exactly one turn exists, use it.
1355
- if (this.#turns.size === 1) {
1356
- // Map.keys() iterator — noUncheckedIndexedAccess-safe via for..of.
1357
- for (const key of this.#turns.keys()) {
1358
- return key;
1359
- }
1489
+ // §4 per-turn routing / INV-OWNER (draft.5, CB-7): an omitted turnId
1490
+ // resolves to the sole OPEN turn, never to a closed one (through draft.4
1491
+ // this counted records, so a lone closed turn or a stub could be picked).
1492
+ return this.#soleOpenRecord()?.turnId;
1493
+ }
1494
+ /** The sole OPEN turn record (no `outcome` yet), or undefined when none or several are open. */
1495
+ #soleOpenRecord() {
1496
+ let found;
1497
+ for (const t of this.#turns.values()) {
1498
+ if (t.outcome !== undefined)
1499
+ continue;
1500
+ if (found !== undefined)
1501
+ return undefined;
1502
+ found = t;
1360
1503
  }
1361
- return undefined;
1504
+ return found;
1362
1505
  }
1363
1506
  /**
1364
- * Defensive turn lookup: get an existing `AgTurnRecord` by turnId, or create a
1365
- * minimal stub if the record-on-turn event arrives before its `turn.start`.
1366
- *
1367
- * Record-on-turn events (turn.done, turn.error, turn.abort, source, handoff,
1368
- * prompt.blocked, guardrail.result, display.required) all carry `turnId` (optional
1369
- * in the base schema). When turnId is undefined, fall back to the sole open turn
1370
- * (single-turn-stream default). If still ambiguous, create a fallback record keyed
1371
- * on "unknown-turn" — the stub will be visible in turns[] but can be reconciled on
1372
- * a subsequent messages.snapshot resync.
1373
- *
1374
- * AgTurnRecord requires `threadId`; when creating a defensive stub we use the
1375
- * turnId itself as a placeholder (no threadId is available without turn.start).
1507
+ * Where a record event lands (CB-7, draft.5 INV-OWNER). A named turn with a
1508
+ * record lands on it; one whose thread is known gets a new record on that
1509
+ * thread; one whose thread is not known yet is held (a record result() omits),
1510
+ * or, past the implementation bound, parks the fold. A turnId-less record
1511
+ * event lands on the sole open turn's record, else its owner is unresolvable
1512
+ * and the fold parks.
1376
1513
  */
1514
+ #landingRecord(turnId) {
1515
+ if (turnId === undefined) {
1516
+ const sole = this.#soleOpenRecord();
1517
+ if (sole === undefined)
1518
+ this.#resync = true;
1519
+ return sole;
1520
+ }
1521
+ const existing = this.#turns.get(turnId);
1522
+ if (existing !== undefined)
1523
+ return existing;
1524
+ const threadId = this.#seenOpened.get(turnId);
1525
+ if (threadId !== undefined)
1526
+ return this.#seenTurnRecord(turnId);
1527
+ let held = this.#held.get(turnId);
1528
+ if ((held === undefined && this.#held.size >= HELD_TURNS_CAP) || this.#heldLandings >= HELD_LANDINGS_CAP) {
1529
+ this.#resync = true; // degrade loudly past the bound
1530
+ return undefined;
1531
+ }
1532
+ if (held === undefined) {
1533
+ // threadId is set on adoption; a held record is never emitted.
1534
+ held = { record: { turnId, threadId: "" }, landings: 0 };
1535
+ this.#held.set(turnId, held);
1536
+ }
1537
+ held.landings++;
1538
+ this.#heldLandings++;
1539
+ return held.record;
1540
+ }
1541
+ /**
1542
+ * Move the record held for `turnId` (CB-7) into #turns on the thread that is
1543
+ * now known, with `parentTurnId` when a subagent.start opened it. Returns the
1544
+ * adopted record, or undefined when nothing was held for the turn.
1545
+ */
1546
+ #adoptHeld(turnId, threadId, parentTurnId) {
1547
+ const held = this.#held.get(turnId);
1548
+ if (held === undefined)
1549
+ return undefined;
1550
+ this.#held.delete(turnId);
1551
+ this.#heldLandings -= held.landings;
1552
+ const { turnId: _turnId, threadId: _placeholder, ...landings } = held.record;
1553
+ const record = {
1554
+ turnId,
1555
+ ...(parentTurnId !== undefined ? { parentTurnId } : {}),
1556
+ threadId,
1557
+ ...landings,
1558
+ };
1559
+ this.#turns.set(turnId, record);
1560
+ return record;
1561
+ }
1377
1562
  /**
1378
1563
  * D9: the record a terminal for a SEEN turn folds onto — the existing one,
1379
1564
  * else one created on the thread the fold saw the turn opened on. With no
@@ -1389,21 +1574,13 @@ export class Reducer {
1389
1574
  const threadId = this.#seenOpened.get(turnId);
1390
1575
  if (threadId === undefined)
1391
1576
  return undefined;
1577
+ const adopted = this.#adoptHeld(turnId, threadId);
1578
+ if (adopted !== undefined)
1579
+ return adopted;
1392
1580
  const record = { turnId, threadId };
1393
1581
  this.#turns.set(turnId, record);
1394
1582
  return record;
1395
1583
  }
1396
- ensureTurn(turnId) {
1397
- const resolved = this.#resolveTurnId(turnId) ?? turnId;
1398
- const key = resolved ?? "unknown-turn";
1399
- const existing = this.#turns.get(key);
1400
- if (existing !== undefined)
1401
- return existing;
1402
- // Defensive stub: threadId is required on AgTurnRecord; use key as placeholder.
1403
- const stub = { turnId: key, threadId: key };
1404
- this.#turns.set(key, stub);
1405
- return stub;
1406
- }
1407
1584
  /**
1408
1585
  * Materialize the current fold state as a DEFENSIVE DEEP COPY.
1409
1586
  * Each call returns fresh arrays and objects — holding a snapshot