Skip to main content

car_sync/
conversation.rs

1//! Transcript resume: the conversation surface as an ordered, role-threaded
2//! projection of the oplog (slice **B2** of
3//! `docs/proposals/multi-device-sync.md`), hardened by kernel review.
4//!
5//! # What this closes
6//!
7//! `docs/solutions/conversation-persistence-removed-in-0.25.md` records that
8//! the disk-backed `ConversationStore` island was **removed in 0.25** — dead
9//! code with a latent *compaction-vs-store incoherence* bug (compaction
10//! summarized the in-memory graph but never wrote the summaries back to the
11//! JSONL store, so a resume would have reloaded stale raw turns). That doc's
12//! forward path: "an append-only oplog as the source of truth with files/caches
13//! as projections." B2 is that path, oplog-native — a conversation is a
14//! projection of ordered turn ops, not a resurrected second store.
15//!
16//! # The model: a transcript is a projection, not a store
17//!
18//! A conversation turn is an [`crate::oplog::OpRecord`] on the
19//! [`crate::oplog::Surface::Conversation`] surface. The transcript is a *pure
20//! fold* of those ops: filter by `conversation_id`, order by the canonical
21//! `(hlc, op_id)` total order the crate already agrees on
22//! ([`crate::fold::SyncState::log_entries`]), project each payload into a typed
23//! [`Turn`]. One source of truth; no second store to drift.
24//!
25//! # Turn identity: an EVENT STREAM (op_id-keyed), not a content entity
26//!
27//! **Kernel-review correction (reversed from the first B2 cut).** A conversation
28//! turn folds as an **event-stream multiset keyed by `op_id`**
29//! ([`crate::oplog::Surface::is_event_stream`] returns `true` for
30//! `Conversation`), NOT by content. The content-keyed first cut had a
31//! reproduced **silent data-loss** bug: `stable_key` hashes the caller's
32//! *payload* — `{conversation_id, role, content, timestamp}` — so two genuine
33//! user "yes" turns stamped at the same payload timestamp (second-granularity
34//! stamps, a cached `now()`, a rapid double-confirm) collapsed to ONE entry.
35//! The earlier justification ("a repeated utterance differs in timestamp / the
36//! HLC advances") was wrong: the fold keyed on the payload timestamp, not the
37//! HLC.
38//!
39//! The right identity: **a turn has exactly one author and propagates by op
40//! replication, so op identity IS turn identity.** Keyed by `op_id`, a *resent*
41//! op dedups (retransmission), while two *distinct* authorings never collapse —
42//! even byte-identical ones. This reuses B1's multiset machinery (the same the
43//! routing observations use). Conversation differs from routing only in that
44//! its entries are **independent** (no path-dependent EMA replay), so it
45//! tolerates `LastN` retention where routing forbids any trim — see
46//! [`crate::oplog::Surface::is_replay_stream`].
47//!
48//! # Ordering across devices
49//!
50//! HLC gives causal order; two devices talking to the same agent concurrently
51//! interleave deterministically by `Hlc`'s derived `Ord`
52//! (`(wall_ms, counter, device_id)`), tie-broken on `op_id`. A turn that
53//! causally follows another (its writer `observe`d it) always sorts after it;
54//! genuinely concurrent turns fall back to the stable `device_id` tiebreak. So
55//! every device reconstructs a byte-identical transcript from any delivery
56//! order.
57//!
58//! **But determinism ≠ provider-validity** (the second kernel-review defect).
59//! Causal order says nothing about *concurrent* turns: two devices each replying
60//! to the same user turn yield `[user, assistant, assistant]` — which Anthropic
61//! 400s. So [`crate::fold::SyncState::resume_messages`] does not emit the raw
62//! transcript; it runs a **repair** that guarantees a provider-valid `Message`
63//! sequence (the "runtime validates" thesis applied to the projection): adjacent
64//! same-role turns are coalesced, an orphan `tool_result` (one not answering a
65//! preceding assistant `tool_call` — e.g. a `LastN` window that cut inside a
66//! tool exchange) is dropped, and a dangling assistant `tool_call` with no
67//! following `tool_result` has its calls stripped. See [`repair`].
68//!
69//! # Compaction coherence (why the 0.25 bug cannot return)
70//!
71//! Conversation retention is B4's `RetentionRule::LastN` over the folded
72//! snapshot; the checkpoint keeps the last N turns by `timestamp` and older raw
73//! turns drop from the read model. The 0.25 incoherence was structural — *two*
74//! stores on two write paths. B2 has **one** source of truth (the oplog) and the
75//! transcript is a projection of the *same* folded state B4's checkpoint
76//! serializes. `apply_retention` over the compacted device's state equals
77//! `apply_retention` over a fresh full fold (byte- and hash-identical). The
78//! **semantic** summarization of aged-out turns lives in memgine
79//! (`ConversationSummary` nodes, a B6 concern); B2 supplies the ordered raw
80//! turns it summarizes and the last-N window, nothing lossy.
81//!
82//! # The resume bridge
83//!
84//! [`Turn::to_message`] builds each turn as the **real**
85//! [`car_inference_types::Message`] (`user` / `assistant {content, tool_calls}`
86//! / `tool_result {tool_use_id, content}`), and `resume_messages` returns the
87//! repaired `Vec<Message>` car-inference's multi-turn path replays. Because
88//! car-sync depends on the shared `car-inference-types` crate — not a hand-copied
89//! mirror — a change to `Message`'s shape is a **compile error** here, not a
90//! runtime `from_value::<Message>` break in the daemon. The daemon/memgine
91//! adoption (feeding these into the engine's multi-turn path) is B6.
92
93use crate::fold::{FoldedRecord, SyncState};
94use crate::oplog::Hlc;
95use car_inference_types::{Message, ToolCall};
96use serde::{Deserialize, Serialize};
97use serde_json::{json, Value};
98
99/// The conversation a turn belongs to when its payload carries no explicit
100/// `conversation_id` (e.g. the legacy `{speaker, text, timestamp}` turns the
101/// B4 tests emit). Such turns fold into one unnamed default transcript.
102pub const DEFAULT_CONVERSATION: &str = "";
103
104/// A conversation turn's role. Serializes snake_case (`user`/`assistant`/
105/// `tool`); [`Turn::to_message`] maps `Tool` onto the `Message::ToolResult`
106/// role.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
108#[serde(rename_all = "snake_case")]
109pub enum Role {
110    /// A user turn (`Message::User`).
111    User,
112    /// An assistant turn, possibly with `tool_calls` (`Message::Assistant`).
113    Assistant,
114    /// A tool-result turn (`Message::ToolResult`).
115    Tool,
116}
117
118impl Role {
119    /// Parse the `role`/`speaker` string a Conversation payload carries.
120    /// Tolerant of the legacy `speaker` values and of `tool_result` (the
121    /// Message role name) as well as `tool`.
122    fn parse(s: &str) -> Role {
123        match s {
124            "assistant" => Role::Assistant,
125            "tool" | "tool_result" => Role::Tool,
126            _ => Role::User,
127        }
128    }
129}
130
131/// One folded, ordered transcript turn — the typed projection of a
132/// [`crate::oplog::Surface::Conversation`] op.
133///
134/// `hlc`/`op_id` are provenance/ordering only (not part of the replayed
135/// `Message`): they record where the turn sits in the causal order and which
136/// op produced it (op identity IS turn identity — see the module docs).
137#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
138pub struct Turn {
139    /// Which conversation this turn threads into ([`DEFAULT_CONVERSATION`] when
140    /// the payload names none).
141    pub conversation_id: String,
142    /// user / assistant / tool.
143    pub role: Role,
144    /// The turn text (`content`, falling back to the legacy `text` field).
145    pub content: String,
146    /// Assistant tool calls — the REAL [`car_inference_types::ToolCall`] type,
147    /// parsed from the payload. Empty for non-assistant turns or an assistant
148    /// turn that called no tool.
149    #[serde(default, skip_serializing_if = "Vec::is_empty")]
150    pub tool_calls: Vec<ToolCall>,
151    /// For a `Tool` turn: the id of the tool call this result answers
152    /// (`Message::ToolResult.tool_use_id`).
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub tool_use_id: Option<String>,
155    /// Turn timestamp (ms) — the recency key B4's `LastN` conversation
156    /// retention orders on.
157    pub timestamp: u64,
158    /// The causal-order stamp this turn folded with (ordering/provenance).
159    pub hlc: Hlc,
160    /// The op that produced this turn (provenance; the fold identity).
161    pub op_id: String,
162}
163
164impl Turn {
165    /// Build the Conversation op **payload** for a user turn — append it via
166    /// `DeviceLog::append(scope, Surface::Conversation, payload)`.
167    pub fn user_payload(conversation_id: &str, content: &str, timestamp: u64) -> Value {
168        json!({
169            "conversation_id": conversation_id,
170            "role": "user",
171            "content": content,
172            "timestamp": timestamp,
173        })
174    }
175
176    /// Build the Conversation op payload for an assistant turn. `tool_calls`
177    /// are raw `ToolCall` JSON values (`{id?, name, arguments}` — how a model
178    /// or the daemon already holds them); [`Turn::from_record`] parses them
179    /// into the typed [`ToolCall`]. Empty for a plain text reply.
180    pub fn assistant_payload(
181        conversation_id: &str,
182        content: &str,
183        tool_calls: Vec<Value>,
184        timestamp: u64,
185    ) -> Value {
186        json!({
187            "conversation_id": conversation_id,
188            "role": "assistant",
189            "content": content,
190            "tool_calls": tool_calls,
191            "timestamp": timestamp,
192        })
193    }
194
195    /// Build the Conversation op payload for a tool-result turn.
196    pub fn tool_payload(
197        conversation_id: &str,
198        tool_use_id: &str,
199        content: &str,
200        timestamp: u64,
201    ) -> Value {
202        json!({
203            "conversation_id": conversation_id,
204            "role": "tool",
205            "tool_use_id": tool_use_id,
206            "content": content,
207            "timestamp": timestamp,
208        })
209    }
210
211    /// Project a folded conversation record into a typed [`Turn`]. Returns
212    /// `None` for a tombstone stub (a retention-dropped entity's referential
213    /// placeholder — never a real turn).
214    ///
215    /// Tolerant of both the rich B2 payload (`role`/`content`/`tool_calls`) and
216    /// the legacy `(speaker, text, timestamp)` shape the B4 tests use, so one
217    /// transcript view serves every conversation op ever written.
218    pub fn from_record(record: &FoldedRecord) -> Option<Turn> {
219        if crate::compact::is_tombstone(record) {
220            return None;
221        }
222        let p = &record.payload;
223        let role = p
224            .get("role")
225            .or_else(|| p.get("speaker"))
226            .and_then(Value::as_str)
227            .map(Role::parse)
228            .unwrap_or(Role::User);
229        let content = p
230            .get("content")
231            .or_else(|| p.get("text"))
232            .and_then(Value::as_str)
233            .unwrap_or("")
234            .to_string();
235        let conversation_id = p
236            .get("conversation_id")
237            .and_then(Value::as_str)
238            .unwrap_or(DEFAULT_CONVERSATION)
239            .to_string();
240        // Parse the tool_calls array into the REAL ToolCall type (best-effort:
241        // a malformed entry is dropped rather than poisoning the whole turn).
242        let tool_calls = p
243            .get("tool_calls")
244            .and_then(Value::as_array)
245            .map(|arr| {
246                arr.iter()
247                    .filter_map(|v| serde_json::from_value::<ToolCall>(v.clone()).ok())
248                    .collect()
249            })
250            .unwrap_or_default();
251        let tool_use_id = p
252            .get("tool_use_id")
253            .and_then(Value::as_str)
254            .map(str::to_string);
255        let timestamp = p
256            .get("timestamp")
257            .and_then(|v| v.as_u64().or_else(|| v.as_f64().map(|f| f as u64)))
258            .unwrap_or(0);
259        Some(Turn {
260            conversation_id,
261            role,
262            content,
263            tool_calls,
264            tool_use_id,
265            timestamp,
266            hlc: record.hlc.clone(),
267            op_id: record.op_id.clone(),
268        })
269    }
270
271    /// Build the REAL [`car_inference_types::Message`] for this turn (typed —
272    /// a shape change to `Message` is a compile error here). The mapping:
273    ///
274    /// - [`Role::User`] → `Message::User`
275    /// - [`Role::Assistant`] → `Message::Assistant { content, tool_calls }`
276    /// - [`Role::Tool`] → `Message::ToolResult { tool_use_id, content }`
277    pub fn to_message(&self) -> Message {
278        match self.role {
279            Role::User => Message::User {
280                content: self.content.clone(),
281            },
282            Role::Assistant => Message::Assistant {
283                content: self.content.clone(),
284                tool_calls: self.tool_calls.clone(),
285            },
286            Role::Tool => Message::ToolResult {
287                tool_use_id: self.tool_use_id.clone().unwrap_or_default(),
288                content: self.content.clone(),
289            },
290        }
291    }
292}
293
294/// Join two turn bodies for a coalesced turn (skip an empty side).
295fn join_content(a: &str, b: &str) -> String {
296    match (a.is_empty(), b.is_empty()) {
297        (true, _) => b.to_string(),
298        (_, true) => a.to_string(),
299        _ => format!("{a}\n\n{b}"),
300    }
301}
302
303/// Repair an ordered transcript into a **provider-valid** `Message` sequence.
304///
305/// The raw transcript is causally ordered but not provider-valid: concurrent
306/// turns can produce invalid adjacencies (`[user, assistant, assistant]` →
307/// Anthropic 400), and a `LastN` window can cut inside a tool exchange leaving
308/// an orphan `tool_result` at the head (also a 400). This is the runtime
309/// validating its own projection. Guarantees on the output:
310///
311/// 1. **No adjacent same-role messages** — consecutive `User`s (or `Assistant`s)
312///    are coalesced into one, their bodies joined and (for assistants) their
313///    tool_calls concatenated. Two concurrent replies to one user turn merge;
314///    an assistant "threaded after" an unrelated user turn it never observed is
315///    merged rather than mis-attributed (best-effort — the deterministic order
316///    is preserved, the invalid adjacency is not emitted).
317/// 2. **No orphan `tool_result`** — a `Tool` turn is kept only if it answers a
318///    preceding assistant that carried `tool_calls` (or a run of such results);
319///    otherwise it is dropped (the `LastN`-cut-mid-exchange case).
320/// 3. **No dangling assistant `tool_call`** — an assistant whose `tool_calls`
321///    are not answered by a following `tool_result` has its calls stripped
322///    (kept as a plain text turn), so the sequence never presents an
323///    unanswered tool_use.
324///
325/// Leading-role normalization (ensuring the sequence *starts* with a user turn,
326/// a per-provider requirement) is the caller/protocol-handler's concern — it
327/// already folds the system prompt and prepends the next user message; `repair`
328/// only guarantees internal adjacency + tool-pairing validity.
329pub fn repair(turns: Vec<Turn>) -> Vec<Message> {
330    let mut out: Vec<Turn> = Vec::new();
331    // Does the last emitted turn leave a tool exchange open (an assistant with
332    // tool_calls, or a tool_result continuing one)? Only then is a tool_result
333    // valid.
334    let mut tool_open = false;
335    for t in turns {
336        match t.role {
337            Role::Tool => {
338                if tool_open {
339                    out.push(t); // a valid result; the exchange stays open
340                }
341                // else: orphan tool_result → dropped
342            }
343            Role::User => {
344                if let Some(last) = out.last_mut() {
345                    if last.role == Role::User {
346                        last.content = join_content(&last.content, &t.content);
347                        continue;
348                    }
349                }
350                tool_open = false;
351                out.push(t);
352            }
353            Role::Assistant => {
354                if let Some(last) = out.last_mut() {
355                    if last.role == Role::Assistant {
356                        last.content = join_content(&last.content, &t.content);
357                        last.tool_calls.extend(t.tool_calls);
358                        tool_open = !last.tool_calls.is_empty();
359                        continue;
360                    }
361                }
362                tool_open = !t.tool_calls.is_empty();
363                out.push(t);
364            }
365        }
366    }
367    // Post-pass: strip a dangling assistant tool_call (no following tool_result),
368    // so no unanswered tool_use is ever presented to a provider.
369    for i in 0..out.len() {
370        if out[i].role == Role::Assistant && !out[i].tool_calls.is_empty() {
371            let answered = out.get(i + 1).is_some_and(|n| n.role == Role::Tool);
372            if !answered {
373                out[i].tool_calls.clear();
374            }
375        }
376    }
377    out.iter().map(Turn::to_message).collect()
378}
379
380impl SyncState {
381    /// The ordered, role-threaded transcript for one conversation — the
382    /// causally `(hlc, op_id)`-ordered `Vec<Turn>` (B2). This is the raw
383    /// projection (every folded turn, in order); [`SyncState::resume_messages`]
384    /// is the provider-valid `Message` view. Turns whose payload names no
385    /// `conversation_id` belong to [`DEFAULT_CONVERSATION`]; tombstone stubs are
386    /// skipped. Order-independent of delivery, byte-identical on every device
387    /// that folded the same op-set.
388    pub fn transcript(&self, conversation_id: &str) -> Vec<Turn> {
389        self.log_entries(&crate::oplog::Surface::Conversation.tag())
390            .into_iter()
391            .filter_map(Turn::from_record)
392            .filter(|t| t.conversation_id == conversation_id)
393            .collect()
394    }
395
396    /// Every conversation id present in the folded state, in stable sorted
397    /// order (includes [`DEFAULT_CONVERSATION`] when unnamed turns exist).
398    pub fn conversation_ids(&self) -> Vec<String> {
399        let mut ids: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
400        for rec in self.log_entries(&crate::oplog::Surface::Conversation.tag()) {
401            if let Some(turn) = Turn::from_record(rec) {
402                ids.insert(turn.conversation_id);
403            }
404        }
405        ids.into_iter().collect()
406    }
407
408    /// Reconstruct the runtime's multi-turn conversation state: the ordered,
409    /// **provider-valid** [`car_inference_types::Message`] sequence
410    /// car-inference's multi-turn path replays to continue the conversation
411    /// (B2's resume bridge). The raw transcript is [`repair`]ed first, so the
412    /// result never contains an invalid role adjacency or an orphan/dangling
413    /// tool exchange. The daemon/memgine adoption is B6.
414    pub fn resume_messages(&self, conversation_id: &str) -> Vec<Message> {
415        repair(self.transcript(conversation_id))
416    }
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422    use crate::compact::{
423        apply_retention, plan_compaction, AckTable, RetentionPolicy, RetentionRule,
424    };
425    use crate::fold::{fold, fold_onto, state_hash};
426    use crate::oplog::{DeviceLog, Scope, Surface};
427
428    /// Assert a repaired sequence is provider-valid: no adjacent same-role
429    /// (assistant/assistant, user/user), no orphan/leading tool_result, no
430    /// dangling assistant tool_call.
431    fn assert_provider_valid(ms: &[Message]) {
432        for (i, w) in ms.windows(2).enumerate() {
433            let dup = matches!(
434                (&w[0], &w[1]),
435                (Message::Assistant { .. }, Message::Assistant { .. })
436                    | (Message::User { .. }, Message::User { .. })
437            );
438            assert!(!dup, "invalid adjacency at {i}: {:?} then {:?}", w[0], w[1]);
439        }
440        for (i, m) in ms.iter().enumerate() {
441            if matches!(m, Message::ToolResult { .. }) {
442                let opens_here = i > 0
443                    && (matches!(&ms[i - 1], Message::Assistant { tool_calls, .. } if !tool_calls.is_empty())
444                        || matches!(&ms[i - 1], Message::ToolResult { .. }));
445                assert!(opens_here, "orphan tool_result at index {i}");
446            }
447            if let Message::Assistant { tool_calls, .. } = m {
448                if !tool_calls.is_empty() {
449                    let answered = ms
450                        .get(i + 1)
451                        .is_some_and(|n| matches!(n, Message::ToolResult { .. }));
452                    assert!(answered, "dangling assistant tool_call at index {i}");
453                }
454            }
455        }
456    }
457
458    /// Append the three turn kinds to one conversation on a single device.
459    fn one_device_conversation(conv: &str) -> Vec<crate::oplog::OpRecord> {
460        let mut d = DeviceLog::new("dev-a");
461        vec![
462            d.append(
463                Scope::Personal,
464                Surface::Conversation,
465                Turn::user_payload(conv, "what's the weather?", 10),
466            ),
467            d.append(
468                Scope::Personal,
469                Surface::Conversation,
470                Turn::assistant_payload(
471                    conv,
472                    "",
473                    vec![
474                        json!({"id": "call_0", "name": "get_weather", "arguments": {"city": "SF"}}),
475                    ],
476                    11,
477                ),
478            ),
479            d.append(
480                Scope::Personal,
481                Surface::Conversation,
482                Turn::tool_payload(conv, "call_0", "sunny, 72F", 12),
483            ),
484            d.append(
485                Scope::Personal,
486                Surface::Conversation,
487                Turn::assistant_payload(conv, "It's sunny and 72F in SF.", vec![], 13),
488            ),
489        ]
490    }
491
492    #[test]
493    fn transcript_folds_in_causal_order_regardless_of_delivery() {
494        let ops = one_device_conversation("c1");
495        let expected = [
496            "what's the weather?",
497            "",
498            "sunny, 72F",
499            "It's sunny and 72F in SF.",
500        ];
501        for delivery in [ops.clone(), ops.iter().rev().cloned().collect::<Vec<_>>()] {
502            let turns = fold(&delivery).transcript("c1");
503            let texts: Vec<&str> = turns.iter().map(|t| t.content.as_str()).collect();
504            assert_eq!(texts, expected);
505            assert_eq!(
506                turns.iter().map(|t| t.role).collect::<Vec<_>>(),
507                vec![Role::User, Role::Assistant, Role::Tool, Role::Assistant]
508            );
509        }
510    }
511
512    #[test]
513    fn resume_produces_a_valid_message_sequence_of_the_real_type() {
514        // The resume bridge builds the REAL Message type (compile-checked), and
515        // the sequence is provider-valid.
516        let ops = one_device_conversation("c1");
517        let messages: Vec<Message> = fold(&ops).resume_messages("c1");
518        assert_eq!(messages.len(), 4);
519        assert_provider_valid(&messages);
520
521        match &messages[0] {
522            Message::User { content } => assert_eq!(content, "what's the weather?"),
523            other => panic!("turn 0 should be a user message, got {other:?}"),
524        }
525        match &messages[1] {
526            Message::Assistant { tool_calls, .. } => {
527                assert_eq!(
528                    tool_calls.len(),
529                    1,
530                    "assistant tool_calls round-trip as the real ToolCall"
531                );
532                assert_eq!(tool_calls[0].name, "get_weather");
533            }
534            other => panic!("turn 1 should be an assistant tool call, got {other:?}"),
535        }
536        match &messages[2] {
537            Message::ToolResult {
538                tool_use_id,
539                content,
540            } => {
541                assert_eq!(tool_use_id, "call_0");
542                assert_eq!(content, "sunny, 72F");
543            }
544            other => panic!("turn 2 should be a tool_result, got {other:?}"),
545        }
546        match &messages[3] {
547            Message::Assistant {
548                content,
549                tool_calls,
550            } => {
551                assert_eq!(content, "It's sunny and 72F in SF.");
552                assert!(tool_calls.is_empty());
553            }
554            other => panic!("turn 3 should be a plain assistant reply, got {other:?}"),
555        }
556    }
557
558    // ------------------------------------------------------------------
559    // CRIT-2 (reproduced): content-keyed identity DROPPED distinct turns. Now a
560    // conversation turn is an event stream — op identity is turn identity — so
561    // two distinct authorings never collapse; only a resent op dedups.
562    // ------------------------------------------------------------------
563    #[test]
564    fn crit2_two_genuine_same_payload_turns_do_not_collapse() {
565        // Two genuine user "yes" turns stamped at the SAME payload timestamp
566        // (second-granularity clock / rapid double-confirm). Under the old
567        // content-key fold these were ONE entry (silent data loss). As an event
568        // stream they are two distinct ops → two transcript entries.
569        let mut d = DeviceLog::new("dev-a");
570        let yes = || Turn::user_payload("c1", "yes", 5); // identical payload incl. timestamp
571        let o1 = d.append(Scope::Personal, Surface::Conversation, yes());
572        let o2 = d.append(Scope::Personal, Surface::Conversation, yes());
573        assert_ne!(
574            o1.op_id, o2.op_id,
575            "distinct ops (different seq/hlc) → distinct op_id"
576        );
577        assert_eq!(
578            fold(&[o1.clone(), o2]).transcript("c1").len(),
579            2,
580            "both genuine turns survive (CRIT-2 fixed)"
581        );
582        // A RESENT op (same op_id, retransmission) still dedups to one.
583        assert_eq!(
584            fold(&[o1.clone(), o1]).transcript("c1").len(),
585            1,
586            "resent op dedups on op_id"
587        );
588    }
589
590    #[test]
591    fn same_payload_turns_on_two_devices_are_distinct_events() {
592        // Two devices independently authoring a byte-identical turn are TWO
593        // events (distinct op_id via distinct device_id), not one.
594        let mut a = DeviceLog::new("dev-a");
595        let mut b = DeviceLog::new("dev-b");
596        let payload = Turn::user_payload("c1", "hello", 5);
597        let oa = a.append(Scope::Personal, Surface::Conversation, payload.clone());
598        let ob = b.append(Scope::Personal, Surface::Conversation, payload);
599        assert_eq!(fold(&[oa, ob]).transcript("c1").len(), 2);
600    }
601
602    // ------------------------------------------------------------------
603    // CRIT-1 (reproduced): concurrent-device replies produced an invalid
604    // [user, assistant, assistant] adjacency. resume_messages now repairs it.
605    // ------------------------------------------------------------------
606    #[test]
607    fn crit1_concurrent_assistant_replies_repair_to_a_valid_sequence() {
608        let mut a = DeviceLog::new("dev-a");
609        let mut b = DeviceLog::new("dev-b");
610        let u = a.append(
611            Scope::Personal,
612            Surface::Conversation,
613            Turn::user_payload("c1", "hi", 1),
614        );
615        b.observe(&u.hlc);
616        // Two concurrent replies to u (neither observed the other).
617        let ra = a.append(
618            Scope::Personal,
619            Surface::Conversation,
620            Turn::assistant_payload("c1", "reply A", vec![], 2),
621        );
622        let rb = b.append(
623            Scope::Personal,
624            Surface::Conversation,
625            Turn::assistant_payload("c1", "reply B", vec![], 2),
626        );
627
628        let ops = vec![u, ra, rb];
629        // Raw transcript has the invalid [user, assistant, assistant]…
630        let raw = fold(&ops).transcript("c1");
631        assert_eq!(raw.len(), 3);
632        assert_eq!(
633            (raw[1].role, raw[2].role),
634            (Role::Assistant, Role::Assistant)
635        );
636        // …but resume repairs it, order-independently over every delivery.
637        let baseline = fold(&ops).resume_messages("c1");
638        assert_eq!(baseline.len(), 2, "the two concurrent replies coalesce");
639        assert_provider_valid(&baseline);
640        assert!(matches!(&baseline[0], Message::User { .. }));
641        assert!(
642            matches!(&baseline[1], Message::Assistant { content, .. } if content.contains("reply A") && content.contains("reply B"))
643        );
644        for perm in permutations(&ops) {
645            assert_eq!(
646                fold(&perm).resume_messages("c1"),
647                baseline,
648                "repair is delivery-order-independent"
649            );
650        }
651    }
652
653    #[test]
654    fn adjacent_user_turns_coalesce_before_a_reply() {
655        // Two user turns land back-to-back (userA, then userB observing it),
656        // then a reply that observed both. Raw = [user, user, assistant] — the
657        // two users are an invalid adjacency. Repair coalesces them so the
658        // assistant follows a single merged user context, never a mis-thread.
659        let mut a = DeviceLog::new("dev-a");
660        let mut b = DeviceLog::new("dev-b");
661        let ua = a.append(
662            Scope::Personal,
663            Surface::Conversation,
664            Turn::user_payload("c1", "userA", 1),
665        );
666        b.observe(&ua.hlc);
667        let ub = b.append(
668            Scope::Personal,
669            Surface::Conversation,
670            Turn::user_payload("c1", "userB", 2),
671        );
672        a.observe(&ub.hlc);
673        let ra = a.append(
674            Scope::Personal,
675            Surface::Conversation,
676            Turn::assistant_payload("c1", "reply", vec![], 3),
677        );
678
679        let ops = vec![ua, ub, ra];
680        assert_eq!(
681            fold(&ops)
682                .transcript("c1")
683                .iter()
684                .map(|t| t.role)
685                .collect::<Vec<_>>(),
686            vec![Role::User, Role::User, Role::Assistant],
687            "raw has the invalid user/user adjacency"
688        );
689        let ms = fold(&ops).resume_messages("c1");
690        assert_eq!(ms.len(), 2, "the two users coalesce");
691        assert_provider_valid(&ms);
692        assert!(
693            matches!(&ms[0], Message::User { content } if content.contains("userA") && content.contains("userB"))
694        );
695        assert!(matches!(&ms[1], Message::Assistant { .. }));
696    }
697
698    // ------------------------------------------------------------------
699    // CRIT-3 (reproduced): a LastN window cut inside a tool exchange orphaned a
700    // leading tool_result. resume_messages drops it.
701    // ------------------------------------------------------------------
702    #[test]
703    fn crit3_lastn_orphan_tool_result_is_dropped_on_resume() {
704        // [user, assistant(tool_call), tool_result, assistant] under LastN{2}
705        // retains [tool_result, assistant] — a LEADING orphan tool_result
706        // (provider 400). (This ALSO exercises that LastN is ALLOWED on the
707        // event-stream conversation surface — the retention-guard reconciliation.)
708        let ops = one_device_conversation("c1"); // ts 10..13
709        let mut policy = RetentionPolicy::keep_all();
710        policy
711            .rules
712            .insert("conversation".to_string(), RetentionRule::LastN { n: 2 });
713        let (retained, _) = apply_retention(&fold(&ops), &policy, 1_000).unwrap();
714
715        let raw = retained.transcript("c1");
716        assert_eq!(
717            raw.iter().map(|t| t.role).collect::<Vec<_>>(),
718            vec![Role::Tool, Role::Assistant],
719            "the retained window is the orphan [tool_result, assistant]"
720        );
721
722        let ms = retained.resume_messages("c1");
723        assert!(
724            !matches!(ms.first(), Some(Message::ToolResult { .. })),
725            "leading orphan tool_result dropped"
726        );
727        assert_provider_valid(&ms);
728        assert_eq!(ms.len(), 1);
729        assert!(matches!(&ms[0], Message::Assistant { .. }));
730    }
731
732    #[test]
733    fn repair_drops_a_leading_orphan_tool_result_directly() {
734        // Unit-level: repair guarantees no leading/orphan tool_result even from
735        // a hand-built transcript that starts mid-exchange.
736        let hlc = Hlc {
737            wall_ms: 0,
738            counter: 0,
739            device_id: "d".into(),
740        };
741        let orphan = Turn {
742            conversation_id: "c".into(),
743            role: Role::Tool,
744            content: "res".into(),
745            tool_calls: vec![],
746            tool_use_id: Some("call_0".into()),
747            timestamp: 1,
748            hlc: hlc.clone(),
749            op_id: "op-x".into(),
750        };
751        let asst = Turn {
752            conversation_id: "c".into(),
753            role: Role::Assistant,
754            content: "done".into(),
755            tool_calls: vec![],
756            tool_use_id: None,
757            timestamp: 2,
758            hlc,
759            op_id: "op-y".into(),
760        };
761        let ms = repair(vec![orphan, asst]);
762        assert!(!matches!(ms.first(), Some(Message::ToolResult { .. })));
763        assert_provider_valid(&ms);
764    }
765
766    #[test]
767    fn concurrent_device_turns_interleave_deterministically_and_order_independently() {
768        let mut a = DeviceLog::new("dev-a");
769        let mut b = DeviceLog::new("dev-b");
770        let a1 = a.append(
771            Scope::Personal,
772            Surface::Conversation,
773            Turn::user_payload("c1", "from A", 1),
774        );
775        b.observe(&a1.hlc);
776        let b1 = b.append(
777            Scope::Personal,
778            Surface::Conversation,
779            Turn::assistant_payload("c1", "B replies to A", vec![], 2),
780        );
781        let a2 = a.append(
782            Scope::Personal,
783            Surface::Conversation,
784            Turn::user_payload("c1", "A concurrent", 3),
785        );
786        let b2 = b.append(
787            Scope::Personal,
788            Surface::Conversation,
789            Turn::user_payload("c1", "B concurrent", 3),
790        );
791
792        let ops = vec![a1, b1, a2, b2];
793        let baseline = fold(&ops).transcript("c1");
794        assert_eq!(baseline.len(), 4);
795        let texts: Vec<&str> = baseline.iter().map(|t| t.content.as_str()).collect();
796        let pos = |s: &str| texts.iter().position(|t| *t == s).unwrap();
797        assert_eq!(pos("from A"), 0);
798        assert!(pos("from A") < pos("B replies to A"), "causality survives");
799
800        let baseline_hash = state_hash(&fold(&ops));
801        for perm in permutations(&ops) {
802            let folded = fold(&perm);
803            assert_eq!(
804                folded.transcript("c1"),
805                baseline,
806                "transcript is delivery-order-independent"
807            );
808            assert_eq!(state_hash(&folded), baseline_hash);
809        }
810    }
811
812    #[test]
813    fn transcripts_are_partitioned_by_conversation_id() {
814        let ops = {
815            let mut v = one_device_conversation("work");
816            let mut d = DeviceLog::new("dev-b");
817            v.push(d.append(
818                Scope::Personal,
819                Surface::Conversation,
820                Turn::user_payload("home", "dinner?", 20),
821            ));
822            v
823        };
824        let state = fold(&ops);
825        assert_eq!(
826            state.conversation_ids(),
827            vec!["home".to_string(), "work".to_string()]
828        );
829        assert_eq!(state.transcript("work").len(), 4);
830        assert_eq!(state.transcript("home").len(), 1);
831        assert!(state.transcript("nonexistent").is_empty());
832    }
833
834    #[test]
835    fn legacy_speaker_text_turns_project_and_resume() {
836        let mut d = DeviceLog::new("dev-a");
837        let ops = vec![
838            d.append(
839                Scope::Personal,
840                Surface::Conversation,
841                json!({"speaker": "user", "text": "hi", "timestamp": 1}),
842            ),
843            d.append(
844                Scope::Personal,
845                Surface::Conversation,
846                json!({"speaker": "assistant", "text": "hello", "timestamp": 2}),
847            ),
848        ];
849        let state = fold(&ops);
850        let turns = state.transcript(DEFAULT_CONVERSATION);
851        assert_eq!(turns.len(), 2);
852        assert_eq!(
853            (turns[0].role, turns[1].role),
854            (Role::User, Role::Assistant)
855        );
856        let ms = state.resume_messages(DEFAULT_CONVERSATION);
857        assert_provider_valid(&ms);
858        assert!(matches!(&ms[0], Message::User { content } if content == "hi"));
859        assert!(matches!(&ms[1], Message::Assistant { content, .. } if content == "hello"));
860    }
861
862    #[test]
863    fn lastn_compaction_keeps_the_last_n_in_order_and_round_trips() {
864        // Conversation is an event stream (op_id-keyed) but INDEPENDENT, so
865        // LastN is allowed and works. After LastN{2} the resumable transcript is
866        // the retained snapshot window + live tail, in order — the same folded
867        // state compaction produced (0.25 incoherence cannot recur).
868        let mut a = DeviceLog::new("dev-a");
869        let mut b = DeviceLog::new("dev-b");
870        let mut ops = vec![
871            a.append(
872                Scope::Personal,
873                Surface::Conversation,
874                Turn::user_payload("c1", "t0", 100),
875            ),
876            a.append(
877                Scope::Personal,
878                Surface::Conversation,
879                Turn::assistant_payload("c1", "t1", vec![], 101),
880            ),
881            a.append(
882                Scope::Personal,
883                Surface::Conversation,
884                Turn::user_payload("c1", "t2", 102),
885            ),
886            a.append(
887                Scope::Personal,
888                Surface::Conversation,
889                Turn::assistant_payload("c1", "t3", vec![], 103),
890            ),
891        ];
892        let split = ops.len();
893        for op in &ops {
894            b.observe(&op.hlc);
895        }
896        ops.push(b.append(
897            Scope::Personal,
898            Surface::Conversation,
899            Turn::user_payload("c1", "t4", 104),
900        ));
901        ops.push(b.append(
902            Scope::Personal,
903            Surface::Conversation,
904            Turn::assistant_payload("c1", "t5", vec![], 105),
905        ));
906
907        let frontier = ops[..split].iter().map(|o| o.hlc.clone()).max().unwrap();
908        let mut acks = AckTable::new();
909        for op in &ops {
910            acks.ack(op.device_id.clone(), frontier.clone());
911        }
912        let mut policy = RetentionPolicy::keep_all();
913        policy
914            .rules
915            .insert("conversation".to_string(), RetentionRule::LastN { n: 2 });
916        let plan = plan_compaction(&ops, &acks, &policy, Some(1_000)).unwrap();
917
918        let ckpt = plan.checkpoint.state.transcript("c1");
919        assert_eq!(
920            ckpt.iter().map(|t| t.content.as_str()).collect::<Vec<_>>(),
921            vec!["t2", "t3"]
922        );
923
924        // Checkpoint round-trip: serialize+deserialize; transcript unchanged.
925        let ckpt_json = serde_json::to_string(&plan.checkpoint.state).unwrap();
926        let ckpt_back: SyncState = serde_json::from_str(&ckpt_json).unwrap();
927        assert_eq!(
928            ckpt_back.transcript("c1"),
929            plan.checkpoint.state.transcript("c1")
930        );
931
932        let reconstructed = fold_onto(&plan.checkpoint.state, &plan.retained_ops);
933        let resumed: Vec<String> = reconstructed
934            .transcript("c1")
935            .iter()
936            .map(|t| t.content.clone())
937            .collect();
938        assert_eq!(
939            resumed,
940            vec!["t2", "t3", "t4", "t5"],
941            "resume = retained window + live tail, in order"
942        );
943        assert_provider_valid(&reconstructed.resume_messages("c1"));
944
945        let (global, _) = apply_retention(&fold(&ops), &policy, 1_000).unwrap();
946        let (local, _) = apply_retention(&reconstructed, &policy, 1_000).unwrap();
947        assert_eq!(local.transcript("c1"), global.transcript("c1"));
948        assert_eq!(
949            global
950                .transcript("c1")
951                .iter()
952                .map(|t| t.content.clone())
953                .collect::<Vec<_>>(),
954            vec!["t4", "t5"],
955            "the last-N display window is the same on every device"
956        );
957        assert_eq!(state_hash(&local), state_hash(&global));
958    }
959
960    /// Heap's algorithm — every permutation, no rand dependency.
961    fn permutations<T: Clone>(items: &[T]) -> Vec<Vec<T>> {
962        fn heap<T: Clone>(k: usize, arr: &mut Vec<T>, out: &mut Vec<Vec<T>>) {
963            if k == 1 {
964                out.push(arr.clone());
965                return;
966            }
967            for i in 0..k {
968                heap(k - 1, arr, out);
969                if k.is_multiple_of(2) {
970                    arr.swap(i, k - 1);
971                } else {
972                    arr.swap(0, k - 1);
973                }
974            }
975        }
976        let mut arr = items.to_vec();
977        let mut out = Vec::new();
978        heap(arr.len(), &mut arr, &mut out);
979        out
980    }
981}