Skip to main content

causa_kernel/context/
turn.rs

1//! TurnContext / ContextFrame / TurnSnapshot — the turn fact machine.
2use crate::context::block::{
3    BlockContent, BlockMeta, ContentPart, ContextBlock, TextPayload, ToolCallPayload,
4};
5use crate::context::ids::{
6    BlockId, BlockSequence, ContextVersion, ConversationId, FrameId, FrameScope, RoundId, TurnId,
7};
8use crate::context::model::{ModelResponse, ModelStopReason};
9use crate::context::tool_data::{ToolCallId, ToolResultPayload};
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11use std::collections::{HashMap, HashSet};
12
13// --- TurnContext <-> TurnSnapshot serde bridge -----------------------------
14//
15// `TurnContext` is the in-memory mutable fact machine; it does not derive
16// `Serialize` because a live active turn is not a stable wire payload. Once
17// a turn is sealed, `TurnContext::snapshot()` returns an immutable
18// `TurnSnapshot` projection that IS `Serialize`.
19//
20// These helpers let `TurnOutcome` and `ConversationState` derive
21// `Serialize, Deserialize` directly, while routing only the `TurnContext`
22// fields through this projection via
23// `#[serde(with = "turn_context_as_snapshot")]`. On the wire the field
24// looks like a `TurnSnapshot`; on reload it rebuilds a sealed `TurnContext`
25// via `from_validated_blocks`.
26
27// The canonical driver lives outside the kernel (causa_runtime), so this
28// serde bridge is part of the external-driver contract surface.
29/// Serde bridge: a `TurnContext` is serialized as its immutable
30/// `TurnSnapshot` projection and rebuilt from that shape on load. The wire
31/// representation of the field is always a `TurnSnapshot`.
32pub mod turn_context_as_snapshot {
33    use super::*;
34
35    /// Serializes the context's snapshot projection.
36    pub fn serialize<S: Serializer>(value: &TurnContext, s: S) -> Result<S::Ok, S::Error> {
37        TurnSnapshot::serialize(&value.snapshot(), s)
38    }
39
40    /// Deserializes a `TurnSnapshot` and rebuilds a validated `TurnContext`,
41    /// re-sealing it if the snapshot was sealed.
42    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<TurnContext, D::Error> {
43        let snap = TurnSnapshot::deserialize(d)?;
44        let mut ctx = TurnContext::from_validated_blocks(
45            snap.turn_id,
46            snap.blocks.into_inner(),
47            snap.source_version,
48        )
49        .map_err(serde::de::Error::custom)?;
50        if snap.sealed {
51            ctx.seal();
52        }
53        Ok(ctx)
54    }
55}
56
57/// Serde bridge for `Option<TurnContext>` fields (the session aggregate's
58/// active slot): `Some` serializes as the snapshot projection, `None` as
59/// null. The session aggregate lives in `causa-runtime` and serializes its
60/// active slot through this bridge.
61pub mod option_turn_context_as_snapshot {
62    use super::*;
63
64    /// Serializes `Some` as the snapshot projection, `None` as null.
65    pub fn serialize<S: Serializer>(value: &Option<TurnContext>, s: S) -> Result<S::Ok, S::Error> {
66        match value {
67            Some(ctx) => turn_context_as_snapshot::serialize(ctx, s),
68            None => s.serialize_none(),
69        }
70    }
71
72    /// Deserializes `null` as `None`, otherwise rebuilds a validated
73    /// (re-sealed) `TurnContext`.
74    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<TurnContext>, D::Error> {
75        let opt: Option<TurnSnapshot> = Option::deserialize(d)?;
76        opt.map(|snap| {
77            let mut ctx = TurnContext::from_validated_blocks(
78                snap.turn_id,
79                snap.blocks.into_inner(),
80                snap.source_version,
81            )
82            .map_err(serde::de::Error::custom)?;
83            if snap.sealed {
84                ctx.seal();
85            }
86            Ok(ctx)
87        })
88        .transpose()
89    }
90}
91
92/// Whether a turn still accepts appends or is terminal.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum TurnLifecycle {
95    /// The turn accepts appends through the three doors.
96    Open,
97    /// Terminal; every append operation is rejected.
98    Sealed,
99}
100
101/// The model-facing context of a frame: the ordered fact blocks a round saw.
102#[derive(Debug, Clone)]
103pub struct ModelContext {
104    /// The ordered fact blocks that make up the model context.
105    pub blocks: Vec<ContextBlock>,
106}
107
108/// One deterministic projection of fact state handed to (or from) a model
109/// round: identity, scope, the round it belongs to, and the block content.
110#[derive(Debug, Clone)]
111pub struct ContextFrame {
112    /// Deterministic digest of the scope and round (see `FrameId::from_scope`).
113    pub frame_id: FrameId,
114    /// What this frame projects: the single turn or the merged conversation.
115    pub scope: FrameScope,
116    /// The model round this frame was built for.
117    pub round_id: RoundId,
118    /// The ordered blocks presented to the model.
119    pub model_context: ModelContext,
120}
121
122/// Fact-machine rejections: lifecycle, pairing, or structural-validity
123/// violations. None carry transport or execution semantics.
124#[derive(Debug, thiserror::Error)]
125pub enum ContextError {
126    /// The turn is sealed and rejects appends.
127    #[error("sealed turn")]
128    SealedTurn,
129    /// A model output was submitted under a different turn id than the
130    /// context's own.
131    #[error("foreign invocation: expected turn {expected:?}, got {actual:?}")]
132    ForeignInvocation {
133        /// The turn id the context was built with.
134        expected: TurnId,
135        /// The turn id carried by the offending invocation.
136        actual: TurnId,
137    },
138    /// The model response is structurally invalid (bad stop-reason/tool-call
139    /// pairing, empty tool name, or non-object arguments).
140    #[error("invalid model output: {0}")]
141    InvalidModelOutput(String),
142    /// Sequence or pairing state is invalid (monotonicity, duplicate or
143    /// already-paired tool results).
144    #[error("invalid sequence: {0}")]
145    InvalidSequence(String),
146    /// A tool call id already exists in the fact state.
147    #[error("duplicate tool call id: {0:?}")]
148    DuplicateToolCallId(crate::context::tool_data::ToolCallId),
149    /// A tool result references a call id no committed call block issued.
150    #[error("unpaired tool result: {0:?}")]
151    UnpairedToolResult(crate::context::tool_data::ToolCallId),
152}
153
154/// Receipt of the model door: the committed fact block ids plus the prepared
155/// tool calls in model draft order. The tool calls are the execution handoff —
156/// call ids are generated exactly once, here, so the driver dispatches the
157/// same payloads the kernel committed and never re-reads blocks.
158#[derive(Debug, Clone)]
159pub struct AppliedModelOutput {
160    /// Ids of the fact blocks committed for this output, in commit order.
161    pub block_ids: Vec<BlockId>,
162    /// The prepared tool calls with kernel-generated ids, in model draft
163    /// order; the execution handoff.
164    pub tool_calls: Vec<ToolCallPayload>,
165}
166
167/// The fact machine's block log: append-only and order-preserving.
168#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
169pub struct OrderedBlocks(Vec<ContextBlock>);
170impl OrderedBlocks {
171    /// Creates an empty log.
172    pub fn empty() -> Self {
173        Self(Vec::new())
174    }
175    /// Borrows the ordered blocks.
176    pub fn as_slice(&self) -> &[ContextBlock] {
177        &self.0
178    }
179    /// Consumes the log, returning the ordered blocks.
180    pub fn into_inner(self) -> Vec<ContextBlock> {
181        self.0
182    }
183}
184
185/// Current turn's ordered fact state. All mutation goes through the three
186/// controlled doors (`append_input` / `append_model_output` /
187/// `append_tool_results`) plus `seal`; there is no second `&mut` seam —
188/// fields are private by design. The only projection the fact machine offers
189/// is the lossless `frame()`; policy-shaped materialization lives in
190/// `causa_runtime::budget::FramePolicy::materialize`, so context never
191/// depends on harness policy and never awaits behavior.
192#[derive(Clone)]
193pub struct TurnContext {
194    turn_id: TurnId,
195    blocks: OrderedBlocks,
196    version: ContextVersion,
197    lifecycle: TurnLifecycle,
198    next_seq: u64,
199}
200
201impl std::fmt::Debug for TurnContext {
202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203        f.debug_struct("TurnContext")
204            .field("turn_id", &self.turn_id)
205            .field("version", &self.version)
206            .field("lifecycle", &self.lifecycle)
207            .field("blocks_len", &self.blocks.0.len())
208            .field("next_seq", &self.next_seq)
209            .finish()
210    }
211}
212
213impl TurnContext {
214    /// Creates an empty, open turn with version 0.
215    pub fn new(turn_id: TurnId) -> Self {
216        Self {
217            turn_id,
218            blocks: OrderedBlocks::empty(),
219            version: ContextVersion(0),
220            lifecycle: TurnLifecycle::Open,
221            next_seq: 0,
222        }
223    }
224
225    /// Returns whether the turn has been sealed.
226    pub fn is_sealed(&self) -> bool {
227        matches!(self.lifecycle, TurnLifecycle::Sealed)
228    }
229    /// Borrows the committed fact blocks in commit order.
230    pub fn blocks(&self) -> &[ContextBlock] {
231        &self.blocks.0
232    }
233    /// Returns the current `ContextVersion` (count of canonical fact commits).
234    pub fn version(&self) -> ContextVersion {
235        self.version
236    }
237    /// Returns the turn's id.
238    pub fn turn_id(&self) -> TurnId {
239        self.turn_id.clone()
240    }
241    /// Returns the current lifecycle state.
242    pub fn lifecycle(&self) -> TurnLifecycle {
243        self.lifecycle
244    }
245    /// Returns an owned copy of the committed blocks in commit order.
246    pub fn snapshot_blocks(&self) -> Vec<ContextBlock> {
247        self.blocks.0.clone()
248    }
249
250    /// Host door: admit one single-text message — the one-part sugar over
251    /// [`TurnContext::append_parts`]. The kernel does not interpret the
252    /// source label; role assignment is the renderer's job.
253    pub fn append_input(
254        &mut self,
255        text: TextPayload,
256        source: impl Into<String>,
257    ) -> Result<BlockId, ContextError> {
258        self.append_parts(vec![ContentPart::Text(text)], source)
259    }
260
261    /// Host door for one logical message's mixed content (caption + media,
262    /// multi-image, text runs): the ordered parts commit as ONE fact block.
263    /// Atomic — all-or-nothing validation, exactly one version bump,
264    /// contiguous sequences. Stamps `source` verbatim on the envelope.
265    /// Empty parts are rejected; media parts carry references only.
266    pub fn append_parts(
267        &mut self,
268        parts: Vec<ContentPart>,
269        source: impl Into<String>,
270    ) -> Result<BlockId, ContextError> {
271        self.ensure_open()?;
272        if parts.is_empty() {
273            return Err(ContextError::InvalidSequence(
274                "append_parts: empty parts are not a fact".into(),
275            ));
276        }
277        let meta = BlockMeta {
278            source: Some(source.into()),
279            ..BlockMeta::default()
280        };
281        let mut ids = self.commit_blocks(vec![(BlockContent::Parts(parts), meta)]);
282        Ok(ids.pop().expect("single-block commit yields one id"))
283    }
284
285    /// Model door: record the model's response as facts. Borrows the response
286    /// so the caller keeps the envelope for its own traces; usage and
287    /// reasoning are deliberately caller-retained and never enter the fact
288    /// state. Tool call ids are generated exactly once and returned in the
289    /// receipt as the execution handoff.
290    pub fn append_model_output(
291        &mut self,
292        invocation: crate::context::ids::InvocationId,
293        response: &ModelResponse,
294        stop_reason: ModelStopReason,
295    ) -> Result<AppliedModelOutput, ContextError> {
296        self.ensure_open()?;
297        if invocation.turn_id != self.turn_id {
298            return Err(ContextError::ForeignInvocation {
299                expected: self.turn_id.clone(),
300                actual: invocation.turn_id.clone(),
301            });
302        }
303        // Structural validation only — any stop reason is recordable as
304        // facts; interpreting terminal reasons (e.g. interrupting on
305        // MaxTokens/Refusal) is driver policy above the kernel.
306        match stop_reason {
307            ModelStopReason::EndTurn if !response.tool_calls.is_empty() => {
308                return Err(ContextError::InvalidModelOutput(
309                    "EndTurn must have empty tool_calls".into(),
310                ));
311            }
312            ModelStopReason::ToolUse if response.tool_calls.is_empty() => {
313                return Err(ContextError::InvalidModelOutput(
314                    "ToolUse must have non-empty tool_calls".into(),
315                ));
316            }
317            _ => {}
318        }
319        // Prepare everything before committing anything: text (when
320        // non-empty), then one call payload per draft with its id generated
321        // exactly once. Nothing touches the fact state until `commit_blocks`.
322        let mut prepared: Vec<(BlockContent, BlockMeta)> = Vec::new();
323        let mut tool_calls: Vec<ToolCallPayload> = Vec::new();
324        if !response.text.0.trim().is_empty() {
325            prepared.push((
326                BlockContent::Parts(vec![ContentPart::Text(TextPayload(
327                    response.text.0.clone(),
328                ))]),
329                BlockMeta::default(),
330            ));
331        }
332        // No intra-batch seen-set: ids embed the draft position, so two
333        // drafts at distinct positions cannot collide. The committed-block
334        // scan below defends the real collision surface — the 32-bit
335        // hash-prefix on the cross-round recovery path.
336        for (pos, draft) in response.tool_calls.iter().enumerate() {
337            if draft.tool_name.trim().is_empty() {
338                return Err(ContextError::InvalidModelOutput("tool_name empty".into()));
339            }
340            if !draft.arguments.is_object() {
341                return Err(ContextError::InvalidModelOutput(
342                    "arguments must be object".into(),
343                ));
344            }
345            let call_id =
346                ToolCallId::generate(invocation.round_id, &draft.tool_name, &draft.arguments, pos);
347            for b in &self.blocks.0 {
348                if let BlockContent::ToolCall(tc) = &b.content
349                    && tc.call_id == call_id
350                {
351                    return Err(ContextError::DuplicateToolCallId(call_id));
352                }
353            }
354            let payload = ToolCallPayload {
355                call_id: call_id.clone(),
356                tool_name: draft.tool_name.clone(),
357                arguments: draft.arguments.clone(),
358            };
359            tool_calls.push(payload.clone());
360            // `provider_call_id` rides on the envelope `BlockMeta`; pairing
361            // stays on the kernel-generated `call_id`.
362            prepared.push((
363                BlockContent::ToolCall(payload),
364                BlockMeta {
365                    provider_call_id: draft.provider_call_id.clone(),
366                    ..BlockMeta::default()
367                },
368            ));
369        }
370        let block_ids = self.commit_blocks(prepared);
371        Ok(AppliedModelOutput {
372            block_ids,
373            tool_calls,
374        })
375    }
376
377    /// Tool door: commit tool results. Canonical commit order is the paired
378    /// call's block order (the model's original draft order), so two drivers
379    /// submitting the same logical results in different completion orders
380    /// produce identical snapshots. Batch completeness is runner policy; the
381    /// kernel enforces pairing only.
382    pub fn append_tool_results(
383        &mut self,
384        results: Vec<ToolResultPayload>,
385    ) -> Result<Vec<BlockId>, ContextError> {
386        self.ensure_open()?;
387        if results.is_empty() {
388            return Ok(vec![]);
389        }
390        // Pairing state from committed facts: each call's block sequence and
391        // the set of already-paired calls.
392        let mut call_seq: HashMap<ToolCallId, BlockSequence> = HashMap::new();
393        let mut paired: HashSet<ToolCallId> = HashSet::new();
394        for b in &self.blocks.0 {
395            match &b.content {
396                BlockContent::ToolCall(tc) => {
397                    call_seq.insert(tc.call_id.clone(), b.sequence);
398                }
399                BlockContent::ToolResult(tr) => {
400                    paired.insert(tr.call_id.clone());
401                }
402                _ => {}
403            }
404        }
405        // Validate all results atomically, then commit in canonical order.
406        let mut batch: HashSet<ToolCallId> = HashSet::new();
407        let mut ordered: Vec<(BlockSequence, &ToolResultPayload)> = Vec::new();
408        for r in &results {
409            let seq = match call_seq.get(&r.call_id) {
410                Some(seq) => *seq,
411                None => return Err(ContextError::UnpairedToolResult(r.call_id.clone())),
412            };
413            if paired.contains(&r.call_id) {
414                return Err(ContextError::InvalidSequence(format!(
415                    "tool call already paired: {:?}",
416                    r.call_id
417                )));
418            }
419            if !batch.insert(r.call_id.clone()) {
420                return Err(ContextError::InvalidSequence(format!(
421                    "duplicate tool result in batch: {:?}",
422                    r.call_id
423                )));
424            }
425            ordered.push((seq, r));
426        }
427        ordered.sort_by_key(|(seq, _)| *seq);
428        let prepared = ordered
429            .into_iter()
430            .map(|(_, r)| {
431                (
432                    BlockContent::ToolResult(ToolResultPayload {
433                        call_id: r.call_id.clone(),
434                        status: r.status.clone(),
435                        output: r.output.clone(),
436                        media: r.media.clone(),
437                    }),
438                    BlockMeta::default(),
439                )
440            })
441            .collect();
442        Ok(self.commit_blocks(prepared))
443    }
444
445    /// Lossless canonical projection: the committed facts, ordered, with the
446    /// deterministic frame identity. Frame-materialization policy (budget,
447    /// compaction) is NOT applied here — the fact machine never awaits
448    /// behavior; the execution stack materializes policy-shaped frames
449    /// through `causa_runtime::budget::FramePolicy::materialize`, which
450    /// replaces only this frame's block list.
451    pub fn frame(&self, round_id: RoundId) -> ContextFrame {
452        self.frame_with(round_id, self.blocks.0.clone())
453    }
454
455    /// Crate-only: the same Turn-scope projection over an explicit block
456    /// list — the single home of the frame-identity construction.
457    pub(crate) fn frame_with(&self, round_id: RoundId, blocks: Vec<ContextBlock>) -> ContextFrame {
458        let frame_id =
459            crate::context::ids::FrameId::deterministic(&self.turn_id, self.version, round_id);
460        ContextFrame {
461            frame_id,
462            scope: FrameScope::Turn {
463                turn_id: self.turn_id.clone(),
464                source_version: self.version,
465            },
466            round_id,
467            model_context: ModelContext { blocks },
468        }
469    }
470
471    /// Terminal lifecycle transition, owned by the driver: seal when the turn
472    /// is over. Sealed turns reject every append operation; the kernel
473    /// guarantees no post-terminal mutation. Conversation-level history
474    /// eligibility is a driver stamp, not this marker.
475    pub fn seal(&mut self) {
476        self.lifecycle = TurnLifecycle::Sealed;
477    }
478
479    fn ensure_open(&self) -> Result<(), ContextError> {
480        if self.is_sealed() {
481            Err(ContextError::SealedTurn)
482        } else {
483            Ok(())
484        }
485    }
486
487    /// The single commit primitive: write prepared blocks, then bump the
488    /// version exactly once iff the commit is non-empty. `ContextVersion`
489    /// counts canonical fact commits — no-ops (empty output, empty results,
490    /// failed validation, retries, compaction) leave it untouched.
491    fn commit_blocks(&mut self, prepared: Vec<(BlockContent, BlockMeta)>) -> Vec<BlockId> {
492        if prepared.is_empty() {
493            return Vec::new();
494        }
495        let mut ids = Vec::with_capacity(prepared.len());
496        for (content, meta) in prepared {
497            ids.push(self.push_block(content, meta));
498        }
499        self.version = self.version.next();
500        ids
501    }
502
503    fn push_block(&mut self, content: BlockContent, meta: BlockMeta) -> BlockId {
504        let seq = BlockSequence(self.next_seq);
505        let id = BlockId {
506            turn_id: self.turn_id.clone(),
507            sequence: seq,
508        };
509        let block = ContextBlock {
510            id: id.clone(),
511            sequence: seq,
512            content,
513            meta,
514        };
515        self.blocks.0.push(block);
516        self.next_seq += 1;
517        id
518    }
519
520    /// Rebuilds an open turn from a validated block log — the reload path
521    /// behind the serde bridge. Sequence monotonicity, id agreement, and
522    /// tool pairing are validated before construction; the next sequence
523    /// continues densely after the given blocks.
524    pub fn from_validated_blocks(
525        turn_id: TurnId,
526        blocks: Vec<ContextBlock>,
527        version: ContextVersion,
528    ) -> Result<Self, ContextError> {
529        Self::validate_blocks(&turn_id, &blocks)?;
530        let next_seq = blocks.len() as u64;
531        Ok(Self {
532            turn_id,
533            blocks: OrderedBlocks(blocks),
534            version,
535            lifecycle: TurnLifecycle::Open,
536            next_seq,
537        })
538    }
539
540    /// The structural validation behind `from_validated_blocks`, callable
541    /// without constructing a throwaway machine — replay paths validate
542    /// snapshots in place. The runtime's session replay
543    /// (`ConversationState::from_history`) also validates committed snapshots
544    /// through this entry, so every reload path shares one validator.
545    pub fn validate_blocks(turn_id: &TurnId, blocks: &[ContextBlock]) -> Result<(), ContextError> {
546        // validate monotonic sequence and turn_id matching
547        for (idx, b) in blocks.iter().enumerate() {
548            if b.id.turn_id != *turn_id {
549                return Err(ContextError::InvalidSequence(format!(
550                    "block turn_id mismatch at {}",
551                    idx
552                )));
553            }
554            if b.sequence.0 != idx as u64 {
555                return Err(ContextError::InvalidSequence(format!(
556                    "block sequence not monotonic at {} expected {} got {}",
557                    idx, idx, b.sequence.0
558                )));
559            }
560            if b.id.sequence != b.sequence {
561                return Err(ContextError::InvalidSequence(format!(
562                    "block id sequence mismatch at {}",
563                    idx
564                )));
565            }
566        }
567        // validate tool pairing: no duplicate call ids, every result paired
568        let mut call_set = HashSet::new();
569        let mut seen_results = HashSet::new();
570        for b in blocks {
571            match &b.content {
572                BlockContent::Parts(parts) => {
573                    if parts.is_empty() {
574                        return Err(ContextError::InvalidSequence("empty parts block".into()));
575                    }
576                }
577                BlockContent::ToolCall(tc) => {
578                    if !call_set.insert(tc.call_id.clone()) {
579                        return Err(ContextError::DuplicateToolCallId(tc.call_id.clone()));
580                    }
581                }
582                BlockContent::ToolResult(tr) => {
583                    if !call_set.contains(&tr.call_id) {
584                        return Err(ContextError::UnpairedToolResult(tr.call_id.clone()));
585                    }
586                    if !seen_results.insert(tr.call_id.clone()) {
587                        return Err(ContextError::InvalidSequence(format!(
588                            "duplicate tool result for {:?}",
589                            tr.call_id
590                        )));
591                    }
592                }
593            }
594        }
595        Ok(())
596    }
597
598    /// Projects the current state into an immutable `TurnSnapshot` — the
599    /// canonical wire shape for persistence. Session ordering is NOT part of
600    /// the snapshot: the runtime's session aggregate assigns the
601    /// `HistoryEntry` sequence at commit.
602    pub fn snapshot(&self) -> TurnSnapshot {
603        TurnSnapshot {
604            turn_id: self.turn_id.clone(),
605            blocks: self.blocks.clone(),
606            source_version: self.version,
607            sealed: self.is_sealed(),
608        }
609    }
610}
611
612fn default_sealed() -> bool {
613    true
614}
615
616/// Immutable, serializable projection of a turn — the canonical wire shape
617/// for a persisted turn (a live `TurnContext` is never serialized directly).
618/// The snapshot describes the record itself only: identity, blocks, fact
619/// version, and write lifecycle. Session ordering lives in the runtime's
620/// `HistoryEntry`, not here.
621#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
622pub struct TurnSnapshot {
623    /// Identity of the snapshotted turn.
624    pub turn_id: TurnId,
625    /// The committed blocks, in commit order.
626    pub blocks: OrderedBlocks,
627    /// The turn's `ContextVersion` at snapshot time.
628    pub source_version: ContextVersion,
629    /// Whether the turn was sealed when snapshotted. A *paused* turn
630    /// snapshots as `false` so a persisted conversation reloads with the
631    /// active turn still open and resumable. Serde-additive: an absent field
632    /// defaults to `true` (only sealed turns have a wire snapshot).
633    #[serde(default = "default_sealed")]
634    pub sealed: bool,
635}
636
637/// Shared lossless merged materialization over committed history plus the
638/// active turn — the single semantics both the runtime's
639/// `ConversationState::frame()` and any external conversation driver's
640/// merged-view entry use. The session aggregate that calls it lives in
641/// `causa-runtime`, but the projection itself is common frame vocabulary and
642/// stays with the facts. No reordering, no dedup, no trimming; nothing is
643/// written back.
644pub fn merged_frame(
645    conversation_id: &ConversationId,
646    history: &[TurnSnapshot],
647    active: &TurnContext,
648    round_id: RoundId,
649) -> ContextFrame {
650    let mut blocks = Vec::new();
651    for snapshot in history {
652        blocks.extend(snapshot.blocks.as_slice().iter().cloned());
653    }
654    blocks.extend(active.blocks().iter().cloned());
655    let scope = FrameScope::Conversation {
656        conversation_id: conversation_id.clone(),
657        active_turn_id: active.turn_id(),
658        source_version: active.version(),
659    };
660    ContextFrame {
661        frame_id: FrameId::from_scope(&scope, round_id),
662        scope,
663        round_id,
664        model_context: ModelContext { blocks },
665    }
666}