causa-kernel 0.0.1

Causa kernel — primitive facts (ContextBlock) and behavior contracts (ports)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! TurnContext / ContextFrame / TurnSnapshot — the turn fact machine.
use crate::context::block::{
    BlockContent, BlockMeta, ContentPart, ContextBlock, TextPayload, ToolCallPayload,
};
use crate::context::ids::{
    BlockId, BlockSequence, ContextVersion, ConversationId, FrameId, FrameScope, RoundId, TurnId,
};
use crate::context::model::{ModelResponse, ModelStopReason};
use crate::context::tool_data::{ToolCallId, ToolResultPayload};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::{HashMap, HashSet};

// --- TurnContext <-> TurnSnapshot serde bridge -----------------------------
//
// `TurnContext` is the in-memory mutable fact machine; it does not derive
// `Serialize` because a live active turn is not a stable wire payload. Once
// a turn is sealed, `TurnContext::snapshot()` returns an immutable
// `TurnSnapshot` projection that IS `Serialize`.
//
// These helpers let `TurnOutcome` and `ConversationState` derive
// `Serialize, Deserialize` directly, while routing only the `TurnContext`
// fields through this projection via
// `#[serde(with = "turn_context_as_snapshot")]`. On the wire the field
// looks like a `TurnSnapshot`; on reload it rebuilds a sealed `TurnContext`
// via `from_validated_blocks`.

// The canonical driver lives outside the kernel (causa_runtime), so this
// serde bridge is part of the external-driver contract surface.
/// Serde bridge: a `TurnContext` is serialized as its immutable
/// `TurnSnapshot` projection and rebuilt from that shape on load. The wire
/// representation of the field is always a `TurnSnapshot`.
pub mod turn_context_as_snapshot {
    use super::*;

    /// Serializes the context's snapshot projection.
    pub fn serialize<S: Serializer>(value: &TurnContext, s: S) -> Result<S::Ok, S::Error> {
        TurnSnapshot::serialize(&value.snapshot(), s)
    }

    /// Deserializes a `TurnSnapshot` and rebuilds a validated `TurnContext`,
    /// re-sealing it if the snapshot was sealed.
    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<TurnContext, D::Error> {
        let snap = TurnSnapshot::deserialize(d)?;
        let mut ctx = TurnContext::from_validated_blocks(
            snap.turn_id,
            snap.blocks.into_inner(),
            snap.source_version,
        )
        .map_err(serde::de::Error::custom)?;
        if snap.sealed {
            ctx.seal();
        }
        Ok(ctx)
    }
}

/// Serde bridge for `Option<TurnContext>` fields (the session aggregate's
/// active slot): `Some` serializes as the snapshot projection, `None` as
/// null. The session aggregate lives in `causa-runtime` and serializes its
/// active slot through this bridge.
pub mod option_turn_context_as_snapshot {
    use super::*;

    /// Serializes `Some` as the snapshot projection, `None` as null.
    pub fn serialize<S: Serializer>(value: &Option<TurnContext>, s: S) -> Result<S::Ok, S::Error> {
        match value {
            Some(ctx) => turn_context_as_snapshot::serialize(ctx, s),
            None => s.serialize_none(),
        }
    }

    /// Deserializes `null` as `None`, otherwise rebuilds a validated
    /// (re-sealed) `TurnContext`.
    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<TurnContext>, D::Error> {
        let opt: Option<TurnSnapshot> = Option::deserialize(d)?;
        opt.map(|snap| {
            let mut ctx = TurnContext::from_validated_blocks(
                snap.turn_id,
                snap.blocks.into_inner(),
                snap.source_version,
            )
            .map_err(serde::de::Error::custom)?;
            if snap.sealed {
                ctx.seal();
            }
            Ok(ctx)
        })
        .transpose()
    }
}

/// Whether a turn still accepts appends or is terminal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TurnLifecycle {
    /// The turn accepts appends through the three doors.
    Open,
    /// Terminal; every append operation is rejected.
    Sealed,
}

/// The model-facing context of a frame: the ordered fact blocks a round saw.
#[derive(Debug, Clone)]
pub struct ModelContext {
    /// The ordered fact blocks that make up the model context.
    pub blocks: Vec<ContextBlock>,
}

