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                // Cross-session thinking-block resume is a follow-up: the oplog
286                // Turn does not (yet) record thinking, so resumed turns replay
287                // without it. Empty keeps the wire valid (Anthropic drops absent
288                // thinking silently on a fresh session's first turn).
289                thinking: Vec::new(),
290            },
291            Role::Tool => Message::ToolResult {
292                tool_use_id: self.tool_use_id.clone().unwrap_or_default(),
293                content: self.content.clone(),
294            },
295        }
296    }
297}
298
299/// Join two turn bodies for a coalesced turn (skip an empty side).
300fn join_content(a: &str, b: &str) -> String {
301    match (a.is_empty(), b.is_empty()) {
302        (true, _) => b.to_string(),
303        (_, true) => a.to_string(),
304        _ => format!("{a}\n\n{b}"),
305    }
306}
307
308/// Repair an ordered transcript into a **provider-valid** `Message` sequence.
309///
310/// The raw transcript is causally ordered but not provider-valid: concurrent
311/// turns can produce invalid adjacencies (`[user, assistant, assistant]` →
312/// Anthropic 400), and a `LastN` window can cut inside a tool exchange leaving
313/// an orphan `tool_result` at the head (also a 400). This is the runtime
314/// validating its own projection. Guarantees on the output:
315///
316/// 1. **No adjacent same-role messages** — consecutive `User`s (or `Assistant`s)
317///    are coalesced into one, their bodies joined and (for assistants) their
318///    tool_calls concatenated. Two concurrent replies to one user turn merge;
319///    an assistant "threaded after" an unrelated user turn it never observed is
320///    merged rather than mis-attributed (best-effort — the deterministic order
321///    is preserved, the invalid adjacency is not emitted).
322/// 2. **No orphan `tool_result`** — a `Tool` turn is kept only if it answers a
323///    preceding assistant that carried `tool_calls` (or a run of such results);
324///    otherwise it is dropped (the `LastN`-cut-mid-exchange case).
325/// 3. **No dangling assistant `tool_call`** — an assistant whose `tool_calls`
326///    are not answered by a following `tool_result` has its calls stripped
327///    (kept as a plain text turn), so the sequence never presents an
328///    unanswered tool_use.
329///
330/// Leading-role normalization (ensuring the sequence *starts* with a user turn,
331/// a per-provider requirement) is the caller/protocol-handler's concern — it
332/// already folds the system prompt and prepends the next user message; `repair`
333/// only guarantees internal adjacency + tool-pairing validity.
334pub fn repair(turns: Vec<Turn>) -> Vec<Message> {
335    let mut out: Vec<Turn> = Vec::new();
336    // Does the last emitted turn leave a tool exchange open (an assistant with
337    // tool_calls, or a tool_result continuing one)? Only then is a tool_result
338    // valid.
339    let mut tool_open = false;
340    for t in turns {
341        match t.role {
342            Role::Tool => {
343                if tool_open {
344                    out.push(t); // a valid result; the exchange stays open
345                }
346                // else: orphan tool_result → dropped
347            }
348            Role::User => {
349                if let Some(last) = out.last_mut() {
350                    if last.role == Role::User {
351                        last.content = join_content(&last.content, &t.content);
352                        continue;
353                    }
354                }
355                tool_open = false;
356                out.push(t);
357            }
358            Role::Assistant => {
359                if let Some(last) = out.last_mut() {
360                    if last.role == Role::Assistant {
361                        last.content = join_content(&last.content, &t.content);
362                        last.tool_calls.extend(t.tool_calls);
363                        tool_open = !last.tool_calls.is_empty();
364                        continue;
365                    }
366                }
367                tool_open = !t.tool_calls.is_empty();
368                out.push(t);
369            }
370        }
371    }
372    // Post-pass: strip a dangling assistant tool_call (no following tool_result),
373    // so no unanswered tool_use is ever presented to a provider.
374    for i in 0..out.len() {
375        if out[i].role == Role::Assistant && !out[i].tool_calls.is_empty() {
376            let answered = out.get(i + 1).is_some_and(|n| n.role == Role::Tool);
377            if !answered {
378                out[i].tool_calls.clear();
379            }
380        }
381    }
382    out.iter().map(Turn::to_message).collect()
383}
384
385impl SyncState {
386    /// The ordered, role-threaded transcript for one conversation — the
387    /// causally `(hlc, op_id)`-ordered `Vec<Turn>` (B2). This is the raw
388    /// projection (every folded turn, in order); [`SyncState::resume_messages`]
389    /// is the provider-valid `Message` view. Turns whose payload names no
390    /// `conversation_id` belong to [`DEFAULT_CONVERSATION`]; tombstone stubs are
391    /// skipped. Order-independent of delivery, byte-identical on every device
392    /// that folded the same op-set.
393    pub fn transcript(&self, conversation_id: &str) -> Vec<Turn> {
394        self.log_entries(&crate::oplog::Surface::Conversation.tag())
395            .into_iter()
396            .filter_map(Turn::from_record)
397            .filter(|t| t.conversation_id == conversation_id)
398            .collect()
399    }
400
401    /// Every conversation id present in the folded state, in stable sorted
402    /// order (includes [`DEFAULT_CONVERSATION`] when unnamed turns exist).
403    pub fn conversation_ids(&self) -> Vec<String> {
404        let mut ids: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
405        for rec in self.log_entries(&crate::oplog::Surface::Conversation.tag()) {
406            if let Some(turn) = Turn::from_record(rec) {
407                ids.insert(turn.conversation_id);
408            }
409        }
410        ids.into_iter().collect()
411    }
412
413    /// Reconstruct the runtime's multi-turn conversation state: the ordered,
414    /// **provider-valid** [`car_inference_types::Message`] sequence
415    /// car-inference's multi-turn path replays to continue the conversation
416    /// (B2's resume bridge). The raw transcript is [`repair`]ed first, so the
417    /// result never contains an invalid role adjacency or an orphan/dangling
418    /// tool exchange. The daemon/memgine adoption is B6.
419    pub fn resume_messages(&self, conversation_id: &str) -> Vec<Message> {
420        repair(self.transcript(conversation_id))
421    }
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427    use crate::compact::{
428        apply_retention, plan_compaction, AckTable, RetentionPolicy, RetentionRule,
429    };
430    use crate::fold::{fold, fold_onto, state_hash};
431    use crate::oplog::{DeviceLog, Scope, Surface};
432
433    /// Assert a repaired sequence is provider-valid: no adjacent same-role
434    /// (assistant/assistant, user/user), no orphan/leading tool_result, no
435    /// dangling assistant tool_call.
436    fn assert_provider_valid(ms: &[Message]) {
437        for (i, w) in ms.windows(2).enumerate() {
438            let dup = matches!(
439                (&w[0], &w[1]),
440                (Message::Assistant { .. }, Message::Assistant { .. })
441                    | (Message::User { .. }, Message::User { .. })
442            );
443            assert!(!dup, "invalid adjacency at {i}: {:?} then {:?}", w[0], w[1]);
444        }
445        for (i, m) in ms.iter().enumerate() {
446            if matches!(m, Message::ToolResult { .. }) {
447                let opens_here = i > 0
448                    && (matches!(&ms[i - 1], Message::Assistant { tool_calls, .. } if !tool_calls.is_empty())
449                        || matches!(&ms[i - 1], Message::ToolResult { .. }));
450                assert!(opens_here, "orphan tool_result at index {i}");
451            }
452            if let Message::Assistant { tool_calls, .. } = m {
453                if !tool_calls.is_empty() {
454                    let answered = ms
455                        .get(i + 1)
456                        .is_some_and(|n| matches!(n, Message::ToolResult { .. }));
457                    assert!(answered, "dangling assistant tool_call at index {i}");
458                }
459            }
460        }
461    }
462
463    /// Append the three turn kinds to one conversation on a single device.
464    fn one_device_conversation(conv: &str) -> Vec<crate::oplog::OpRecord> {
465        let mut d = DeviceLog::new("dev-a");
466        vec![
467            d.append(
468                Scope::Personal,
469                Surface::Conversation,
470                Turn::user_payload(conv, "what's the weather?", 10),
471            ),
472            d.append(
473                Scope::Personal,
474                Surface::Conversation,
475                Turn::assistant_payload(
476                    conv,
477                    "",
478                    vec![
479                        json!({"id": "call_0", "name": "get_weather", "arguments": {"city": "SF"}}),
480                    ],
481                    11,
482                ),
483            ),
484            d.append(
485                Scope::Personal,
486                Surface::Conversation,
487                Turn::tool_payload(conv, "call_0", "sunny, 72F", 12),
488            ),
489            d.append(
490                Scope::Personal,
491                Surface::Conversation,
492                Turn::assistant_payload(conv, "It's sunny and 72F in SF.", vec![], 13),
493            ),
494        ]
495    }
496
497    #[test]
498    fn transcript_folds_in_causal_order_regardless_of_delivery() {
499        let ops = one_device_conversation("c1");
500        let expected = [
501            "what's the weather?",
502            "",
503            "sunny, 72F",
504            "It's sunny and 72F in SF.",
505        ];
506        for delivery in [ops.clone(), ops.iter().rev().cloned().collect::<Vec<_>>()] {
507            let turns = fold(&delivery).transcript("c1");
508            let texts: Vec<&str> = turns.iter().map(|t| t.content.as_str()).collect();
509            assert_eq!(texts, expected);
510            assert_eq!(
511                turns.iter().map(|t| t.role).collect::<Vec<_>>(),
512                vec![Role::User, Role::Assistant, Role::Tool, Role::Assistant]
513            );
514        }
515    }
516
517    #[test]
518    fn resume_produces_a_valid_message_sequence_of_the_real_type() {
519        // The resume bridge builds the REAL Message type (compile-checked), and
520        // the sequence is provider-valid.
521        let ops = one_device_conversation("c1");
522        let messages: Vec<Message> = fold(&ops).resume_messages("c1");
523        assert_eq!(messages.len(), 4);
524        assert_provider_valid(&messages);
525
526        match &messages[0] {
527            Message::User { content } => assert_eq!(content, "what's the weather?"),
528            other => panic!("turn 0 should be a user message, got {other:?}"),
529        }
530        match &messages[1] {
531            Message::Assistant { tool_calls, .. } => {
532                assert_eq!(
533                    tool_calls.len(),
534                    1,
535                    "assistant tool_calls round-trip as the real ToolCall"
536                );
537                assert_eq!(tool_calls[0].name, "get_weather");
538            }
539            other => panic!("turn 1 should be an assistant tool call, got {other:?}"),
540        }
541        match &messages[2] {
542            Message::ToolResult {
543                tool_use_id,
544                content,
545            } => {
546                assert_eq!(tool_use_id, "call_0");
547                assert_eq!(content, "sunny, 72F");
548            }
549            other => panic!("turn 2 should be a tool_result, got {other:?}"),
550        }
551        match &messages[3] {
552            Message::Assistant {
553                content,
554                tool_calls,
555                ..
556            } => {
557                assert_eq!(content, "It's sunny and 72F in SF.");
558                assert!(tool_calls.is_empty());
559            }
560            other => panic!("turn 3 should be a plain assistant reply, got {other:?}"),
561        }
562    }
563
564    // ------------------------------------------------------------------
565    // CRIT-2 (reproduced): content-keyed identity DROPPED distinct turns. Now a
566    // conversation turn is an event stream — op identity is turn identity — so
567    // two distinct authorings never collapse; only a resent op dedups.
568    // ------------------------------------------------------------------
569    #[test]
570    fn crit2_two_genuine_same_payload_turns_do_not_collapse() {
571        // Two genuine user "yes" turns stamped at the SAME payload timestamp
572        // (second-granularity clock / rapid double-confirm). Under the old
573        // content-key fold these were ONE entry (silent data loss). As an event
574        // stream they are two distinct ops → two transcript entries.
575        let mut d = DeviceLog::new("dev-a");
576        let yes = || Turn::user_payload("c1", "yes", 5); // identical payload incl. timestamp
577        let o1 = d.append(Scope::Personal, Surface::Conversation, yes());
578        let o2 = d.append(Scope::Personal, Surface::Conversation, yes());
579        assert_ne!(
580            o1.op_id, o2.op_id,
581            "distinct ops (different seq/hlc) → distinct op_id"
582        );
583        assert_eq!(
584            fold(&[o1.clone(), o2]).transcript("c1").len(),
585            2,
586            "both genuine turns survive (CRIT-2 fixed)"
587        );
588        // A RESENT op (same op_id, retransmission) still dedups to one.
589        assert_eq!(
590            fold(&[o1.clone(), o1]).transcript("c1").len(),
591            1,
592            "resent op dedups on op_id"
593        );
594    }
595
596    #[test]
597    fn same_payload_turns_on_two_devices_are_distinct_events() {
598        // Two devices independently authoring a byte-identical turn are TWO
599        // events (distinct op_id via distinct device_id), not one.
600        let mut a = DeviceLog::new("dev-a");
601        let mut b = DeviceLog::new("dev-b");
602        let payload = Turn::user_payload("c1", "hello", 5);
603        let oa = a.append(Scope::Personal, Surface::Conversation, payload.clone());
604        let ob = b.append(Scope::Personal, Surface::Conversation, payload);
605        assert_eq!(fold(&[oa, ob]).transcript("c1").len(), 2);
606    }
607
608    // ------------------------------------------------------------------
609    // CRIT-1 (reproduced): concurrent-device replies produced an invalid
610    // [user, assistant, assistant] adjacency. resume_messages now repairs it.
611    // ------------------------------------------------------------------
612    #[test]
613    fn crit1_concurrent_assistant_replies_repair_to_a_valid_sequence() {
614        let mut a = DeviceLog::new("dev-a");
615        let mut b = DeviceLog::new("dev-b");
616        let u = a.append(
617            Scope::Personal,
618            Surface::Conversation,
619            Turn::user_payload("c1", "hi", 1),
620        );
621        b.observe(&u.hlc);
622        // Two concurrent replies to u (neither observed the other).
623        let ra = a.append(
624            Scope::Personal,
625            Surface::Conversation,
626            Turn::assistant_payload("c1", "reply A", vec![], 2),
627        );
628        let rb = b.append(
629            Scope::Personal,
630            Surface::Conversation,
631            Turn::assistant_payload("c1", "reply B", vec![], 2),
632        );
633
634        let ops = vec![u, ra, rb];
635        // Raw transcript has the invalid [user, assistant, assistant]…
636        let raw = fold(&ops).transcript("c1");
637        assert_eq!(raw.len(), 3);
638        assert_eq!(
639            (raw[1].role, raw[2].role),
640            (Role::Assistant, Role::Assistant)
641        );
642        // …but resume repairs it, order-independently over every delivery.
643        let baseline = fold(&ops).resume_messages("c1");
644        assert_eq!(baseline.len(), 2, "the two concurrent replies coalesce");
645        assert_provider_valid(&baseline);
646        assert!(matches!(&baseline[0], Message::User { .. }));
647        assert!(
648            matches!(&baseline[1], Message::Assistant { content, .. } if content.contains("reply A") && content.contains("reply B"))
649        );
650        for perm in permutations(&ops) {
651            assert_eq!(
652                fold(&perm).resume_messages("c1"),
653                baseline,
654                "repair is delivery-order-independent"
655            );
656        }
657    }
658
659    #[test]
660    fn adjacent_user_turns_coalesce_before_a_reply() {
661        // Two user turns land back-to-back (userA, then userB observing it),
662        // then a reply that observed both. Raw = [user, user, assistant] — the
663        // two users are an invalid adjacency. Repair coalesces them so the
664        // assistant follows a single merged user context, never a mis-thread.
665        let mut a = DeviceLog::new("dev-a");
666        let mut b = DeviceLog::new("dev-b");
667        let ua = a.append(
668            Scope::Personal,
669            Surface::Conversation,
670            Turn::user_payload("c1", "userA", 1),
671        );
672        b.observe(&ua.hlc);
673        let ub = b.append(
674            Scope::Personal,
675            Surface::Conversation,
676            Turn::user_payload("c1", "userB", 2),
677        );
678        a.observe(&ub.hlc);
679        let ra = a.append(
680            Scope::Personal,
681            Surface::Conversation,
682            Turn::assistant_payload("c1", "reply", vec![], 3),
683        );
684
685        let ops = vec![ua, ub, ra];
686        assert_eq!(
687            fold(&ops)
688                .transcript("c1")
689                .iter()
690                .map(|t| t.role)
691                .collect::<Vec<_>>(),
692            vec![Role::User, Role::User, Role::Assistant],
693            "raw has the invalid user/user adjacency"
694        );
695        let ms = fold(&ops).resume_messages("c1");
696        assert_eq!(ms.len(), 2, "the two users coalesce");
697        assert_provider_valid(&ms);
698        assert!(
699            matches!(&ms[0], Message::User { content } if content.contains("userA") && content.contains("userB"))
700        );
701        assert!(matches!(&ms[1], Message::Assistant { .. }));
702    }
703
704    // ------------------------------------------------------------------
705    // CRIT-3 (reproduced): a LastN window cut inside a tool exchange orphaned a
706    // leading tool_result. resume_messages drops it.
707    // ------------------------------------------------------------------
708    #[test]
709    fn crit3_lastn_orphan_tool_result_is_dropped_on_resume() {
710        // [user, assistant(tool_call), tool_result, assistant] under LastN{2}
711        // retains [tool_result, assistant] — a LEADING orphan tool_result
712        // (provider 400). (This ALSO exercises that LastN is ALLOWED on the
713        // event-stream conversation surface — the retention-guard reconciliation.)
714        let ops = one_device_conversation("c1"); // ts 10..13
715        let mut policy = RetentionPolicy::keep_all();
716        policy
717            .rules
718            .insert("conversation".to_string(), RetentionRule::LastN { n: 2 });
719        let (retained, _) = apply_retention(&fold(&ops), &policy, 1_000).unwrap();
720
721        let raw = retained.transcript("c1");
722        assert_eq!(
723            raw.iter().map(|t| t.role).collect::<Vec<_>>(),
724            vec![Role::Tool, Role::Assistant],
725            "the retained window is the orphan [tool_result, assistant]"
726        );
727
728        let ms = retained.resume_messages("c1");
729        assert!(
730            !matches!(ms.first(), Some(Message::ToolResult { .. })),
731            "leading orphan tool_result dropped"
732        );
733        assert_provider_valid(&ms);
734        assert_eq!(ms.len(), 1);
735        assert!(matches!(&ms[0], Message::Assistant { .. }));
736    }
737
738    #[test]
739    fn repair_drops_a_leading_orphan_tool_result_directly() {
740        // Unit-level: repair guarantees no leading/orphan tool_result even from
741        // a hand-built transcript that starts mid-exchange.
742        let hlc = Hlc {
743            wall_ms: 0,
744            counter: 0,
745            device_id: "d".into(),
746        };
747        let orphan = Turn {
748            conversation_id: "c".into(),
749            role: Role::Tool,
750            content: "res".into(),
751            tool_calls: vec![],
752            tool_use_id: Some("call_0".into()),
753            timestamp: 1,
754            hlc: hlc.clone(),
755            op_id: "op-x".into(),
756        };
757        let asst = Turn {
758            conversation_id: "c".into(),
759            role: Role::Assistant,
760            content: "done".into(),
761            tool_calls: vec![],
762            tool_use_id: None,
763            timestamp: 2,
764            hlc,
765            op_id: "op-y".into(),
766        };
767        let ms = repair(vec![orphan, asst]);
768        assert!(!matches!(ms.first(), Some(Message::ToolResult { .. })));
769        assert_provider_valid(&ms);
770    }
771
772    #[test]
773    fn concurrent_device_turns_interleave_deterministically_and_order_independently() {
774        let mut a = DeviceLog::new("dev-a");
775        let mut b = DeviceLog::new("dev-b");
776        let a1 = a.append(
777            Scope::Personal,
778            Surface::Conversation,
779            Turn::user_payload("c1", "from A", 1),
780        );
781        b.observe(&a1.hlc);
782        let b1 = b.append(
783            Scope::Personal,
784            Surface::Conversation,
785            Turn::assistant_payload("c1", "B replies to A", vec![], 2),
786        );
787        let a2 = a.append(
788            Scope::Personal,
789            Surface::Conversation,
790            Turn::user_payload("c1", "A concurrent", 3),
791        );
792        let b2 = b.append(
793            Scope::Personal,
794            Surface::Conversation,
795            Turn::user_payload("c1", "B concurrent", 3),
796        );
797
798        let ops = vec![a1, b1, a2, b2];
799        let baseline = fold(&ops).transcript("c1");
800        assert_eq!(baseline.len(), 4);
801        let texts: Vec<&str> = baseline.iter().map(|t| t.content.as_str()).collect();
802        let pos = |s: &str| texts.iter().position(|t| *t == s).unwrap();
803        assert_eq!(pos("from A"), 0);
804        assert!(pos("from A") < pos("B replies to A"), "causality survives");
805
806        let baseline_hash = state_hash(&fold(&ops));
807        for perm in permutations(&ops) {
808            let folded = fold(&perm);
809            assert_eq!(
810                folded.transcript("c1"),
811                baseline,
812                "transcript is delivery-order-independent"
813            );
814            assert_eq!(state_hash(&folded), baseline_hash);
815        }
816    }
817
818    #[test]
819    fn transcripts_are_partitioned_by_conversation_id() {
820        let ops = {
821            let mut v = one_device_conversation("work");
822            let mut d = DeviceLog::new("dev-b");
823            v.push(d.append(
824                Scope::Personal,
825                Surface::Conversation,
826                Turn::user_payload("home", "dinner?", 20),
827            ));
828            v
829        };
830        let state = fold(&ops);
831        assert_eq!(
832            state.conversation_ids(),
833            vec!["home".to_string(), "work".to_string()]
834        );
835        assert_eq!(state.transcript("work").len(), 4);
836        assert_eq!(state.transcript("home").len(), 1);
837        assert!(state.transcript("nonexistent").is_empty());
838    }
839
840    #[test]
841    fn legacy_speaker_text_turns_project_and_resume() {
842        let mut d = DeviceLog::new("dev-a");
843        let ops = vec![
844            d.append(
845                Scope::Personal,
846                Surface::Conversation,
847                json!({"speaker": "user", "text": "hi", "timestamp": 1}),
848            ),
849            d.append(
850                Scope::Personal,
851                Surface::Conversation,
852                json!({"speaker": "assistant", "text": "hello", "timestamp": 2}),
853            ),
854        ];
855        let state = fold(&ops);
856        let turns = state.transcript(DEFAULT_CONVERSATION);
857        assert_eq!(turns.len(), 2);
858        assert_eq!(
859            (turns[0].role, turns[1].role),
860            (Role::User, Role::Assistant)
861        );
862        let ms = state.resume_messages(DEFAULT_CONVERSATION);
863        assert_provider_valid(&ms);
864        assert!(matches!(&ms[0], Message::User { content } if content == "hi"));
865        assert!(matches!(&ms[1], Message::Assistant { content, .. } if content == "hello"));
866    }
867
868    #[test]
869    fn lastn_compaction_keeps_the_last_n_in_order_and_round_trips() {
870        // Conversation is an event stream (op_id-keyed) but INDEPENDENT, so
871        // LastN is allowed and works. After LastN{2} the resumable transcript is
872        // the retained snapshot window + live tail, in order — the same folded
873        // state compaction produced (0.25 incoherence cannot recur).
874        let mut a = DeviceLog::new("dev-a");
875        let mut b = DeviceLog::new("dev-b");
876        let mut ops = vec![
877            a.append(
878                Scope::Personal,
879                Surface::Conversation,
880                Turn::user_payload("c1", "t0", 100),
881            ),
882            a.append(
883                Scope::Personal,
884                Surface::Conversation,
885                Turn::assistant_payload("c1", "t1", vec![], 101),
886            ),
887            a.append(
888                Scope::Personal,
889                Surface::Conversation,
890                Turn::user_payload("c1", "t2", 102),
891            ),
892            a.append(
893                Scope::Personal,
894                Surface::Conversation,
895                Turn::assistant_payload("c1", "t3", vec![], 103),
896            ),
897        ];
898        let split = ops.len();
899        for op in &ops {
900            b.observe(&op.hlc);
901        }
902        ops.push(b.append(
903            Scope::Personal,
904            Surface::Conversation,
905            Turn::user_payload("c1", "t4", 104),
906        ));
907        ops.push(b.append(
908            Scope::Personal,
909            Surface::Conversation,
910            Turn::assistant_payload("c1", "t5", vec![], 105),
911        ));
912
913        let frontier = ops[..split].iter().map(|o| o.hlc.clone()).max().unwrap();
914        let mut acks = AckTable::new();
915        for op in &ops {
916            acks.ack(op.device_id.clone(), frontier.clone());
917        }
918        let mut policy = RetentionPolicy::keep_all();
919        policy
920            .rules
921            .insert("conversation".to_string(), RetentionRule::LastN { n: 2 });
922        let plan = plan_compaction(&ops, &acks, &policy, Some(1_000)).unwrap();
923
924        let ckpt = plan.checkpoint.state.transcript("c1");
925        assert_eq!(
926            ckpt.iter().map(|t| t.content.as_str()).collect::<Vec<_>>(),
927            vec!["t2", "t3"]
928        );
929
930        // Checkpoint round-trip: serialize+deserialize; transcript unchanged.
931        let ckpt_json = serde_json::to_string(&plan.checkpoint.state).unwrap();
932        let ckpt_back: SyncState = serde_json::from_str(&ckpt_json).unwrap();
933        assert_eq!(
934            ckpt_back.transcript("c1"),
935            plan.checkpoint.state.transcript("c1")
936        );
937
938        let reconstructed = fold_onto(&plan.checkpoint.state, &plan.retained_ops);
939        let resumed: Vec<String> = reconstructed
940            .transcript("c1")
941            .iter()
942            .map(|t| t.content.clone())
943            .collect();
944        assert_eq!(
945            resumed,
946            vec!["t2", "t3", "t4", "t5"],
947            "resume = retained window + live tail, in order"
948        );
949        assert_provider_valid(&reconstructed.resume_messages("c1"));
950
951        let (global, _) = apply_retention(&fold(&ops), &policy, 1_000).unwrap();
952        let (local, _) = apply_retention(&reconstructed, &policy, 1_000).unwrap();
953        assert_eq!(local.transcript("c1"), global.transcript("c1"));
954        assert_eq!(
955            global
956                .transcript("c1")
957                .iter()
958                .map(|t| t.content.clone())
959                .collect::<Vec<_>>(),
960            vec!["t4", "t5"],
961            "the last-N display window is the same on every device"
962        );
963        assert_eq!(state_hash(&local), state_hash(&global));
964    }
965
966    /// Heap's algorithm — every permutation, no rand dependency.
967    fn permutations<T: Clone>(items: &[T]) -> Vec<Vec<T>> {
968        fn heap<T: Clone>(k: usize, arr: &mut Vec<T>, out: &mut Vec<Vec<T>>) {
969            if k == 1 {
970                out.push(arr.clone());
971                return;
972            }
973            for i in 0..k {
974                heap(k - 1, arr, out);
975                if k.is_multiple_of(2) {
976                    arr.swap(i, k - 1);
977                } else {
978                    arr.swap(0, k - 1);
979                }
980            }
981        }
982        let mut arr = items.to_vec();
983        let mut out = Vec::new();
984        heap(arr.len(), &mut arr, &mut out);
985        out
986    }
987}