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