/// One deterministic projection of fact state handed to (or from) a model
/// round: identity, scope, the round it belongs to, and the block content.
#[derive(Debug, Clone)]
pub struct ContextFrame {
    /// Deterministic digest of the scope and round (see `FrameId::from_scope`).
    pub frame_id: FrameId,
    /// What this frame projects: the single turn or the merged conversation.
    pub scope: FrameScope,
    /// The model round this frame was built for.
    pub round_id: RoundId,
    /// The ordered blocks presented to the model.
    pub model_context: ModelContext,
}

/// Fact-machine rejections: lifecycle, pairing, or structural-validity
/// violations. None carry transport or execution semantics.
#[derive(Debug, thiserror::Error)]
pub enum ContextError {
    /// The turn is sealed and rejects appends.
    #[error("sealed turn")]
    SealedTurn,
    /// A model output was submitted under a different turn id than the
    /// context's own.
    #[error("foreign invocation: expected turn {expected:?}, got {actual:?}")]
    ForeignInvocation {
        /// The turn id the context was built with.
        expected: TurnId,
        /// The turn id carried by the offending invocation.
        actual: TurnId,
    },
    /// The model response is structurally invalid (bad stop-reason/tool-call
    /// pairing, empty tool name, or non-object arguments).
    #[error("invalid model output: {0}")]
    InvalidModelOutput(String),
    /// Sequence or pairing state is invalid (monotonicity, duplicate or
    /// already-paired tool results).
    #[error("invalid sequence: {0}")]
    InvalidSequence(String),
    /// A tool call id already exists in the fact state.
    #[error("duplicate tool call id: {0:?}")]
    DuplicateToolCallId(crate::context::tool_data::ToolCallId),
    /// A tool result references a call id no committed call block issued.
    #[error("unpaired tool result: {0:?}")]
    UnpairedToolResult(crate::context::tool_data::ToolCallId),
}

/// Receipt of the model door: the committed fact block ids plus the prepared
/// tool calls in model draft order. The tool calls are the execution handoff —
/// call ids are generated exactly once, here, so the driver dispatches the
/// same payloads the kernel committed and never re-reads blocks.
#[derive(Debug, Clone)]
pub struct AppliedModelOutput {
    /// Ids of the fact blocks committed for this output, in commit order.
    pub block_ids: Vec<BlockId>,
    /// The prepared tool calls with kernel-generated ids, in model draft
    /// order; the execution handoff.
    pub tool_calls: Vec<ToolCallPayload>,
}

/// The fact machine's block log: append-only and order-preserving.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OrderedBlocks(Vec<ContextBlock>);
impl OrderedBlocks {
    /// Creates an empty log.
    pub fn empty() -> Self {
        Self(Vec::new())
    }
    /// Borrows the ordered blocks.
    pub fn as_slice(&self) -> &[ContextBlock] {
        &self.0
    }
    /// Consumes the log, returning the ordered blocks.
    pub fn into_inner(self) -> Vec<ContextBlock> {
        self.0
    }
}

/// Current turn's ordered fact state. All mutation goes through the three
/// controlled doors (`append_input` / `append_model_output` /
/// `append_tool_results`) plus `seal`; there is no second `&mut` seam —
/// fields are private by design. The only projection the fact machine offers
/// is the lossless `frame()`; policy-shaped materialization lives in
/// `causa_runtime::budget::FramePolicy::materialize`, so context never
/// depends on harness policy and never awaits behavior.
#[derive(Clone)]
pub struct TurnContext {
    turn_id: TurnId,
    blocks: OrderedBlocks,
    version: ContextVersion,
    lifecycle: TurnLifecycle,
    next_seq: u64,
}

impl std::fmt::Debug for TurnContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TurnContext")
            .field("turn_id", &self.turn_id)
            .field("version", &self.version)
            .field("lifecycle", &self.lifecycle)
            .field("blocks_len", &self.blocks.0.len())
            .field("next_seq", &self.next_seq)
            .finish()
    }
}

