causa_runtime/conversation.rs
1//! The session aggregate — `ConversationState`, its ordering vocabulary,
2//! and the `ConversationStore` archive port. The single active slot,
3//! completed-only history admission, and commit-time sequence assignment
4//! are this component's decisions, not fact-layer invariants, so they live
5//! with the execution stack. The kernel keeps the facts
6//! ([`causa_kernel::TurnContext`] / [`causa_kernel::TurnSnapshot`]), the
7//! validated recovery entries, and the shared [`causa_kernel::merged_frame`]
8//! projection; it never depends back on this crate.
9//!
10//! ## Snapshot vs. session entry
11//!
12//! A [`causa_kernel::TurnSnapshot`] describes one record only — identity,
13//! blocks, fact version, write lifecycle. Session ordering lives in
14//! [`HistoryEntry`] (`sequence` + `snapshot`), assigned exactly once by
15//! [`ConversationState::commit`]. A bare snapshot alone promises fact
16//! recovery, never a resumable execution checkpoint. Legacy payloads that
17//! embedded `turn_sequence` inside the snapshot are migrated by extracting it
18//! into the entry (the persistence example carries the recipe).
19
20use async_trait::async_trait;
21use serde::{Deserialize, Deserializer, Serialize};
22
23use causa_kernel::{
24 ContextError, ContextFrame, ConversationId, RoundId, TurnContext, TurnSnapshot, merged_frame,
25};
26
27/// Position of a committed turn within a session's history, assigned
28/// exactly once by [`ConversationState::commit`]. The ordering *rule* —
29/// completed turns only, dense sequence assigned at commit — is this
30/// component's policy, not a fact-layer invariant.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
32pub struct TurnSequence(pub u64);
33
34/// Counts controlled transitions of a session (`begin_turn` / `commit` /
35/// `abort_turn`); the aggregate-level analogue of `ContextVersion`.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
37pub struct ConversationVersion(pub u64);
38impl ConversationVersion {
39 /// Returns the successor version.
40 pub fn next(self) -> Self {
41 Self(self.0 + 1)
42 }
43}
44
45/// Kernel-side eligibility stamp recorded when the driver finalizes the
46/// active turn. Marker only — the rich cause stays with the caller via the
47/// runner's `TurnResult` (`TurnInterruption` is driver vocabulary and must not enter the facts layer).
48///
49/// `Paused` stamps a turn that is *not* sealed: the active
50/// `TurnContext` stays open so `resume_turn` can continue it. `commit`
51/// rejects a Paused stamp (`TurnPaused`) — only `abort_turn` (host gives
52/// up) or a resumed completion/commit may close the slot.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(rename_all = "snake_case")]
55pub enum SealedResult {
56 /// The turn finished successfully — the only stamp `commit` accepts.
57 Completed,
58 /// The turn was cut short. Seals the turn, but `commit` rejects it —
59 /// only `abort_turn` closes the slot.
60 Interrupted,
61 /// The turn is suspended but *not* sealed: the active `TurnContext`
62 /// stays open for `resume_turn`; `commit` rejects it with `TurnPaused`.
63 Paused,
64}
65
66/// One committed session entry: the snapshot plus the session order the
67/// record was admitted at. The record describes only its own facts; the
68/// session owns the order.
69#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct HistoryEntry {
71 /// The `TurnSequence` `commit` assigned to this record.
72 pub sequence: TurnSequence,
73 /// The turn's committed facts.
74 pub snapshot: TurnSnapshot,
75}
76
77impl HistoryEntry {
78 /// Convenience view of the wrapped record.
79 pub fn snapshot(&self) -> &TurnSnapshot {
80 &self.snapshot
81 }
82}
83
84/// Rejections of the session-level controlled operations. Pure state
85/// guards — every variant is deterministic from the aggregate's facts.
86#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
87pub enum ConversationError {
88 /// An open (unsealed) active turn exists; seal-then-commit or abort it first.
89 #[error("a turn is already active in this conversation")]
90 TurnAlreadyActive,
91 /// The active turn is already sealed; commit or abort it before
92 /// starting a new one.
93 #[error("active turn is already sealed; abort it before starting a new one")]
94 TurnAlreadySealed,
95 /// The operation needs an active turn (e.g. `frame`), but the slot is empty.
96 #[error("no active turn in this conversation")]
97 NoActiveTurn,
98 /// The given turn id is not the active turn — including a repeated
99 /// commit after the slot was cleared.
100 #[error("unknown turn: {0:?}")]
101 UnknownTurn(causa_kernel::TurnId),
102 /// `begin_turn` with an id already present in committed history.
103 #[error("duplicate turn id: {0:?}")]
104 DuplicateTurnId(causa_kernel::TurnId),
105 /// `commit` on a turn that is not sealed-and-`Completed`.
106 #[error("turn not completed, cannot commit: {0:?}")]
107 TurnNotCompleted(causa_kernel::TurnId),
108 /// `commit` on a paused turn; resume it or abort it instead.
109 #[error("turn is paused, cannot commit until resumed: {0:?}")]
110 TurnPaused(causa_kernel::TurnId),
111 /// The turn is not paused (no `Paused` stamp), so it cannot be resumed.
112 #[error("turn is not paused, cannot resume: {0:?}")]
113 NotPaused(causa_kernel::TurnId),
114 /// Replay validation failed in `from_history`; carries the reason
115 /// (non-monotonic `TurnSequence`, a duplicate turn id, or a
116 /// block-level violation).
117 #[error("invalid conversation state: {0}")]
118 InvalidSequence(String),
119}
120
121/// Session-level controlled operations over the kernel's facts:
122///
123/// - `begin_turn` admits a fresh active turn (rejects concurrent active and
124/// turn-id collisions with committed history);
125/// - `seal_turn` is the only stamping path — for `Completed`/`Interrupted`
126/// it seals the active `TurnContext` and records the outcome in one step
127/// (invariant `sealed_result ∈ {Completed, Interrupted} ⇒ active.is_sealed()`);
128/// for `Paused` it records the stamp while the active `TurnContext` stays
129/// open, so a later `resume_turn` can continue it (invariant
130/// `sealed_result == Paused ⇒ active` is open);
131/// - `commit` is the exactly-once transition into history: it alone assigns
132/// the `TurnSequence` (as a [`HistoryEntry`]), rejects anything not
133/// sealed-and-`Completed` (`Paused` gets the dedicated `TurnPaused`
134/// rejection), and clears the active slot — a repeated commit therefore
135/// lands on `UnknownTurn` (rejection, not idempotence);
136/// - `abort_turn` discards the active turn in any state (open, paused,
137/// sealed); history is untouched either way, and an aborted turn's id
138/// may be reused.
139///
140/// The single active slot, completed-only admission, and commit-time
141/// ordering are this component's defaults — a custom host composes the
142/// kernel facts differently without touching them.
143#[derive(Clone, Serialize)]
144pub struct ConversationState {
145 conversation_id: ConversationId,
146 /// Committed history in `TurnSequence` order — entries, not bare
147 /// snapshots (the order is session vocabulary).
148 history: Vec<HistoryEntry>,
149 /// The sealed active turn at handoff. Serialized through the
150 /// `option_turn_context_as_snapshot` adapter (see
151 /// `causa_kernel`): the in-memory `TurnContext` is the
152 /// mutable fact machine; once sealed its snapshot projection is the
153 /// canonical wire shape. On reload we rebuild a sealed
154 /// `TurnContext` via `from_validated_blocks` + `seal()`.
155 #[serde(with = "causa_kernel::option_turn_context_as_snapshot")]
156 active_turn: Option<TurnContext>,
157 sealed_result: Option<SealedResult>,
158 version: ConversationVersion,
159}
160
161/// Wire-shaped field carrier for [`ConversationState`]: the exact derived
162/// shape the `Serialize` derive emits, kept in one place so the manual
163/// `Deserialize` impl below cannot drift from it. It adds load-time
164/// validation; the wire shape is unchanged.
165#[derive(Deserialize)]
166struct ConversationStateFields {
167 conversation_id: ConversationId,
168 history: Vec<HistoryEntry>,
169 #[serde(with = "causa_kernel::option_turn_context_as_snapshot")]
170 active_turn: Option<TurnContext>,
171 sealed_result: Option<SealedResult>,
172 version: ConversationVersion,
173}
174
175impl<'de> Deserialize<'de> for ConversationState {
176 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
177 where
178 D: Deserializer<'de>,
179 {
180 let fields = ConversationStateFields::deserialize(deserializer)?;
181 // `begin_turn` never admits an active turn whose id is already in
182 // committed history, so a payload claiming otherwise never came
183 // from this aggregate.
184 if let Some(active) = &fields.active_turn
185 && fields
186 .history
187 .iter()
188 .any(|entry| entry.snapshot.turn_id == active.turn_id())
189 {
190 return Err(serde::de::Error::custom(format!(
191 "active turn {:?} duplicates a committed history id",
192 active.turn_id()
193 )));
194 }
195 // Same closed set as `from_history`: a corrupt or hand-edited
196 // payload is rejected with the strength the in-memory paths
197 // enforce by construction.
198 validate_history(&fields.history).map_err(serde::de::Error::custom)?;
199 Ok(Self {
200 conversation_id: fields.conversation_id,
201 history: fields.history,
202 active_turn: fields.active_turn,
203 sealed_result: fields.sealed_result,
204 version: fields.version,
205 })
206 }
207}
208
209/// The validated-replay closed set shared by
210/// [`ConversationState::from_history`] and the aggregate's `Deserialize`
211/// impl: `TurnSequence` strictly increasing (gaps allowed — future
212/// trimming territory), turn ids distinct (duplicate records must not
213/// silently collapse into one history), and every snapshot's blocks pass
214/// the kernel's `TurnContext::validate_blocks`; any violation maps to
215/// `ConversationError::InvalidSequence`.
216fn validate_history(entries: &[HistoryEntry]) -> Result<(), ConversationError> {
217 let mut last_seq = TurnSequence(0);
218 let mut seen_ids = std::collections::HashSet::new();
219 for entry in entries {
220 if entry.sequence < last_seq {
221 return Err(ConversationError::InvalidSequence(format!(
222 "turn_sequence not strictly increasing: {:?}",
223 entry.sequence
224 )));
225 }
226 if !seen_ids.insert(entry.snapshot.turn_id.clone()) {
227 return Err(ConversationError::InvalidSequence(format!(
228 "duplicate turn id in history: {:?}",
229 entry.snapshot.turn_id
230 )));
231 }
232 TurnContext::validate_blocks(&entry.snapshot.turn_id, entry.snapshot.blocks.as_slice())
233 .map_err(|e: ContextError| ConversationError::InvalidSequence(e.to_string()))?;
234 last_seq = TurnSequence(entry.sequence.0 + 1);
235 }
236 Ok(())
237}
238
239impl std::fmt::Debug for ConversationState {
240 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241 f.debug_struct("ConversationState")
242 .field("conversation_id", &self.conversation_id)
243 .field("version", &self.version)
244 .field("history_len", &self.history.len())
245 .field("next_turn_sequence", &self.next_turn_sequence())
246 .field("active_turn", &self.active_turn)
247 .field("sealed_result", &self.sealed_result)
248 .finish()
249 }
250}
251
252impl ConversationState {
253 /// A fresh, empty session: no history, no active turn, version zero.
254 pub fn new(conversation_id: ConversationId) -> Self {
255 Self {
256 conversation_id,
257 history: Vec::new(),
258 active_turn: None,
259 sealed_result: None,
260 version: ConversationVersion(0),
261 }
262 }
263
264 /// The next `TurnSequence` the session will assign on `commit`. Derived
265 /// from `history.last() + 1` so the source of truth is history; there
266 /// is no in-memory field to drift. `TurnSequence(0)` if empty.
267 pub fn next_turn_sequence(&self) -> TurnSequence {
268 self.history
269 .last()
270 .map(|e| TurnSequence(e.sequence.0 + 1))
271 .unwrap_or(TurnSequence(0))
272 }
273
274 /// Admit a fresh active turn. Rejects while any active exists (sealed
275 /// ones must be committed or aborted first) and when the id collides
276 /// with committed history — an aborted turn's id is reusable.
277 pub fn begin_turn(
278 &mut self,
279 turn_id: causa_kernel::TurnId,
280 ) -> Result<&mut TurnContext, ConversationError> {
281 self.assert_stamp_invariant();
282 if let Some(active) = &self.active_turn {
283 return Err(if active.is_sealed() {
284 ConversationError::TurnAlreadySealed
285 } else {
286 ConversationError::TurnAlreadyActive
287 });
288 }
289 if self.history.iter().any(|e| e.snapshot.turn_id == turn_id) {
290 return Err(ConversationError::DuplicateTurnId(turn_id));
291 }
292 self.active_turn = Some(TurnContext::new(turn_id));
293 self.version = self.version.next();
294 Ok(self.active_turn.as_mut().expect("just inserted"))
295 }
296
297 /// The only stamping path. `Completed`/`Interrupted` seal the active
298 /// `TurnContext` and record the outcome atomically; `Paused` records
299 /// the stamp while the turn stays open — the driver-owned counterpart
300 /// of `TurnContext::seal`, deliberately withheld for resumable pauses.
301 pub fn seal_turn(
302 &mut self,
303 turn_id: causa_kernel::TurnId,
304 result: SealedResult,
305 ) -> Result<(), ConversationError> {
306 self.assert_stamp_invariant();
307 match self.active_turn.as_mut() {
308 Some(active) if active.turn_id() == turn_id => {
309 if result != SealedResult::Paused {
310 active.seal();
311 }
312 self.sealed_result = Some(result);
313 Ok(())
314 }
315 _ => Err(ConversationError::UnknownTurn(turn_id)),
316 }
317 }
318
319 /// Read-only view of the active turn.
320 pub fn active_turn(&self) -> Option<&TurnContext> {
321 self.active_turn.as_ref()
322 }
323
324 /// The eligibility stamp, if any (`Some(Paused)` marks a resumable
325 /// turn).
326 pub fn sealed_result(&self) -> Option<SealedResult> {
327 self.sealed_result
328 }
329
330 /// Mutable view of the active turn — the host's door access for
331 /// `append_input` before running.
332 pub fn active_turn_mut(&mut self) -> Option<&mut TurnContext> {
333 self.active_turn.as_mut()
334 }
335
336 /// Exactly-once commit: requires the turn id to match the active slot,
337 /// the turn to be sealed, and the stamp to read `Completed`. Assigns
338 /// the next `TurnSequence`, appends the [`HistoryEntry`] to history,
339 /// and clears the active slot. Rejection (not idempotence): after the
340 /// first commit the slot is empty, so a repeated commit returns
341 /// `UnknownTurn`.
342 pub fn commit(
343 &mut self,
344 turn_id: causa_kernel::TurnId,
345 ) -> Result<HistoryEntry, ConversationError> {
346 self.assert_stamp_invariant();
347 match self.active_turn.as_ref() {
348 Some(active) if active.turn_id() == turn_id => {}
349 _ => return Err(ConversationError::UnknownTurn(turn_id)),
350 }
351 if self.sealed_result == Some(SealedResult::Paused) {
352 // Facts of a paused turn are still open; resume it (or abort)
353 // instead of committing.
354 return Err(ConversationError::TurnPaused(turn_id));
355 }
356 let active = self.active_turn.as_ref().expect("matched above");
357 if !active.is_sealed() || self.sealed_result != Some(SealedResult::Completed) {
358 return Err(ConversationError::TurnNotCompleted(turn_id));
359 }
360 let active = self.active_turn.take().expect("matched above");
361 self.sealed_result = None;
362 let sequence = self.next_turn_sequence();
363 let entry = HistoryEntry {
364 sequence,
365 snapshot: active.snapshot(),
366 };
367 self.history.push(entry.clone());
368 self.version = self.version.next();
369 Ok(entry)
370 }
371
372 /// Discard the active turn in any state (open, paused, sealed-completed,
373 /// sealed-interrupted). History is untouched; the returned
374 /// `TurnContext` is for caller inspection only (no reopen/unseal). An
375 /// aborted turn's id may be reused by a later `begin_turn`.
376 pub fn abort_turn(
377 &mut self,
378 turn_id: causa_kernel::TurnId,
379 ) -> Result<TurnContext, ConversationError> {
380 self.assert_stamp_invariant();
381 match self.active_turn.as_ref() {
382 Some(active) if active.turn_id() == turn_id => {}
383 _ => return Err(ConversationError::UnknownTurn(turn_id)),
384 }
385 let active = self.active_turn.take().expect("matched above");
386 self.sealed_result = None;
387 self.version = self.version.next();
388 Ok(active)
389 }
390
391 /// Lossless merged view: committed history (sequence ascending,
392 /// blocks in BlockSequence order) followed by the active turn's blocks,
393 /// under the Conversation scope identity. Sync and policy-free by
394 /// design — budget, selection and compaction over the merged view
395 /// orchestrate through the policy layer and never mutate facts. The
396 /// only failure source is a missing active turn.
397 pub fn frame(&self, round_id: RoundId) -> Result<ContextFrame, ConversationError> {
398 let active = match &self.active_turn {
399 Some(active) => active,
400 None => return Err(ConversationError::NoActiveTurn),
401 };
402 let history: Vec<TurnSnapshot> = self.history.iter().map(|e| e.snapshot.clone()).collect();
403 Ok(merged_frame(
404 &self.conversation_id,
405 &history,
406 active,
407 round_id,
408 ))
409 }
410
411 /// Borrow-split for a conversation driver's consume/return flow: the
412 /// conversation id and committed history are read while the active
413 /// turn is driven mutably. Stamping still goes through the public
414 /// `seal_turn` afterwards, so no second `&mut` seam exists.
415 pub fn runner_parts(
416 &mut self,
417 ) -> (&ConversationId, Vec<TurnSnapshot>, Option<&mut TurnContext>) {
418 (
419 &self.conversation_id,
420 self.history.iter().map(|e| e.snapshot.clone()).collect(),
421 self.active_turn.as_mut(),
422 )
423 }
424
425 /// Validated replay path: rebuild a session from committed history
426 /// entries. The active slot starts empty (live paths never enter
427 /// here); `ConversationVersion` resets to zero (replay is a fresh load).
428 /// Validation runs the shared `validate_history` closed set — any
429 /// violation maps to `ConversationError::InvalidSequence` so callers
430 /// never touch `ContextError`.
431 pub fn from_history(
432 conversation_id: ConversationId,
433 entries: Vec<HistoryEntry>,
434 ) -> Result<Self, ConversationError> {
435 validate_history(&entries)?;
436 Ok(Self {
437 conversation_id,
438 history: entries,
439 active_turn: None,
440 sealed_result: None,
441 version: ConversationVersion(0),
442 })
443 }
444
445 /// Committed history in ascending `TurnSequence` order.
446 pub fn history(&self) -> &[HistoryEntry] {
447 &self.history
448 }
449
450 /// Number of committed entries in history.
451 pub fn history_len(&self) -> usize {
452 self.history.len()
453 }
454
455 /// The `ConversationVersion`, ticked at every controlled transition
456 /// (`begin_turn` / `commit` / `abort_turn`); zero for a fresh or
457 /// replayed session.
458 pub fn version(&self) -> ConversationVersion {
459 self.version
460 }
461
462 /// The session's identity.
463 pub fn conversation_id(&self) -> &ConversationId {
464 &self.conversation_id
465 }
466
467 /// Canonical-path invariant: a `Completed`/`Interrupted` stamp exists
468 /// only while the active turn is sealed; a `Paused` stamp exists only
469 /// while it is open. Enforced by construction (`seal_turn` seals
470 /// exactly when it does not stamp `Paused`; every other path only
471 /// clears). Commit does not rely on this — it checks both facts
472 /// defensively.
473 fn assert_stamp_invariant(&self) {
474 debug_assert!(match self.sealed_result {
475 None => true,
476 Some(SealedResult::Paused) => {
477 self.active_turn.as_ref().is_some_and(|t| !t.is_sealed())
478 }
479 Some(_) => self.active_turn.as_ref().is_some_and(|t| t.is_sealed()),
480 });
481 }
482}
483
484/// Persist one session's committed history as [`HistoryEntry`] records —
485/// the archive convenience port this component offers. It is a
486/// session-archive contract (completed-turn history), not a cross-host
487/// capability, and it is **not** wired into `commit` — the host
488/// calls `save_entry` after `ConversationState::commit`, keeping
489/// persistence policy (batch writes, compression, fsync cadence, retry
490/// strategy) host-owned.
491///
492/// Full paused outcomes are NOT stored through this port: the host saves
493/// them in its own checkpoint document (fact state + continuation can live
494/// atomically in one file).
495///
496/// Implementations are expected to be `Send + Sync` so they can sit
497/// behind an `Arc` in the host's wiring.
498#[async_trait]
499pub trait ConversationStore: Send + Sync {
500 /// Persist one committed history entry. Caller is the host's harness,
501 /// invoked inside or after `ConversationState::commit`. Idempotent on
502 /// `(conversation_id, sequence)` — repeated writes of the same entry
503 /// are valid (host may retry).
504 ///
505 /// Entries do not carry their `ConversationId` (the id is implicit in
506 /// the host's commit flow), so the trait takes it explicitly.
507 async fn save_entry(
508 &self,
509 conversation_id: &ConversationId,
510 entry: &HistoryEntry,
511 ) -> Result<(), ConversationStoreError>;
512
513 /// Load committed history for `conversation_id`. Returned entries are
514 /// in their own `TurnSequence` ascending order; the session validates
515 /// strict monotonicity through `ConversationState::from_history`.
516 /// Returns `ConversationStoreError::NotFound` when the conversation
517 /// has never been written.
518 async fn load_entries(
519 &self,
520 conversation_id: &ConversationId,
521 ) -> Result<Vec<HistoryEntry>, ConversationStoreError>;
522}
523
524/// Session-archive error surface. Distinct from
525/// `ArtifactStore::StoreError` (artifact persistence). Implementations
526/// map their native failures onto these variants so the host has a
527/// single error type to handle.
528#[derive(Debug, thiserror::Error)]
529pub enum ConversationStoreError {
530 /// No entry has ever been written for this conversation; carries the
531 /// conversation id.
532 #[error("conversation not found: {0}")]
533 NotFound(String),
534 /// The underlying storage failed; carries the human-readable cause.
535 #[error("io error: {0}")]
536 Io(String),
537 /// An entry could not be (de)serialized; carries the human-readable
538 /// cause.
539 #[error("serialization error: {0}")]
540 Serialization(String),
541 /// Stored data is present but unusable; carries the human-readable cause.
542 #[error("corrupted data: {0}")]
543 Corrupted(String),
544}