@silverprotocol/core 0.1.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 ADDED
@@ -0,0 +1,1209 @@
1
+ import { REMOVE_ALL } from "./agjson.js";
2
+ import { applyPatch } from "./json-patch.js";
3
+ // ─────────────────────────────────────────────────────────────────────────────
4
+ // Reducer — the normative event→state fold (spec §5).
5
+ //
6
+ // R0 scaffold: all scratch initialized; push() = switch with default no-op;
7
+ // result() materializes via structuredClone (aliasing-safe).
8
+ //
9
+ // R1: lifecycle handlers (turn.start / message.start / message.end /
10
+ // subagent.start / subagent.done / step.start / step.done) +
11
+ // (turnId, candidateIndex) partition helper.
12
+ //
13
+ // R2: text + reasoning blocks (APPEND deltas, REPLACE opaque, seeded required
14
+ // fields, byte-order via #blockPos).
15
+ // R4: content.block (APPEND/REPLACE-in-place by id; transient SKIP) +
16
+ // message.metadata (REPLACE-by-key shallow merge).
17
+ // ─────────────────────────────────────────────────────────────────────────────
18
+ // ── providerMetadata merge helpers ────────────────────────────────────────────
19
+ /**
20
+ * Merge `incoming` providerMetadata into `existing` (REPLACE-by-key).
21
+ * Returns the merged record, or `incoming` if `existing` is undefined.
22
+ * Returns `undefined` if both are undefined.
23
+ */
24
+ function mergeProviderMeta(existing, incoming) {
25
+ if (incoming === undefined)
26
+ return existing;
27
+ if (existing === undefined)
28
+ return incoming;
29
+ return { ...existing, ...incoming };
30
+ }
31
+ /**
32
+ * Build the partition key for the open-message map.
33
+ *
34
+ * Spec §5: the partition key is `(turnId, candidateIndex)` — absent
35
+ * `candidateIndex` defaults to 0 (back-compat anchor).
36
+ *
37
+ * R2/R3/R4 reuse this helper via `openMessage()`.
38
+ *
39
+ * @param turnId The owning turn's id.
40
+ * @param candidateIndex The candidate index (absent → 0).
41
+ */
42
+ function partKey(turnId, candidateIndex) {
43
+ return `${turnId} ${candidateIndex}`;
44
+ }
45
+ /**
46
+ * Narrow `AgEvent` to `AgClosedEventType` by ruling out the open `AgExtEvent`
47
+ * arm (whose `type` always matches `/^ext\.[^.]+\..+$/`).
48
+ *
49
+ * `AgExtEvent` uses `.catchall(JsonValue)`, which adds an index signature that
50
+ * widens every field access on the `AgEvent` union. This type guard excludes the
51
+ * ext arm so the switch inside `push()` sees the properly-narrowed closed-event
52
+ * type and avoids spurious `string | JsonValue` field types.
53
+ */
54
+ function isClosedEvent(ev) {
55
+ return !ev.type.startsWith("ext.");
56
+ }
57
+ export class Reducer {
58
+ // ── keyed accumulators ──────────────────────────────────────────────────────
59
+ // Messages, keyed by message id (insertion-ordered).
60
+ #messages = new Map();
61
+ // Turn records, keyed by turnId.
62
+ #turns = new Map();
63
+ // Artifacts, keyed by artifactId.
64
+ #artifacts = new Map();
65
+ // Memory records, keyed by `${scope}${key ?? ""}`.
66
+ #memory = new Map();
67
+ // Shared-state working copy (opaque; §11.1).
68
+ #state = undefined;
69
+ // ── open-message tracking ──────────────────────────────────────────────────
70
+ // Partition key `${turnId} ${candidateIndex}` → open message id.
71
+ #openMsg = new Map();
72
+ // Message ids sealed by message.end.
73
+ #sealed = new Set();
74
+ // Resolved turnIds closed by turn.done/turn.error/turn.abort (INV-MSG: no
75
+ // message of a closed turn — sealed or not, existing or not-yet-created —
76
+ // is ever a valid attach/adoption target).
77
+ #closedTurns = new Set();
78
+ // turnIds legitimately opened via turn.start / subagent.start (or restored
79
+ // by a messages.snapshot's turns?) — Task 8c leg 3 (guuey capstone finding
80
+ // B). Distinguishes "a real turn genuinely exists" from "ensureTurn() would
81
+ // happily fabricate a stub for this key" so the tool.done adoption CREATE
82
+ // path can degrade loudly (resync) instead of silently minting a phantom
83
+ // turn for a key that was never actually opened.
84
+ #openedTurns = new Set();
85
+ // block/tool-call id → position in its owning message's content[], for REPLACE.
86
+ #blockPos = new Map();
87
+ // ── streaming scratch ──────────────────────────────────────────────────────
88
+ // toolCallId → raw partial-JSON scratch.
89
+ #toolArgs = new Map();
90
+ // reasoning id → signature scratch.
91
+ #opaque = new Map();
92
+ // ── gap detection ──────────────────────────────────────────────────────────
93
+ #lastSeq = -1;
94
+ #resync = false;
95
+ /**
96
+ * Feed a single normalized AgEvent into the fold.
97
+ * R1: lifecycle handlers (turn/message/subagent/step).
98
+ * R2: text + reasoning blocks (APPEND deltas, REPLACE opaque).
99
+ * R3–R10 fill remaining content types.
100
+ */
101
+ push(ev) {
102
+ // ── Seq-gap detection (R9) ────────────────────────────────────────────────
103
+ // Seq accounting is UNIVERSAL (INV-SEQ: "gap-free ordinal" over the whole
104
+ // per-invoke stream) — EVERY well-formed event with a numeric seq advances
105
+ // the gap check, INCLUDING events the reducer does not fold (ext.* and
106
+ // other live-only events). This must run BEFORE the isClosedEvent skip
107
+ // below: an ext/live-only event between two closed events still occupies a
108
+ // seq slot, so skipping it here would let the NEXT closed event look like
109
+ // a forward gap that never happened (found by M46 review — the false-park
110
+ // this fixes voided every fold with an ext emission between closed events).
111
+ // After the first event (#lastSeq >= 0), a forward gap sets #resync (park)
112
+ // — including when an ext/live-only event is the one revealing the gap.
113
+ if (this.#lastSeq >= 0 && ev.seq > this.#lastSeq + 1) {
114
+ this.#resync = true;
115
+ }
116
+ // ── Park-gate (R9) ───────────────────────────────────────────────────────
117
+ // While parked, process ONLY the two snapshot kinds; all else is ignored.
118
+ // Both snapshots REPLACE + clear #resync inside their handlers.
119
+ if (this.#resync) {
120
+ if (ev.type === "messages.snapshot" || ev.type === "state.snapshot") {
121
+ // Fall through to the switch — these handlers clear #resync.
122
+ }
123
+ else {
124
+ // Parked: ignore. Do NOT update #lastSeq for ignored events.
125
+ return;
126
+ }
127
+ }
128
+ // Update #lastSeq for every processed event (including snapshots and
129
+ // non-folding ext/live-only events — seq accounting is universal, see above).
130
+ this.#lastSeq = ev.seq;
131
+ // Ext events (`ext.<vendor>.<key>`) are live-only / non-folding (§4/§12).
132
+ // Rule them out HERE — after seq accounting above, so an ext event still
133
+ // advances the gap check/#lastSeq — so the switch below sees the narrowed
134
+ // AgClosedEventType and avoids the AgExtEvent.catchall(JsonValue)
135
+ // index-signature field widening.
136
+ if (!isClosedEvent(ev))
137
+ return;
138
+ switch (ev.type) {
139
+ // ── TURN lifecycle ─────────────────────────────────────────────────────
140
+ case "turn.start": {
141
+ // Task 8c leg 3: a turn.start always counts as a legitimately opened turn.
142
+ this.#openedTurns.add(ev.turnId);
143
+ // Idempotent: if the turn already exists, merge defined fields only.
144
+ const existing = this.#turns.get(ev.turnId);
145
+ if (existing === undefined) {
146
+ this.#turns.set(ev.turnId, {
147
+ turnId: ev.turnId,
148
+ threadId: ev.threadId,
149
+ ...(ev.trigger !== undefined ? { trigger: ev.trigger } : {}),
150
+ });
151
+ }
152
+ else {
153
+ // Merge — only overwrite with defined values (idempotent re-delivery).
154
+ if (ev.trigger !== undefined) {
155
+ existing.trigger = ev.trigger;
156
+ }
157
+ }
158
+ break;
159
+ }
160
+ // ── MESSAGE lifecycle ──────────────────────────────────────────────────
161
+ case "message.start": {
162
+ const msg = {
163
+ id: ev.id,
164
+ role: ev.role,
165
+ content: [],
166
+ turnId: ev.turnId,
167
+ threadId: ev.threadId,
168
+ ...(ev.candidateIndex !== undefined ? { candidateIndex: ev.candidateIndex } : {}),
169
+ ...(ev.agentId !== undefined ? { agentId: ev.agentId } : {}),
170
+ ...(ev.agentName !== undefined ? { agentName: ev.agentName } : {}),
171
+ ...(ev.agentRole !== undefined ? { agentRole: ev.agentRole } : {}),
172
+ ...(ev.model !== undefined ? { model: ev.model } : {}),
173
+ ...(ev.extensions !== undefined ? { extensions: ev.extensions } : {}),
174
+ };
175
+ this.#messages.set(ev.id, msg);
176
+ // Register partition pointer: (turnId, candidateIndex ?? 0) → message id.
177
+ this.#openMsg.set(partKey(ev.turnId, ev.candidateIndex ?? 0), ev.id);
178
+ break;
179
+ }
180
+ case "message.end": {
181
+ this.#sealed.add(ev.id);
182
+ // INV-MSG: sealing removes the open-message pointer so a post-seal
183
+ // block-creating event degrades loudly (resync), never a silent attach.
184
+ for (const [pk, msgId] of this.#openMsg) {
185
+ if (msgId === ev.id)
186
+ this.#openMsg.delete(pk);
187
+ }
188
+ if (ev.usage !== undefined) {
189
+ const msg = this.#messages.get(ev.id);
190
+ if (msg !== undefined) {
191
+ msg.usage = ev.usage;
192
+ }
193
+ }
194
+ break;
195
+ }
196
+ // ── SUBAGENT lifecycle ─────────────────────────────────────────────────
197
+ case "subagent.start": {
198
+ // Task 8c leg 3: a subagent.start always counts as a legitimately
199
+ // opened turn, even on the idempotent-duplicate early return below.
200
+ this.#openedTurns.add(ev.turnId);
201
+ // Idempotent: if the nested turn already exists, skip (never duplicate).
202
+ if (this.#turns.has(ev.turnId))
203
+ break;
204
+ // threadId is required on AgTurnRecord; inherit from the parent turn.
205
+ // subagent.start does not carry threadId on the wire, so we look it up.
206
+ const parentTurn = this.#turns.get(ev.parentTurnId);
207
+ let threadId;
208
+ if (parentTurn !== undefined) {
209
+ threadId = parentTurn.threadId;
210
+ }
211
+ else {
212
+ // Task 8c leg 2 (SPEC §1.2 + guuey capstone finding A): a parent
213
+ // lookup miss means ev.parentTurnId is a wire label that was never
214
+ // opened as a real turn (e.g. claude's synthetic `turn_${toolCallId}`
215
+ // Task-tool cross-ref) — NOT a legitimate cross-thread reference.
216
+ // Every entity in a fold shares one root threadId (SPEC §1.2), so
217
+ // fall back to any ALREADY-OPENED real turn's threadId instead of
218
+ // adopting the unresolvable label as this subagent's own threadId.
219
+ // A "real" turn is identified by threadId !== turnId — a defensive
220
+ // ensureTurn() stub uses its own turnId as a threadId placeholder
221
+ // and must never be picked here. `ev.parentTurnId` remains the last
222
+ // resort when no real turn exists yet.
223
+ const realTurn = [...this.#turns.values()].find((t) => t.threadId !== t.turnId);
224
+ threadId = realTurn?.threadId ?? ev.parentTurnId;
225
+ }
226
+ this.#turns.set(ev.turnId, {
227
+ turnId: ev.turnId,
228
+ parentTurnId: ev.parentTurnId,
229
+ threadId,
230
+ });
231
+ break;
232
+ }
233
+ case "subagent.done": {
234
+ // No AgReduceResult landing for subagent.done beyond what's already recorded.
235
+ break;
236
+ }
237
+ // ── STEP lifecycle — structural scratch only, NO AgReduceResult landing ──
238
+ case "step.start": {
239
+ // Live-only structural marker (spec §5 step rows): steps have no
240
+ // AgReduceResult container — no-op on the output tree.
241
+ break;
242
+ }
243
+ case "step.done": {
244
+ // Live-only structural marker (spec §5 step rows): step.done.usage has
245
+ // no fold target; turn.done.usage is the authoritative turn accounting.
246
+ break;
247
+ }
248
+ // ── TEXT blocks ───────────────────────────────────────────────────────────
249
+ case "text.start": {
250
+ const msg = this.openMessage(ev.turnId, ev.candidateIndex ?? 0);
251
+ if (msg === undefined) {
252
+ this.#resync = true;
253
+ break;
254
+ }
255
+ const block = {
256
+ type: "text",
257
+ text: "", // REQUIRED field — mid-stream result() before any delta must parse
258
+ ...(ev.providerMetadata !== undefined ? { providerMetadata: ev.providerMetadata } : {}),
259
+ ...(ev._meta !== undefined ? { _meta: ev._meta } : {}),
260
+ };
261
+ const index = msg.content.length;
262
+ msg.content.push(block);
263
+ this.#blockPos.set(ev.id, { messageId: msg.id, index });
264
+ break;
265
+ }
266
+ case "text.delta": {
267
+ const pos = this.#blockPos.get(ev.id);
268
+ if (pos === undefined)
269
+ break;
270
+ const msg = this.#messages.get(pos.messageId);
271
+ if (msg === undefined)
272
+ break;
273
+ const block = msg.content[pos.index];
274
+ if (block === undefined || block.type !== "text")
275
+ break;
276
+ block.text += ev.delta;
277
+ block.providerMetadata = mergeProviderMeta(block.providerMetadata, ev.providerMetadata);
278
+ break;
279
+ }
280
+ case "text.end": {
281
+ const pos = this.#blockPos.get(ev.id);
282
+ if (pos === undefined)
283
+ break;
284
+ const msg = this.#messages.get(pos.messageId);
285
+ if (msg === undefined)
286
+ break;
287
+ const block = msg.content[pos.index];
288
+ if (block === undefined || block.type !== "text")
289
+ break;
290
+ block.providerMetadata = mergeProviderMeta(block.providerMetadata, ev.providerMetadata);
291
+ // STREAMED-text citations carrier (audit M22): attach citations to the
292
+ // sealed block named by `ev.id` — never re-emitted as a duplicate
293
+ // supplement block.
294
+ if (ev.citations !== undefined)
295
+ block.citations = ev.citations;
296
+ break;
297
+ }
298
+ // ── REASONING blocks ──────────────────────────────────────────────────────
299
+ case "reasoning.start": {
300
+ const msg = this.openMessage(ev.turnId, ev.candidateIndex ?? 0);
301
+ if (msg === undefined) {
302
+ this.#resync = true;
303
+ break;
304
+ }
305
+ const block = {
306
+ type: "reasoning",
307
+ text: "", // seeded — mid-stream result() before any delta must parse
308
+ ...(ev.providerMetadata !== undefined ? { providerMetadata: ev.providerMetadata } : {}),
309
+ ...(ev._meta !== undefined ? { _meta: ev._meta } : {}),
310
+ ...(ev.itemId !== undefined ? { itemId: ev.itemId } : {}),
311
+ };
312
+ const index = msg.content.length;
313
+ msg.content.push(block);
314
+ this.#blockPos.set(ev.id, { messageId: msg.id, index });
315
+ break;
316
+ }
317
+ case "reasoning.delta": {
318
+ const pos = this.#blockPos.get(ev.id);
319
+ if (pos === undefined)
320
+ break;
321
+ const msg = this.#messages.get(pos.messageId);
322
+ if (msg === undefined)
323
+ break;
324
+ const block = msg.content[pos.index];
325
+ if (block === undefined || block.type !== "reasoning")
326
+ break;
327
+ // APPEND delta to text (in-order concat of parts)
328
+ block.text = (block.text ?? "") + ev.delta;
329
+ block.providerMetadata = mergeProviderMeta(block.providerMetadata, ev.providerMetadata);
330
+ break;
331
+ }
332
+ case "reasoning.end": {
333
+ const pos = this.#blockPos.get(ev.id);
334
+ if (pos === undefined)
335
+ break;
336
+ const msg = this.#messages.get(pos.messageId);
337
+ if (msg === undefined)
338
+ break;
339
+ const block = msg.content[pos.index];
340
+ if (block === undefined || block.type !== "reasoning")
341
+ break;
342
+ block.providerMetadata = mergeProviderMeta(block.providerMetadata, ev.providerMetadata);
343
+ if (ev.provider !== undefined) {
344
+ block.provider = ev.provider;
345
+ }
346
+ break;
347
+ }
348
+ case "reasoning.opaque.delta": {
349
+ // APPEND to per-id opaque scratch buffer (sealed by the following reasoning.opaque).
350
+ const existing = this.#opaque.get(ev.id) ?? "";
351
+ this.#opaque.set(ev.id, existing + ev.delta);
352
+ break;
353
+ }
354
+ case "reasoning.opaque": {
355
+ // REPLACE: set opaque on the reasoning block named by id (replay-load-bearing).
356
+ const pos = this.#blockPos.get(ev.id);
357
+ if (pos === undefined)
358
+ break;
359
+ const msg = this.#messages.get(pos.messageId);
360
+ if (msg === undefined)
361
+ break;
362
+ const block = msg.content[pos.index];
363
+ if (block === undefined || block.type !== "reasoning")
364
+ break;
365
+ // Use accumulated opaque scratch if present; otherwise use ev.value directly.
366
+ const value = this.#opaque.has(ev.id) ? (this.#opaque.get(ev.id) ?? ev.value) : ev.value;
367
+ block.opaque = {
368
+ kind: ev.kind,
369
+ value,
370
+ ...(ev.provider !== undefined ? { provider: ev.provider } : {}),
371
+ };
372
+ // Clear the scratch buffer now that it's been sealed.
373
+ this.#opaque.delete(ev.id);
374
+ if (ev.itemId !== undefined) {
375
+ block.itemId = ev.itemId;
376
+ }
377
+ break;
378
+ }
379
+ // ── TOOL-CALL blocks ──────────────────────────────────────────────────────
380
+ case "tool.start": {
381
+ const msg = this.openMessage(ev.turnId, ev.candidateIndex ?? 0);
382
+ if (msg === undefined) {
383
+ this.#resync = true;
384
+ break;
385
+ }
386
+ const block = {
387
+ type: "tool-call",
388
+ toolCallId: ev.toolCallId,
389
+ name: ev.name,
390
+ // Seed with empty object so a mid-stream result() still parses (must-fix #8).
391
+ input: {},
392
+ ...(ev.serverName !== undefined ? { serverName: ev.serverName } : {}),
393
+ ...(ev.providerExecuted !== undefined ? { providerExecuted: ev.providerExecuted } : {}),
394
+ ...(ev.title !== undefined ? { title: ev.title } : {}),
395
+ ...(ev.toolMetadata !== undefined ? { toolMetadata: ev.toolMetadata } : {}),
396
+ ...(ev.itemId !== undefined ? { itemId: ev.itemId } : {}),
397
+ ...(ev.uiVisibility !== undefined ? { uiVisibility: ev.uiVisibility } : {}),
398
+ ...(ev.providerMetadata !== undefined ? { providerMetadata: ev.providerMetadata } : {}),
399
+ };
400
+ const index = msg.content.length;
401
+ msg.content.push(block);
402
+ this.#blockPos.set(ev.toolCallId, { messageId: msg.id, index });
403
+ break;
404
+ }
405
+ case "tool.args.delta": {
406
+ // APPEND raw partial-JSON delta to scratch (NEVER authoritative input).
407
+ const existing = this.#toolArgs.get(ev.toolCallId) ?? "";
408
+ this.#toolArgs.set(ev.toolCallId, existing + ev.delta);
409
+ break;
410
+ }
411
+ case "tool.args.assembled": {
412
+ // AUTHORITATIVE: replace seeded input:{} with the assembled value.
413
+ const pos = this.#blockPos.get(ev.toolCallId);
414
+ if (pos === undefined)
415
+ break;
416
+ const msg = this.#messages.get(pos.messageId);
417
+ if (msg === undefined)
418
+ break;
419
+ const block = msg.content[pos.index];
420
+ if (block === undefined || block.type !== "tool-call")
421
+ break;
422
+ block.input = ev.input;
423
+ if (ev.signature !== undefined) {
424
+ block.signature = ev.signature;
425
+ }
426
+ if (ev.title !== undefined) {
427
+ block.title = ev.title;
428
+ }
429
+ if (ev.toolMetadata !== undefined) {
430
+ block.toolMetadata = ev.toolMetadata;
431
+ }
432
+ block.providerMetadata = mergeProviderMeta(block.providerMetadata, ev.providerMetadata);
433
+ // Clear scratch now that it's been superseded by the authoritative input.
434
+ this.#toolArgs.delete(ev.toolCallId);
435
+ break;
436
+ }
437
+ // ── TOOL-RESULT blocks ────────────────────────────────────────────────────
438
+ case "tool.done": {
439
+ const resultKey = `result:${ev.toolCallId}`;
440
+ const existingPos = this.#blockPos.get(resultKey);
441
+ if (existingPos !== undefined) {
442
+ // MERGE path: a preliminary tool-result block is already open for this
443
+ // toolCallId. Replace its content with the incoming (final or next-preliminary)
444
+ // content.
445
+ const msg = this.#messages.get(existingPos.messageId);
446
+ if (msg === undefined)
447
+ break;
448
+ const block = msg.content[existingPos.index];
449
+ if (block === undefined || block.type !== "tool-result")
450
+ break;
451
+ // INV-MSG enforcement: a post-terminal straggler tool.done for a still-open
452
+ // more:true preliminary must never silently mutate a closed turn's already-
453
+ // published content. Resolve the block's owning turn via the
454
+ // #blockPos → messageId → message.turnId chain and park instead of mutating
455
+ // (mirrors the adoption path's closed-turn/sealed guard above).
456
+ const ownerTurnKey = msg.turnId ?? "unknown-turn";
457
+ if (this.#sealed.has(msg.id) || this.#closedTurns.has(ownerTurnKey)) {
458
+ this.#resync = true;
459
+ break;
460
+ }
461
+ block.content = ev.content;
462
+ if (ev.outcome !== undefined)
463
+ block.outcome = ev.outcome;
464
+ if (ev.isError !== undefined)
465
+ block.isError = ev.isError;
466
+ if (ev.structuredContent !== undefined)
467
+ block.structuredContent = ev.structuredContent;
468
+ if (ev.uiData !== undefined)
469
+ block.uiData = ev.uiData;
470
+ if (ev.sideData !== undefined)
471
+ block.sideData = ev.sideData;
472
+ if (ev.errorText !== undefined)
473
+ block.errorText = ev.errorText;
474
+ if (ev.errorCode !== undefined)
475
+ block.errorCode = ev.errorCode;
476
+ if (ev.pendingInput !== undefined)
477
+ block.pendingInput = ev.pendingInput;
478
+ block.providerMetadata = mergeProviderMeta(block.providerMetadata, ev.providerMetadata);
479
+ // Typed preliminary flag mirrors the block's `more` state (audit M20):
480
+ // more:true keeps it set (partial, kept open); the final more-less tool.done
481
+ // REPLACES the result fields wholesale (merge = REPLACE, code-canonical) and
482
+ // clears it, closing (removing from open tracking).
483
+ if (ev.more) {
484
+ block.preliminary = true;
485
+ }
486
+ else {
487
+ delete block.preliminary;
488
+ this.#blockPos.delete(resultKey);
489
+ }
490
+ }
491
+ else {
492
+ // CREATE path: first tool.done for this toolCallId.
493
+ let msg;
494
+ if (ev.messageId !== undefined) {
495
+ // SPEC §5 tool.done row: the landed tool-result message ADOPTS
496
+ // ev.messageId as its own id (stable ToolMessage identity; audit B10).
497
+ const existing = this.#messages.get(ev.messageId);
498
+ // INV-MSG enforcement: a sealed message, or ANY message of a closed
499
+ // turn — including one that would need to be freshly created — is
500
+ // never a valid adoption target. Resolve the turn this adoption
501
+ // would land in (the existing message's own turnId, or the turnId
502
+ // ensureTurn() would assign a new message) BEFORE either sub-path
503
+ // runs, and park instead of silently attaching/creating past the
504
+ // seal or the turn's binding window.
505
+ const targetTurnKey = existing !== undefined
506
+ ? (existing.turnId ?? "unknown-turn")
507
+ : (this.#resolveTurnId(ev.turnId) ?? ev.turnId ?? "unknown-turn");
508
+ // Task 8c leg 3 (guuey capstone finding B): a turn that was never
509
+ // legitimately opened (turn.start / subagent.start / a snapshot's
510
+ // turns?) is just as invalid an adoption target as a sealed
511
+ // message or a closed turn — without this, ensureTurn() below
512
+ // would happily fabricate a phantom turn stub instead of parking.
513
+ if (this.#sealed.has(ev.messageId) ||
514
+ this.#closedTurns.has(targetTurnKey) ||
515
+ !this.#openedTurns.has(targetTurnKey)) {
516
+ this.#resync = true;
517
+ break;
518
+ }
519
+ if (existing !== undefined) {
520
+ msg = existing;
521
+ }
522
+ else {
523
+ const turn = this.ensureTurn(ev.turnId);
524
+ // Create new tool-result message with the adopted messageId.
525
+ msg = {
526
+ id: ev.messageId,
527
+ role: "tool",
528
+ content: [],
529
+ turnId: turn.turnId,
530
+ threadId: turn.threadId,
531
+ };
532
+ this.#messages.set(ev.messageId, msg);
533
+ }
534
+ }
535
+ else {
536
+ msg = this.openMessage(ev.turnId, ev.candidateIndex ?? 0);
537
+ }
538
+ if (msg === undefined) {
539
+ this.#resync = true;
540
+ break;
541
+ }
542
+ const block = {
543
+ type: "tool-result",
544
+ toolCallId: ev.toolCallId,
545
+ content: ev.content,
546
+ ...(ev.outcome !== undefined ? { outcome: ev.outcome } : {}),
547
+ ...(ev.isError !== undefined ? { isError: ev.isError } : {}),
548
+ ...(ev.structuredContent !== undefined ? { structuredContent: ev.structuredContent } : {}),
549
+ ...(ev.uiData !== undefined ? { uiData: ev.uiData } : {}),
550
+ ...(ev.sideData !== undefined ? { sideData: ev.sideData } : {}),
551
+ ...(ev.errorText !== undefined ? { errorText: ev.errorText } : {}),
552
+ ...(ev.errorCode !== undefined ? { errorCode: ev.errorCode } : {}),
553
+ ...(ev.toolMetadata !== undefined ? { toolMetadata: ev.toolMetadata } : {}),
554
+ ...(ev.dynamic !== undefined ? { dynamic: ev.dynamic } : {}),
555
+ ...(ev.pendingInput !== undefined ? { pendingInput: ev.pendingInput } : {}),
556
+ ...(ev.providerMetadata !== undefined ? { providerMetadata: ev.providerMetadata } : {}),
557
+ ...(ev.more === true ? { preliminary: true } : {}),
558
+ };
559
+ const index = msg.content.length;
560
+ msg.content.push(block);
561
+ // If more:true, keep the block open for subsequent merge.
562
+ if (ev.more) {
563
+ this.#blockPos.set(resultKey, { messageId: msg.id, index });
564
+ }
565
+ }
566
+ break;
567
+ }
568
+ // ── CONTENT.BLOCK ────────────────────────────────────────────────────────
569
+ case "content.block": {
570
+ // Transient at event level: skip (live-only, never folded).
571
+ if (ev.transient === true)
572
+ break;
573
+ // Transient at block level (data block): skip.
574
+ if (ev.block.type === "data" && ev.block.transient === true)
575
+ break;
576
+ const msg = this.openMessage(ev.turnId, ev.candidateIndex ?? 0);
577
+ if (msg === undefined) {
578
+ this.#resync = true;
579
+ break;
580
+ }
581
+ // Same-id REPLACE-in-place: only data blocks carry id?.
582
+ if (ev.block.type === "data" && ev.block.id !== undefined) {
583
+ const existingPos = this.#blockPos.get(ev.block.id);
584
+ if (existingPos !== undefined && existingPos.messageId === msg.id) {
585
+ // REPLACE in place — same position, preserve byte-order.
586
+ msg.content[existingPos.index] = ev.block;
587
+ break;
588
+ }
589
+ }
590
+ // APPEND: push the block and (for blocks with an id) register the position.
591
+ const index = msg.content.length;
592
+ msg.content.push(ev.block);
593
+ if (ev.block.type === "data" && ev.block.id !== undefined) {
594
+ this.#blockPos.set(ev.block.id, { messageId: msg.id, index });
595
+ }
596
+ break;
597
+ }
598
+ // ── MESSAGE.METADATA ─────────────────────────────────────────────────────
599
+ case "message.metadata": {
600
+ // Resolve the target message: by explicit messageId or the open assistant message.
601
+ let msg;
602
+ if (ev.messageId !== undefined) {
603
+ msg = this.#messages.get(ev.messageId);
604
+ }
605
+ else {
606
+ // Fall back to the open message for the event's turnId (base carries turnId?).
607
+ msg = this.openMessage(ev.turnId, 0);
608
+ }
609
+ if (msg === undefined)
610
+ break;
611
+ // Shallow merge REPLACE-by-key into msg.metadata (create if absent).
612
+ msg.metadata = { ...(msg.metadata ?? {}), ...ev.metadata };
613
+ break;
614
+ }
615
+ // ── TURN-RECORD events (R5) ───────────────────────────────────────────────
616
+ case "turn.done": {
617
+ const turn = this.ensureTurn(ev.turnId);
618
+ turn.finishReason = ev.finishReason;
619
+ // Usage is recorded VERBATIM — NO de-cumulation (spec §8.4; normalizer duty).
620
+ if (ev.usage !== undefined)
621
+ turn.usage = ev.usage;
622
+ if (ev.safety !== undefined)
623
+ turn.safety = ev.safety;
624
+ if (ev.taskState !== undefined)
625
+ turn.taskState = ev.taskState;
626
+ turn.outcome = ev.outcome;
627
+ // If outcome is paused, record the asks at the top-level asks[] too.
628
+ if (ev.outcome.type === "paused") {
629
+ turn.asks = ev.outcome.asks;
630
+ }
631
+ // messageMetadata: REPLACE-merge onto the message named by turn.done.messageId
632
+ // when present, else the open message of this turn (audit M20).
633
+ // (Read happens BEFORE the binding window closes below.)
634
+ if (ev.messageMetadata !== undefined) {
635
+ const msg = ev.messageId !== undefined ? this.#messages.get(ev.messageId) : this.openMessage(ev.turnId, 0);
636
+ if (msg !== undefined) {
637
+ msg.messageMetadata = ev.messageMetadata;
638
+ }
639
+ }
640
+ // INV-MSG binding window: no blocks attach to a closed turn's messages.
641
+ this.#closeTurnWindow(ev.turnId);
642
+ this.#evictTurnScratch(ev.turnId);
643
+ break;
644
+ }
645
+ case "turn.error": {
646
+ // Non-folding into content; sets outcome={type:"error",...} on the turn record.
647
+ const turn = this.ensureTurn(ev.turnId);
648
+ turn.outcome = {
649
+ type: "error",
650
+ message: ev.message,
651
+ ...(ev.code !== undefined ? { code: ev.code } : {}),
652
+ };
653
+ // Usage is recorded VERBATIM — NO de-cumulation (mirrors turn.done; normalizer duty).
654
+ if (ev.usage !== undefined)
655
+ turn.usage = ev.usage;
656
+ // INV-MSG binding window: no blocks attach to a closed turn's messages.
657
+ this.#closeTurnWindow(ev.turnId);
658
+ this.#evictTurnScratch(ev.turnId);
659
+ break;
660
+ }
661
+ case "turn.abort": {
662
+ // Non-folding into content; sets a dedicated aborted outcome on the turn record
663
+ // (symmetric with turn.error). taskState is verbatim-A2A only and is NEVER
664
+ // reducer-invented (audit M29) — it stays whatever a prior turn.done left it as.
665
+ const turn = this.ensureTurn(ev.turnId);
666
+ turn.outcome = { type: "aborted", ...(ev.reason !== undefined ? { reason: ev.reason } : {}) };
667
+ // INV-MSG binding window: no blocks attach to a closed turn's messages.
668
+ this.#closeTurnWindow(ev.turnId);
669
+ this.#evictTurnScratch(ev.turnId);
670
+ break;
671
+ }
672
+ case "source": {
673
+ // Append sourceId to the turn's sourceIds[] in order (preserve groundingChunks order),
674
+ // AND land the FULL record (payload/chunkIndex/providerMetadata) on sources[] so
675
+ // citations can resolve post-fold (audit M23) — sourceIds[] stays as the derived index.
676
+ const turn = this.ensureTurn(ev.turnId);
677
+ if (turn.sourceIds === undefined) {
678
+ turn.sourceIds = [];
679
+ }
680
+ turn.sourceIds.push(ev.sourceId);
681
+ if (turn.sources === undefined) {
682
+ turn.sources = [];
683
+ }
684
+ turn.sources.push({
685
+ sourceId: ev.sourceId,
686
+ source: ev.source,
687
+ ...(ev.chunkIndex !== undefined ? { chunkIndex: ev.chunkIndex } : {}),
688
+ ...(ev.providerMetadata !== undefined ? { providerMetadata: ev.providerMetadata } : {}),
689
+ });
690
+ break;
691
+ }
692
+ case "handoff": {
693
+ // Push an AgHandoffRecord onto the turn's handoffs[].
694
+ const turn = this.ensureTurn(ev.turnId);
695
+ if (turn.handoffs === undefined) {
696
+ turn.handoffs = [];
697
+ }
698
+ const record = {
699
+ ...(ev.kind !== undefined ? { kind: ev.kind } : {}),
700
+ ...(ev.fromAgentId !== undefined ? { fromAgentId: ev.fromAgentId } : {}),
701
+ ...(ev.toAgentId !== undefined ? { toAgentId: ev.toAgentId } : {}),
702
+ ...(ev.toAgentName !== undefined ? { toAgentName: ev.toAgentName } : {}),
703
+ };
704
+ turn.handoffs.push(record);
705
+ break;
706
+ }
707
+ case "prompt.blocked": {
708
+ // Record safety[] on the turn (merge — append to existing safety, or create) AND
709
+ // land the dedicated promptBlocked record {reason, safety?} so the REQUIRED reason
710
+ // and the blockedness itself survive the fold — a bare-reason block used to fold to
711
+ // ZERO trace (audit M28).
712
+ const turn = this.ensureTurn(ev.turnId);
713
+ if (ev.safety !== undefined) {
714
+ if (turn.safety === undefined) {
715
+ turn.safety = [...ev.safety];
716
+ }
717
+ else {
718
+ turn.safety = [...turn.safety, ...ev.safety];
719
+ }
720
+ }
721
+ turn.promptBlocked = {
722
+ reason: ev.reason,
723
+ ...(ev.safety !== undefined ? { safety: ev.safety } : {}),
724
+ };
725
+ break;
726
+ }
727
+ case "guardrail.result": {
728
+ // Push a guardrail evaluation record onto the turn's guardrails[].
729
+ const turn = this.ensureTurn(ev.turnId);
730
+ if (turn.guardrails === undefined) {
731
+ turn.guardrails = [];
732
+ }
733
+ turn.guardrails.push({
734
+ target: ev.target,
735
+ passed: ev.passed,
736
+ ...(ev.action !== undefined ? { action: ev.action } : {}),
737
+ ...(ev.reason !== undefined ? { reason: ev.reason } : {}),
738
+ ...(ev.guardrailName !== undefined ? { guardrailName: ev.guardrailName } : {}),
739
+ ...(ev.safety !== undefined ? { safety: ev.safety } : {}),
740
+ });
741
+ break;
742
+ }
743
+ case "display.required": {
744
+ // MUST NOT drop (ToS). Push {provider, html} onto turn's displayRequired[].
745
+ const turn = this.ensureTurn(ev.turnId);
746
+ if (turn.displayRequired === undefined) {
747
+ turn.displayRequired = [];
748
+ }
749
+ const entry = { provider: ev.provider, html: ev.html };
750
+ turn.displayRequired.push(entry);
751
+ break;
752
+ }
753
+ case "agent.capabilities": {
754
+ // SPEC §5: "Record the agent's AgCapabilities on the turn (first-turn negotiation)."
755
+ // Fold ev.capabilities onto the AgTurnRecord for the owning turn.
756
+ const turn = this.ensureTurn(ev.turnId);
757
+ turn.capabilities = ev.capabilities;
758
+ break;
759
+ }
760
+ // ── ARTIFACT side-channel (R7) ─────────────────────────────────────────────
761
+ case "artifact.start": {
762
+ // Create a new AgArtifact entry in #artifacts.
763
+ const artifact = {
764
+ artifactId: ev.artifactId,
765
+ turnId: ev.turnId,
766
+ threadId: ev.threadId,
767
+ parts: [],
768
+ ...(ev.name !== undefined ? { name: ev.name } : {}),
769
+ ...(ev.description !== undefined ? { description: ev.description } : {}),
770
+ ...(ev.extensions !== undefined ? { extensions: ev.extensions } : {}),
771
+ };
772
+ this.#artifacts.set(ev.artifactId, artifact);
773
+ break;
774
+ }
775
+ case "artifact.delta": {
776
+ // Append or concatenate onto the artifact's parts[].
777
+ const artifact = this.#artifacts.get(ev.artifactId);
778
+ if (artifact === undefined)
779
+ break;
780
+ if (ev.append === false) {
781
+ // START a new part: push a shallow copy of the incoming part so that
782
+ // subsequent in-place text concatenation (append:true) does NOT mutate
783
+ // the original event object. The caller may be replaying the same
784
+ // event array twice (batch vs. incremental), so aliasing must be broken here.
785
+ artifact.parts.push({ ...ev.part });
786
+ }
787
+ else {
788
+ // CONCATENATE onto the last part.
789
+ const last = artifact.parts[artifact.parts.length - 1];
790
+ if (last !== undefined && last.type === "text" && ev.part.type === "text") {
791
+ // Both are text blocks: append the text in-place.
792
+ last.text += ev.part.text;
793
+ }
794
+ else {
795
+ // Incompatible types or empty parts array: push a SHALLOW COPY (same
796
+ // aliasing discipline as the append:false path above) so a following
797
+ // append:true in-place concat can't mutate the original event object.
798
+ artifact.parts.push({ ...ev.part });
799
+ }
800
+ }
801
+ break;
802
+ }
803
+ case "artifact.end": {
804
+ // Finalize the artifact. No further parts; nothing to do beyond leaving it
805
+ // in #artifacts. The lastChunk:true flag is informational only.
806
+ break;
807
+ }
808
+ // ── SHARED STATE side-channel (R8) ───────────────────────────────────────
809
+ case "state.snapshot": {
810
+ // REPLACE #state wholesale with the incoming snapshot value.
811
+ // Also clears #resync if set — state.snapshot is one of the two valid
812
+ // resync-recovery paths (the R9 park-gate will route it here while parked).
813
+ this.#state = ev.snapshot;
814
+ this.#resync = false;
815
+ break;
816
+ }
817
+ case "state.delta": {
818
+ // Apply patch to #state using a tightened discriminator:
819
+ //
820
+ // Array.isArray(patch) → RFC-6902 via applyPatch (R6)
821
+ // typeof patch === "object" && != null → LangGraph node-keyed last-writer-wins merge
822
+ // else (scalar / null) → explicit no-op
823
+ // (documented: a future third source may extend this discriminator;
824
+ // scalars are NOT an error and must NOT set #resync)
825
+ const patch = ev.patch;
826
+ if (Array.isArray(patch)) {
827
+ // RFC-6902 path: requires an existing document to patch against.
828
+ if (this.#state === undefined) {
829
+ // No document to apply the patch to — signal resync (same semantics
830
+ // as memory.write patch against a never-seeded record).
831
+ this.#resync = true;
832
+ break;
833
+ }
834
+ const result = applyPatch(this.#state, patch);
835
+ if (!result.ok) {
836
+ // applyPatch failed — signal resync; leave #state unchanged.
837
+ this.#resync = true;
838
+ break;
839
+ }
840
+ this.#state = result.value;
841
+ }
842
+ else if (typeof patch === "object" && patch !== null) {
843
+ // LangGraph node-keyed last-writer-wins merge:
844
+ // patch = { nodeKey: { key: value, ... }, ... }
845
+ // For each top-level node key, shallow-merge its sub-object into #state[node].
846
+ // Creates #state as {} if undefined; creates the node sub-object if absent.
847
+ const base = this.#state !== undefined && typeof this.#state === "object" && !Array.isArray(this.#state)
848
+ ? { ...this.#state }
849
+ : {};
850
+ for (const nodeKey of Object.keys(patch)) {
851
+ const nodeUpdate = patch[nodeKey];
852
+ if (typeof nodeUpdate === "object" && nodeUpdate !== null && !Array.isArray(nodeUpdate)) {
853
+ // Shallow-merge the node's key-value pairs into base[nodeKey].
854
+ const existing = base[nodeKey];
855
+ const existingObj = typeof existing === "object" && existing !== null && !Array.isArray(existing)
856
+ ? { ...existing }
857
+ : {};
858
+ base[nodeKey] = { ...existingObj, ...nodeUpdate };
859
+ }
860
+ else {
861
+ // Non-object node value: replace the node entry wholesale.
862
+ if (nodeUpdate !== undefined) {
863
+ base[nodeKey] = nodeUpdate;
864
+ }
865
+ }
866
+ }
867
+ this.#state = base;
868
+ }
869
+ // else: scalar or null patch — explicit no-op. A future third source may
870
+ // extend this discriminator deliberately; do NOT crash or set #resync.
871
+ break;
872
+ }
873
+ // ── MEMORY side-channel (R7) ──────────────────────────────────────────────
874
+ case "memory.write": {
875
+ // Memory records are keyed by `${scope}${key ?? ""}`.
876
+ const memKey = `${ev.scope}${ev.key ?? ""}`;
877
+ if (ev.value !== undefined) {
878
+ // SET path: create or replace the record.
879
+ const record = {
880
+ scope: ev.scope,
881
+ ...(ev.key !== undefined ? { key: ev.key } : {}),
882
+ value: ev.value,
883
+ ...(ev.reason !== undefined ? { reason: ev.reason } : {}),
884
+ ...(ev.durable !== undefined ? { durable: ev.durable } : {}),
885
+ ...(ev.turnId !== undefined ? { turnId: ev.turnId } : {}),
886
+ };
887
+ this.#memory.set(memKey, record);
888
+ }
889
+ else if (ev.patch !== undefined) {
890
+ // PATCH path: mutate an existing record via R6 applyPatch.
891
+ const existing = this.#memory.get(memKey);
892
+ if (existing === undefined) {
893
+ // NEVER seed from {} — set resync flag and bail.
894
+ this.#resync = true;
895
+ break;
896
+ }
897
+ const result = applyPatch(existing.value, ev.patch);
898
+ if (!result.ok) {
899
+ // applyPatch failed — set resync flag and leave record unchanged.
900
+ this.#resync = true;
901
+ break;
902
+ }
903
+ // Update value in-place; also update optional metadata from the event.
904
+ existing.value = result.value;
905
+ if (ev.reason !== undefined)
906
+ existing.reason = ev.reason;
907
+ if (ev.durable !== undefined)
908
+ existing.durable = ev.durable;
909
+ }
910
+ break;
911
+ }
912
+ // ── MESSAGE.REMOVE (R9) ──────────────────────────────────────────────────
913
+ case "message.remove": {
914
+ if (ev.id === REMOVE_ALL) {
915
+ // REMOVE_ALL: remove every message of exactly the given turnId.
916
+ // Parse-enforced: id===REMOVE_ALL without turnId is already rejected.
917
+ const targetTurnId = ev.turnId;
918
+ if (targetTurnId === undefined)
919
+ break; // parse-rejected; should not reach
920
+ const toRemove = [];
921
+ for (const [msgId, msg] of this.#messages) {
922
+ if (msg.turnId === targetTurnId) {
923
+ toRemove.push(msgId);
924
+ }
925
+ }
926
+ // Zero matches = deterministic no-op (not an error).
927
+ for (const msgId of toRemove) {
928
+ this.#removeMessage(msgId);
929
+ }
930
+ }
931
+ else {
932
+ this.#removeMessage(ev.id);
933
+ }
934
+ break;
935
+ }
936
+ // ── MESSAGES.SNAPSHOT (R9) ───────────────────────────────────────────────
937
+ case "messages.snapshot": {
938
+ // structuredClone each incoming array at store time so a later in-place
939
+ // mutation (turn.done/source/text.delta/memory.write patch onto a
940
+ // snapshot-seeded record) can NOT write through into the original event
941
+ // object — otherwise a re-fold (batch vs incremental) of the same array
942
+ // diverges (same aliasing discipline as result()/applyPatch).
943
+ // ALWAYS replace #messages.
944
+ this.#messages = new Map(structuredClone(ev.messages).map((m) => [m.id, m]));
945
+ // CONDITIONALLY replace #turns (only if turns? present in event).
946
+ if (ev.turns !== undefined) {
947
+ this.#turns = new Map(structuredClone(ev.turns).map((t) => [t.turnId, t]));
948
+ }
949
+ // CONDITIONALLY replace #artifacts (only if artifacts? present in event).
950
+ if (ev.artifacts !== undefined) {
951
+ this.#artifacts = new Map(structuredClone(ev.artifacts).map((a) => [a.artifactId, a]));
952
+ }
953
+ // CONDITIONALLY replace ONLY scope==="thread" memory records.
954
+ // Rebuild: [surviving non-thread records in insertion order, then snapshot's thread records].
955
+ if (ev.memory !== undefined) {
956
+ const nonThread = [];
957
+ for (const [k, rec] of this.#memory) {
958
+ if (rec.scope !== "thread") {
959
+ nonThread.push([k, rec]);
960
+ }
961
+ }
962
+ const snapshotThread = structuredClone(ev.memory)
963
+ .filter((rec) => rec.scope === "thread")
964
+ .map((rec) => [`${rec.scope}${rec.key ?? ""}`, rec]);
965
+ this.#memory = new Map([...nonThread, ...snapshotThread]);
966
+ }
967
+ // Clear ALL transient scratch.
968
+ this.#toolArgs = new Map();
969
+ this.#opaque = new Map();
970
+ this.#openMsg = new Map();
971
+ this.#sealed = new Set();
972
+ this.#closedTurns = new Set();
973
+ this.#blockPos = new Map();
974
+ // Task 8c leg 3: a snapshot-restored turn counts as opened (guuey
975
+ // capstone finding B) — reseed #openedTurns from the replaced turns in
976
+ // lockstep with #turns above; no turns replaced ⇒ no fresh legitimacy
977
+ // to assert (mirrors the unconditional #closedTurns reset above).
978
+ this.#openedTurns = ev.turns !== undefined
979
+ ? new Set(ev.turns.map((t) => t.turnId))
980
+ : new Set(this.#turns.keys());
981
+ // Un-park.
982
+ this.#resync = false;
983
+ break;
984
+ }
985
+ // ── LIVE-ONLY / NON-FOLDING (R9) ─────────────────────────────────────────
986
+ // These events produce NO change to the fold result.
987
+ // `error` (bare advisory), `host.context`, `hitl.ask`, and ALL `ui.*` events.
988
+ // (Note: `turn.error` and `turn.abort` are NOT here — they fold in R5.)
989
+ case "error":
990
+ case "host.context":
991
+ case "hitl.ask":
992
+ case "ui.call":
993
+ case "ui.result":
994
+ case "ui.action-result":
995
+ case "ui.widget.result":
996
+ case "ui.display-mode":
997
+ case "ui.surface.start":
998
+ case "ui.surface.update":
999
+ case "ui.surface.end":
1000
+ case "ui.data-model":
1001
+ // Live-only: deliberate no-op. No accumulator mutation.
1002
+ break;
1003
+ // All other event types are handled by later tasks (R6–R10).
1004
+ default:
1005
+ break;
1006
+ }
1007
+ }
1008
+ /**
1009
+ * Remove a single message by id from #messages, its content blocks' #blockPos
1010
+ * entries (guarded by messageId match), and revert the #openMsg pointer for
1011
+ * its partition to the last still-present, not-#sealed message in insertion order.
1012
+ *
1013
+ * The block-creating handlers that call openMessage() already set #resync when
1014
+ * the pointer is missing (none), so we only need to update the pointer here.
1015
+ */
1016
+ #removeMessage(msgId) {
1017
+ const msg = this.#messages.get(msgId);
1018
+ if (msg === undefined)
1019
+ return; // no-op if not found
1020
+ // Remove #blockPos entries ONLY when their stored messageId matches.
1021
+ // This guards against corrupting blocks in other partitions that share a block id.
1022
+ for (const [blockId, pos] of this.#blockPos) {
1023
+ if (pos.messageId === msgId) {
1024
+ this.#blockPos.delete(blockId);
1025
+ // Clear the per-block scratch buffers too (same block-id / toolCallId key),
1026
+ // else a stale opaque-signature / arg buffer leaks into a LATER message that
1027
+ // reuses the same id (cross-task scratch leak — byte-identity can't catch it
1028
+ // because it corrupts batch AND incremental identically). (final-review M1)
1029
+ this.#toolArgs.delete(blockId);
1030
+ this.#opaque.delete(blockId);
1031
+ }
1032
+ }
1033
+ // Remove from #messages.
1034
+ this.#messages.delete(msgId);
1035
+ // Remove from #sealed if sealed.
1036
+ this.#sealed.delete(msgId);
1037
+ // ── Pointer-revert ────────────────────────────────────────────────────────
1038
+ // Determine the partition key for this message.
1039
+ const turnId = msg.turnId;
1040
+ if (turnId === undefined)
1041
+ return; // no partition to revert
1042
+ const candIdx = msg.candidateIndex ?? 0;
1043
+ const pk = partKey(turnId, candIdx);
1044
+ // Check if the removed message was the current open pointer.
1045
+ const currentOpen = this.#openMsg.get(pk);
1046
+ if (currentOpen !== msgId)
1047
+ return; // pointer was not pointing to this message; done.
1048
+ // Revert: find the LAST still-present, not-#sealed message of this partition
1049
+ // in #messages insertion order.
1050
+ let revertTo = undefined;
1051
+ for (const [id, m] of this.#messages) {
1052
+ if (m.turnId === turnId && (m.candidateIndex ?? 0) === candIdx && !this.#sealed.has(id)) {
1053
+ revertTo = id; // keep scanning — we want the LAST one
1054
+ }
1055
+ }
1056
+ if (revertTo !== undefined) {
1057
+ this.#openMsg.set(pk, revertTo);
1058
+ }
1059
+ else {
1060
+ // No valid prior message: delete the pointer (none).
1061
+ this.#openMsg.delete(pk);
1062
+ // A subsequent block-creating event with no pointer will set #resync
1063
+ // via the openMessage() stub → #resync path in the block handlers.
1064
+ }
1065
+ }
1066
+ /**
1067
+ * Return the open `AgMessage` for a given `(turnId, candidateIndex)` partition.
1068
+ *
1069
+ * Routing rule (spec §5): ALWAYS by the event's own `turnId`. When a single
1070
+ * turn is open and the event omits `turnId`, defaults to that sole open turn.
1071
+ * A missing pointer is a no-op stub here (resync-on-missing-pointer is R9).
1072
+ *
1073
+ * R2/R3/R4 reuse this method to attach blocks to the correct message.
1074
+ *
1075
+ * @param turnId The event's `turnId`, or `undefined` for omitted single-turn.
1076
+ * @param candidateIndex The event's `candidateIndex` (absent → 0).
1077
+ */
1078
+ openMessage(turnId, candidateIndex = 0) {
1079
+ const resolvedTurnId = this.#resolveTurnId(turnId);
1080
+ if (resolvedTurnId === undefined)
1081
+ return undefined;
1082
+ const msgId = this.#openMsg.get(partKey(resolvedTurnId, candidateIndex));
1083
+ if (msgId === undefined)
1084
+ return undefined;
1085
+ // INV-MSG: a sealed message is never an attach target (belt-and-braces —
1086
+ // message.end already clears the pointer; this covers any path that
1087
+ // doesn't go through that clear, e.g. a future direct pointer mutation).
1088
+ if (this.#sealed.has(msgId))
1089
+ return undefined;
1090
+ return this.#messages.get(msgId);
1091
+ }
1092
+ /** Delete every open-message pointer belonging to a closed turn (INV-MSG). */
1093
+ #closeTurnWindow(turnId) {
1094
+ const resolved = this.#resolveTurnId(turnId);
1095
+ if (resolved === undefined)
1096
+ return;
1097
+ this.#closedTurns.add(resolved);
1098
+ for (const [pk] of this.#openMsg) {
1099
+ if (pk.startsWith(`${resolved} `))
1100
+ this.#openMsg.delete(pk);
1101
+ }
1102
+ }
1103
+ /**
1104
+ * Evict dangling per-block streaming scratch owned by a closed turn
1105
+ * (audit M51): #toolArgs/#opaque entries are otherwise reclaimed only on
1106
+ * assembled/seal/snapshot — an errored/aborted turn leaks them and a reused
1107
+ * per-invoke block id in a LATER turn would concatenate stale scratch.
1108
+ */
1109
+ #evictTurnScratch(turnId) {
1110
+ const resolved = this.#resolveTurnId(turnId);
1111
+ if (resolved === undefined)
1112
+ return;
1113
+ for (const [blockId, pos] of this.#blockPos) {
1114
+ const msg = this.#messages.get(pos.messageId);
1115
+ if (msg?.turnId === resolved) {
1116
+ this.#toolArgs.delete(blockId);
1117
+ this.#opaque.delete(blockId);
1118
+ }
1119
+ }
1120
+ }
1121
+ /**
1122
+ * Resolve a possibly-omitted turnId.
1123
+ *
1124
+ * If `turnId` is provided, return it verbatim.
1125
+ * If omitted and exactly one turn is open, return that turn's id.
1126
+ * Otherwise return `undefined` (ambiguous / no turns open).
1127
+ */
1128
+ #resolveTurnId(turnId) {
1129
+ if (turnId !== undefined)
1130
+ return turnId;
1131
+ // Single-turn default: if exactly one turn exists, use it.
1132
+ if (this.#turns.size === 1) {
1133
+ // Map.keys() iterator — noUncheckedIndexedAccess-safe via for..of.
1134
+ for (const key of this.#turns.keys()) {
1135
+ return key;
1136
+ }
1137
+ }
1138
+ return undefined;
1139
+ }
1140
+ /**
1141
+ * Defensive turn lookup: get an existing `AgTurnRecord` by turnId, or create a
1142
+ * minimal stub if the record-on-turn event arrives before its `turn.start`.
1143
+ *
1144
+ * Record-on-turn events (turn.done, turn.error, turn.abort, source, handoff,
1145
+ * prompt.blocked, guardrail.result, display.required) all carry `turnId` (optional
1146
+ * in the base schema). When turnId is undefined, fall back to the sole open turn
1147
+ * (single-turn-stream default). If still ambiguous, create a fallback record keyed
1148
+ * on "unknown-turn" — the stub will be visible in turns[] but can be reconciled on
1149
+ * a subsequent messages.snapshot resync.
1150
+ *
1151
+ * AgTurnRecord requires `threadId`; when creating a defensive stub we use the
1152
+ * turnId itself as a placeholder (no threadId is available without turn.start).
1153
+ */
1154
+ ensureTurn(turnId) {
1155
+ const resolved = this.#resolveTurnId(turnId) ?? turnId;
1156
+ const key = resolved ?? "unknown-turn";
1157
+ const existing = this.#turns.get(key);
1158
+ if (existing !== undefined)
1159
+ return existing;
1160
+ // Defensive stub: threadId is required on AgTurnRecord; use key as placeholder.
1161
+ const stub = { turnId: key, threadId: key };
1162
+ this.#turns.set(key, stub);
1163
+ return stub;
1164
+ }
1165
+ /**
1166
+ * Materialize the current fold state as a DEFENSIVE DEEP COPY.
1167
+ * Each call returns fresh arrays and objects — holding a snapshot
1168
+ * is safe across subsequent push() calls.
1169
+ */
1170
+ result() {
1171
+ return {
1172
+ messages: this.#messages.size
1173
+ ? structuredClone([...this.#messages.values()])
1174
+ : [],
1175
+ artifacts: this.#artifacts.size
1176
+ ? structuredClone([...this.#artifacts.values()])
1177
+ : [],
1178
+ memory: this.#memory.size
1179
+ ? structuredClone([...this.#memory.values()])
1180
+ : [],
1181
+ turns: this.#turns.size
1182
+ ? structuredClone([...this.#turns.values()])
1183
+ : [],
1184
+ ...(this.#state !== undefined
1185
+ ? { state: structuredClone(this.#state) }
1186
+ : {}),
1187
+ };
1188
+ }
1189
+ /**
1190
+ * True when a sequence gap was detected and the consumer should
1191
+ * resync from a snapshot before pushing further events.
1192
+ */
1193
+ get needsResync() {
1194
+ return this.#resync;
1195
+ }
1196
+ }
1197
+ /**
1198
+ * Batch fold. Returns the folded result AND the resync signal — a parked fold
1199
+ * is never a silent truncation (audit M50; INV-SEQ: "a conformant reducer MUST
1200
+ * expose its resync condition to the caller").
1201
+ */
1202
+ export function reduce(events) {
1203
+ const r = new Reducer();
1204
+ for (const ev of events) {
1205
+ r.push(ev);
1206
+ }
1207
+ return { result: r.result(), needsResync: r.needsResync };
1208
+ }
1209
+ //# sourceMappingURL=reduce.js.map