impl TurnContext {
    /// Creates an empty, open turn with version 0.
    pub fn new(turn_id: TurnId) -> Self {
        Self {
            turn_id,
            blocks: OrderedBlocks::empty(),
            version: ContextVersion(0),
            lifecycle: TurnLifecycle::Open,
            next_seq: 0,
        }
    }

    /// Returns whether the turn has been sealed.
    pub fn is_sealed(&self) -> bool {
        matches!(self.lifecycle, TurnLifecycle::Sealed)
    }
    /// Borrows the committed fact blocks in commit order.
    pub fn blocks(&self) -> &[ContextBlock] {
        &self.blocks.0
    }
    /// Returns the current `ContextVersion` (count of canonical fact commits).
    pub fn version(&self) -> ContextVersion {
        self.version
    }
    /// Returns the turn's id.
    pub fn turn_id(&self) -> TurnId {
        self.turn_id.clone()
    }
    /// Returns the current lifecycle state.
    pub fn lifecycle(&self) -> TurnLifecycle {
        self.lifecycle
    }
    /// Returns an owned copy of the committed blocks in commit order.
    pub fn snapshot_blocks(&self) -> Vec<ContextBlock> {
        self.blocks.0.clone()
    }

    /// Host door: admit one single-text message — the one-part sugar over
    /// [`TurnContext::append_parts`]. The kernel does not interpret the
    /// source label; role assignment is the renderer's job.
    pub fn append_input(
        &mut self,
        text: TextPayload,
        source: impl Into<String>,
    ) -> Result<BlockId, ContextError> {
        self.append_parts(vec![ContentPart::Text(text)], source)
    }

    /// Host door for one logical message's mixed content (caption + media,
    /// multi-image, text runs): the ordered parts commit as ONE fact block.
    /// Atomic — all-or-nothing validation, exactly one version bump,
    /// contiguous sequences. Stamps `source` verbatim on the envelope.
    /// Empty parts are rejected; media parts carry references only.
    pub fn append_parts(
        &mut self,
        parts: Vec<ContentPart>,
        source: impl Into<String>,
    ) -> Result<BlockId, ContextError> {
        self.ensure_open()?;
        if parts.is_empty() {
            return Err(ContextError::InvalidSequence(
                "append_parts: empty parts are not a fact".into(),
            ));
        }
        let meta = BlockMeta {
            source: Some(source.into()),
            ..BlockMeta::default()
        };
        let mut ids = self.commit_blocks(vec![(BlockContent::Parts(parts), meta)]);
        Ok(ids.pop().expect("single-block commit yields one id"))
    }

    /// Model door: record the model's response as facts. Borrows the response
    /// so the caller keeps the envelope for its own traces; usage and
    /// reasoning are deliberately caller-retained and never enter the fact
    /// state. Tool call ids are generated exactly once and returned in the
    /// receipt as the execution handoff.
    pub fn append_model_output(
        &mut self,
        invocation: crate::context::ids::InvocationId,
        response: &ModelResponse,
        stop_reason: ModelStopReason,
    ) -> Result<AppliedModelOutput, ContextError> {
        self.ensure_open()?;
        if invocation.turn_id != self.turn_id {
            return Err(ContextError::ForeignInvocation {
                expected: self.turn_id.clone(),
                actual: invocation.turn_id.clone(),
            });
        }
        // Structural validation only — any stop reason is recordable as
        // facts; interpreting terminal reasons (e.g. interrupting on
        // MaxTokens/Refusal) is driver policy above the kernel.
        match stop_reason {
            ModelStopReason::EndTurn if !response.tool_calls.is_empty() => {
                return Err(ContextError::InvalidModelOutput(
                    "EndTurn must have empty tool_calls".into(),
                ));
            }
            ModelStopReason::ToolUse if response.tool_calls.is_empty() => {
                return Err(ContextError::InvalidModelOutput(
                    "ToolUse must have non-empty tool_calls".into(),
                ));
            }
            _ => {}
        }
        // Prepare everything before committing anything: text (when
        // non-empty), then one call payload per draft with its id generated
        // exactly once. Nothing touches the fact state until `commit_blocks`.
        let mut prepared: Vec<(BlockContent, BlockMeta)> = Vec::new();
        let mut tool_calls: Vec<ToolCallPayload> = Vec::new();
        if !response.text.0.trim().is_empty() {
            prepared.push((
                BlockContent::Parts(vec![ContentPart::Text(TextPayload(
                    response.text.0.clone(),
                ))]),
                BlockMeta::default(),
            ));
        }
        // No intra-batch seen-set: ids embed the draft position, so two
        // drafts at distinct positions cannot collide. The committed-block
        // scan below defends the real collision surface — the 32-bit
        // hash-prefix on the cross-round recovery path.
        for (pos, draft) in response.tool_calls.iter().enumerate() {
            if draft.tool_name.trim().is_empty() {
                return Err(ContextError::InvalidModelOutput("tool_name empty".into()));
            }
            if !draft.arguments.is_object() {
                return Err(ContextError::InvalidModelOutput(
                    "arguments must be object".into(),
                ));
            }
            let call_id =
                ToolCallId::generate(invocation.round_id, &draft.tool_name, &draft.arguments, pos);
            for b in &self.blocks.0 {
                if let BlockContent::ToolCall(tc) = &b.content
                    && tc.call_id == call_id
                {
                    return Err(ContextError::DuplicateToolCallId(call_id));
                }
            }
            let payload = ToolCallPayload {
                call_id: call_id.clone(),
                tool_name: draft.tool_name.clone(),
                arguments: draft.arguments.clone(),
            };
            tool_calls.push(payload.clone());
            // `provider_call_id` rides on the envelope `BlockMeta`; pairing
            // stays on the kernel-generated `call_id`.
            prepared.push((
                BlockContent::ToolCall(payload),
                BlockMeta {
                    provider_call_id: draft.provider_call_id.clone(),
                    ..BlockMeta::default()
                },
            ));
        }
        let block_ids = self.commit_blocks(prepared);
        Ok(AppliedModelOutput {
            block_ids,
            tool_calls,
        })
    }

    /// Tool door: commit tool results. Canonical commit order is the paired
    /// call's block order (the model's original draft order), so two drivers
    /// submitting the same logical results in different completion orders
    /// produce identical snapshots. Batch completeness is runner policy; the
    /// kernel enforces pairing only.
    pub fn append_tool_results(
        &mut self,
        results: Vec<ToolResultPayload>,
    ) -> Result<Vec<BlockId>, ContextError> {
        self.ensure_open()?;
        if results.is_empty() {
            return Ok(vec![]);
        }
        // Pairing state from committed facts: each call's block sequence and
        // the set of already-paired calls.
        let mut call_seq: HashMap<ToolCallId, BlockSequence> = HashMap::new();
        let mut paired: HashSet<ToolCallId> = HashSet::new();
        for b in &self.blocks.0 {
            match &b.content {
                BlockContent::ToolCall(tc) => {
                    call_seq.insert(tc.call_id.clone(), b.sequence);
                }
                BlockContent::ToolResult(tr) => {
                    paired.insert(tr.call_id.clone());
                }
                _ => {}
            }
        }
        // Validate all results atomically, then commit in canonical order.
        let mut batch: HashSet<ToolCallId> = HashSet::new();
        let mut ordered: Vec<(BlockSequence, &ToolResultPayload)> = Vec::new();
        for r in &results {
            let seq = match call_seq.get(&r.call_id) {
                Some(seq) => *seq,
                None => return Err(ContextError::UnpairedToolResult(r.call_id.clone())),
            };
            if paired.contains(&r.call_id) {
                return Err(ContextError::InvalidSequence(format!(
                    "tool call already paired: {:?}",
                    r.call_id
                )));
            }
            if !batch.insert(r.call_id.clone()) {
                return Err(ContextError::InvalidSequence(format!(
                    "duplicate tool result in batch: {:?}",
                    r.call_id
                )));
            }
            ordered.push((seq, r));
        }
        ordered.sort_by_key(|(seq, _)| *seq);
        let prepared = ordered
            .into_iter()
            .map(|(_, r)| {
                (
                    BlockContent::ToolResult(ToolResultPayload {
                        call_id: r.call_id.clone(),
                        status: r.status.clone(),
                        output: r.output.clone(),
                        media: r.media.clone(),
                    }),
                    BlockMeta::default(),
                )
            })
            .collect();
        Ok(self.commit_blocks(prepared))
    }

    /// Lossless canonical projection: the committed facts, ordered, with the
    /// deterministic frame identity. Frame-materialization policy (budget,
    /// compaction) is NOT applied here — the fact machine never awaits
    /// behavior; the execution stack materializes policy-shaped frames
    /// through `causa_runtime::budget::FramePolicy::materialize`, which
    /// replaces only this frame's block list.
    pub fn frame(&self, round_id: RoundId) -> ContextFrame {
        self.frame_with(round_id, self.blocks.0.clone())
    }

    /// Crate-only: the same Turn-scope projection over an explicit block
    /// list — the single home of the frame-identity construction.
    pub(crate) fn frame_with(&self, round_id: RoundId, blocks: Vec<ContextBlock>) -> ContextFrame {
        let frame_id =
            crate::context::ids::FrameId::deterministic(&self.turn_id, self.version, round_id);
        ContextFrame {
            frame_id,
            scope: FrameScope::Turn {
                turn_id: self.turn_id.clone(),
                source_version: self.version,
            },
            round_id,
            model_context: ModelContext { blocks },
        }
    }

    /// Terminal lifecycle transition, owned by the driver: seal when the turn
    /// is over. Sealed turns reject every append operation; the kernel
    /// guarantees no post-terminal mutation. Conversation-level history
    /// eligibility is a driver stamp, not this marker.
    pub fn seal(&mut self) {
        self.lifecycle = TurnLifecycle::Sealed;
    }

    fn ensure_open(&self) -> Result<(), ContextError> {
        if self.is_sealed() {
            Err(ContextError::SealedTurn)
        } else {
            Ok(())
        }
    }

    /// The single commit primitive: write prepared blocks, then bump the
    /// version exactly once iff the commit is non-empty. `ContextVersion`
    /// counts canonical fact commits — no-ops (empty output, empty results,
    /// failed validation, retries, compaction) leave it untouched.
    fn commit_blocks(&mut self, prepared: Vec<(BlockContent, BlockMeta)>) -> Vec<BlockId> {
        if prepared.is_empty() {
            return Vec::new();
        }
        let mut ids = Vec::with_capacity(prepared.len());
        for (content, meta) in prepared {
            ids.push(self.push_block(content, meta));
        }
        self.version = self.version.next();
        ids
    }

    fn push_block(&mut self, content: BlockContent, meta: BlockMeta) -> BlockId {
        let seq = BlockSequence(self.next_seq);
        let id = BlockId {
            turn_id: self.turn_id.clone(),
            sequence: seq,
        };
        let block = ContextBlock {
            id: id.clone(),
            sequence: seq,
            content,
            meta,
        };
        self.blocks.0.push(block);
        self.next_seq += 1;
        id
    }

    /// Rebuilds an open turn from a validated block log — the reload path
    /// behind the serde bridge. Sequence monotonicity, id agreement, and
    /// tool pairing are validated before construction; the next sequence
    /// continues densely after the given blocks.
    pub fn from_validated_blocks(
        turn_id: TurnId,
        blocks: Vec<ContextBlock>,
        version: ContextVersion,
    ) -> Result<Self, ContextError> {
        Self::validate_blocks(&turn_id, &blocks)?;
        let next_seq = blocks.len() as u64;
        Ok(Self {
            turn_id,
            blocks: OrderedBlocks(blocks),
            version,
            lifecycle: TurnLifecycle::Open,
            next_seq,
        })
    }

    /// The structural validation behind `from_validated_blocks`, callable
    /// without constructing a throwaway machine — replay paths validate
    /// snapshots in place. The runtime's session replay
    /// (`ConversationState::from_history`) also validates committed snapshots
    /// through this entry, so every reload path shares one validator.
    pub fn validate_blocks(turn_id: &TurnId, blocks: &[ContextBlock]) -> Result<(), ContextError> {
        // validate monotonic sequence and turn_id matching
        for (idx, b) in blocks.iter().enumerate() {
            if b.id.turn_id != *turn_id {
                return Err(ContextError::InvalidSequence(format!(
                    "block turn_id mismatch at {}",
                    idx
                )));
            }
            if b.sequence.0 != idx as u64 {
                return Err(ContextError::InvalidSequence(format!(
                    "block sequence not monotonic at {} expected {} got {}",
                    idx, idx, b.sequence.0
                )));
            }
            if b.id.sequence != b.sequence {
                return Err(ContextError::InvalidSequence(format!(
                    "block id sequence mismatch at {}",
                    idx
                )));
            }
        }
        // validate tool pairing: no duplicate call ids, every result paired
        let mut call_set = HashSet::new();
        let mut seen_results = HashSet::new();
        for b in blocks {
            match &b.content {
                BlockContent::Parts(parts) => {
                    if parts.is_empty() {
                        return Err(ContextError::InvalidSequence("empty parts block".into()));
                    }
                }
                BlockContent::ToolCall(tc) => {
                    if !call_set.insert(tc.call_id.clone()) {
                        return Err(ContextError::DuplicateToolCallId(tc.call_id.clone()));
                    }
                }
                BlockContent::ToolResult(tr) => {
                    if !call_set.contains(&tr.call_id) {
                        return Err(ContextError::UnpairedToolResult(tr.call_id.clone()));
                    }
                    if !seen_results.insert(tr.call_id.clone()) {
                        return Err(ContextError::InvalidSequence(format!(
                            "duplicate tool result for {:?}",
                            tr.call_id
                        )));
                    }
                }
            }
        }
        Ok(())
    }

    /// Projects the current state into an immutable `TurnSnapshot` — the
    /// canonical wire shape for persistence. Session ordering is NOT part of
    /// the snapshot: the runtime's session aggregate assigns the
    /// `HistoryEntry` sequence at commit.
    pub fn snapshot(&self) -> TurnSnapshot {
        TurnSnapshot {
            turn_id: self.turn_id.clone(),
            blocks: self.blocks.clone(),
            source_version: self.version,
            sealed: self.is_sealed(),
        }
    }
}

fn default_sealed() -> bool {
    true
}

/// Immutable, serializable projection of a turn — the canonical wire shape
/// for a persisted turn (a live `TurnContext` is never serialized directly).
/// The snapshot describes the record itself only: identity, blocks, fact
/// version, and write lifecycle. Session ordering lives in the runtime's
/// `HistoryEntry`, not here.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TurnSnapshot {
    /// Identity of the snapshotted turn.
    pub turn_id: TurnId,
    /// The committed blocks, in commit order.
    pub blocks: OrderedBlocks,
    /// The turn's `ContextVersion` at snapshot time.
    pub source_version: ContextVersion,
    /// Whether the turn was sealed when snapshotted. A *paused* turn
    /// snapshots as `false` so a persisted conversation reloads with the
    /// active turn still open and resumable. Serde-additive: an absent field
    /// defaults to `true` (only sealed turns have a wire snapshot).
    #[serde(default = "default_sealed")]
    pub sealed: bool,
}

/// Shared lossless merged materialization over committed history plus the
/// active turn — the single semantics both the runtime's
/// `ConversationState::frame()` and any external conversation driver's
/// merged-view entry use. The session aggregate that calls it lives in
/// `causa-runtime`, but the projection itself is common frame vocabulary and
/// stays with the facts. No reordering, no dedup, no trimming; nothing is
/// written back.
pub fn merged_frame(
    conversation_id: &ConversationId,
    history: &[TurnSnapshot],
    active: &TurnContext,
    round_id: RoundId,
) -> ContextFrame {
    let mut blocks = Vec::new();
    for snapshot in history {
        blocks.extend(snapshot.blocks.as_slice().iter().cloned());
    }
    blocks.extend(active.blocks().iter().cloned());
    let scope = FrameScope::Conversation {
        conversation_id: conversation_id.clone(),
        active_turn_id: active.turn_id(),
        source_version: active.version(),
    };
    ContextFrame {
        frame_id: FrameId::from_scope(&scope, round_id),
        scope,
        round_id,
        model_context: ModelContext { blocks },
    }
}