Skip to main content

codewhale_runtime/
session_tree.rs

1use chrono::{DateTime, Utc};
2use codewhale_models::{ContentBlock, Message, Role};
3use serde::{Deserialize, Serialize};
4use std::collections::{HashMap, HashSet};
5use std::sync::Arc;
6pub const CURRENT_JOURNAL_SCHEMA_VERSION: u32 = 1;
7pub type EntryId = String;
8#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
9pub struct SpawnDepth(pub u32);
10impl SpawnDepth {
11    pub fn next(self) -> Self {
12        Self(self.0.saturating_add(1))
13    }
14}
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
16#[serde(tag = "kind", rename_all = "snake_case")]
17pub enum SessionEntryKind {
18    Message {
19        message: Message,
20    },
21    User {
22        text: String,
23    },
24    Assistant {
25        text: String,
26    },
27    Compaction {
28        summary: String,
29        #[serde(default, skip_serializing_if = "Option::is_none")]
30        tokens_before: Option<u64>,
31        #[serde(default, skip_serializing_if = "Option::is_none")]
32        tokens_after: Option<u64>,
33        #[serde(default, skip_serializing_if = "Option::is_none")]
34        model: Option<String>,
35    },
36    BranchSummary {
37        branch_id: String,
38        summary: String,
39        #[serde(default, skip_serializing_if = "Option::is_none")]
40        parent_branch_id: Option<String>,
41    },
42    System {
43        content: String,
44    },
45}
46impl SessionEntryKind {
47    pub fn is_contextual(&self) -> bool {
48        matches!(
49            self,
50            Self::Message { .. } | Self::User { .. } | Self::Assistant { .. }
51        )
52    }
53    pub fn projects_to(&self, message: &Message) -> bool {
54        match self {
55            Self::Message { message: own } => {
56                codewhale_models::turn_classify::same_recorded_turn(own, message)
57            }
58            other => other.as_message().as_ref() == Some(message),
59        }
60    }
61    pub fn as_message(&self) -> Option<Message> {
62        match self {
63            Self::Message { message } => Some(message.clone()),
64            Self::User { text } => Some(Message {
65                role: Role::User,
66                content: vec![ContentBlock::Text {
67                    text: text.clone(),
68                    cache_control: None,
69                }],
70            }),
71            Self::Assistant { text } => Some(Message {
72                role: Role::Assistant,
73                content: vec![ContentBlock::Text {
74                    text: text.clone(),
75                    cache_control: None,
76                }],
77            }),
78            Self::Compaction { summary, .. } => Some(Message {
79                role: Role::System,
80                content: vec![ContentBlock::Text {
81                    text: format!("[compaction summary] {summary}"),
82                    cache_control: None,
83                }],
84            }),
85            Self::BranchSummary { summary, .. } => Some(Message {
86                role: Role::System,
87                content: vec![ContentBlock::Text {
88                    text: format!("[branch summary] {summary}"),
89                    cache_control: None,
90                }],
91            }),
92            Self::System { content } => Some(Message {
93                role: Role::System,
94                content: vec![ContentBlock::Text {
95                    text: content.clone(),
96                    cache_control: None,
97                }],
98            }),
99        }
100    }
101}
102#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
103pub struct SessionEntry {
104    pub id: EntryId,
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub parent_id: Option<EntryId>,
107    #[serde(flatten)]
108    pub kind: Arc<SessionEntryKind>,
109    pub created_at: DateTime<Utc>,
110    #[serde(default)]
111    pub spawn_depth: u32,
112}
113impl SessionEntry {
114    pub fn new(kind: SessionEntryKind, parent_id: Option<EntryId>, spawn_depth: u32) -> Self {
115        Self {
116            id: uuid::Uuid::new_v4().to_string(),
117            parent_id,
118            kind: Arc::new(kind),
119            created_at: Utc::now(),
120            spawn_depth,
121        }
122    }
123    pub fn short_id(&self) -> &str {
124        char_prefix(&self.id, 8)
125    }
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub struct Rebranch {
130    pub previous_active: usize,
131    pub shared_prefix: usize,
132    pub kept_recorded_metadata: bool,
133}
134
135impl Rebranch {
136    #[must_use]
137    pub fn replaced_from_root(&self) -> bool {
138        self.previous_active > 0 && self.shared_prefix == 0
139    }
140}
141#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
142pub struct SessionJournal {
143    #[serde(default)]
144    pub entries: Vec<SessionEntry>,
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub leaf_id: Option<EntryId>,
147    #[serde(default = "default_journal_schema_version")]
148    pub schema_version: u32,
149    #[serde(default)]
150    pub spawn_depth: u32,
151}
152fn default_journal_schema_version() -> u32 {
153    CURRENT_JOURNAL_SCHEMA_VERSION
154}
155impl SessionJournal {
156    pub fn new() -> Self {
157        Self {
158            entries: Vec::new(),
159            leaf_id: None,
160            schema_version: CURRENT_JOURNAL_SCHEMA_VERSION,
161            spawn_depth: 0,
162        }
163    }
164    pub fn with_spawn_depth(depth: u32) -> Self {
165        Self {
166            spawn_depth: depth,
167            ..Self::new()
168        }
169    }
170    pub fn append(&mut self, kind: SessionEntryKind) -> EntryId {
171        self.append_stamped(kind, Utc::now())
172    }
173    /// Append an entry carrying the time the underlying event happened, not
174    /// the time the save ran. `created_at` is the journal's timeline; stamping
175    /// it at append is what keeps a rebuilt journal honest — a save must never
176    /// rewrite an entry's time to the moment it was written.
177    pub fn append_stamped(&mut self, kind: SessionEntryKind, created_at: DateTime<Utc>) -> EntryId {
178        let mut entry = SessionEntry::new(kind, self.leaf_id.clone(), self.spawn_depth);
179        entry.created_at = created_at;
180        let id = entry.id.clone();
181        self.entries.push(entry);
182        self.leaf_id = Some(id.clone());
183        id
184    }
185    pub fn append_message(&mut self, message: Message) -> EntryId {
186        self.append(SessionEntryKind::Message { message })
187    }
188    pub fn append_compaction(
189        &mut self,
190        summary: String,
191        tokens_before: Option<u64>,
192        tokens_after: Option<u64>,
193        model: Option<String>,
194    ) -> EntryId {
195        self.append(SessionEntryKind::Compaction {
196            summary,
197            tokens_before,
198            tokens_after,
199            model,
200        })
201    }
202    pub fn append_branch_summary(
203        &mut self,
204        branch_id: String,
205        summary: String,
206        parent_branch_id: Option<String>,
207    ) -> EntryId {
208        self.append(SessionEntryKind::BranchSummary {
209            branch_id,
210            summary,
211            parent_branch_id,
212        })
213    }
214    pub fn branch_to(&mut self, entry_id: &str) -> Result<(), String> {
215        if self.entries.iter().any(|e| e.id == entry_id) {
216            self.leaf_id = Some(entry_id.to_string());
217            Ok(())
218        } else {
219            Err(format!("entry {entry_id} not found"))
220        }
221    }
222    pub fn fork_from(&self, from_entry_id: Option<&str>) -> Result<Self, String> {
223        let leaf = if let Some(id) = from_entry_id {
224            if !self.entries.iter().any(|e| e.id == id) {
225                return Err(format!("fork source {id} not found"));
226            }
227            Some(id.to_string())
228        } else {
229            self.leaf_id.clone()
230        };
231        Ok(Self {
232            entries: self.entries.clone(),
233            leaf_id: leaf,
234            schema_version: self.schema_version,
235            spawn_depth: self.spawn_depth.saturating_add(1),
236        })
237    }
238    pub fn index(&self) -> HashMap<&str, &SessionEntry> {
239        self.entries.iter().map(|e| (e.id.as_str(), e)).collect()
240    }
241    pub fn contains(&self, entry_id: &str) -> bool {
242        self.entries.iter().any(|e| e.id == entry_id)
243    }
244    pub fn leaf(&self) -> Option<&SessionEntry> {
245        self.leaf_id
246            .as_deref()
247            .and_then(|id| self.entries.iter().find(|e| e.id == id))
248    }
249    pub fn root_to_leaf(&self) -> Vec<&SessionEntry> {
250        let index: HashMap<&str, &SessionEntry> =
251            self.entries.iter().map(|e| (e.id.as_str(), e)).collect();
252        let mut path = Vec::new();
253        let mut cur = self.leaf_id.as_deref();
254        let mut seen = HashSet::new();
255        while let Some(id) = cur {
256            if !seen.insert(id) {
257                break;
258            }
259            if let Some(entry) = index.get(id) {
260                path.push(*entry);
261                cur = entry.parent_id.as_deref();
262            } else {
263                break;
264            }
265        }
266        path.reverse();
267        path
268    }
269    pub fn active_messages(&self, include_system: bool) -> Vec<Message> {
270        self.root_to_leaf()
271            .into_iter()
272            .filter_map(|e| {
273                if !include_system && !e.kind.is_contextual() {
274                    return None;
275                }
276                e.kind.as_message()
277            })
278            .collect()
279    }
280    pub fn leaves(&self) -> Vec<&SessionEntry> {
281        let parents: HashSet<&str> = self
282            .entries
283            .iter()
284            .filter_map(|e| e.parent_id.as_deref())
285            .collect();
286        self.entries
287            .iter()
288            .filter(|e| !parents.contains(e.id.as_str()))
289            .collect()
290    }
291    pub fn is_empty(&self) -> bool {
292        self.entries.is_empty()
293    }
294    pub fn len(&self) -> usize {
295        self.entries.len()
296    }
297    pub fn validate(&self) -> Result<(), String> {
298        let ids: HashSet<&str> = self.entries.iter().map(|e| e.id.as_str()).collect();
299        for entry in &self.entries {
300            if let Some(parent) = entry.parent_id.as_deref()
301                && !ids.contains(parent)
302            {
303                return Err(format!("entry {} missing parent {}", entry.id, parent));
304            }
305        }
306        if let Some(leaf) = self.leaf_id.as_deref()
307            && !ids.contains(leaf)
308        {
309            return Err(format!("leaf {leaf} not found"));
310        }
311        Ok(())
312    }
313    pub fn from_messages(messages: Vec<Message>, spawn_depth: u32) -> Self {
314        let mut j = Self::with_spawn_depth(spawn_depth);
315        for msg in messages {
316            j.append(SessionEntryKind::Message { message: msg });
317        }
318        j
319    }
320    /// Build the journal honoring a per-message append stamp. `stamps[i]` is
321    /// the time `messages[i]` entered the conversation; a missing stamp falls
322    /// back to now, so a drifted caller degrades to save-time ordering rather
323    /// than dropping the message.
324    pub fn from_messages_stamped(
325        messages: Vec<Message>,
326        stamps: &[DateTime<Utc>],
327        spawn_depth: u32,
328    ) -> Self {
329        let mut j = Self::with_spawn_depth(spawn_depth);
330        for (index, msg) in messages.into_iter().enumerate() {
331            let created_at = stamps.get(index).copied().unwrap_or_else(Utc::now);
332            j.append_stamped(SessionEntryKind::Message { message: msg }, created_at);
333        }
334        j
335    }
336    pub fn to_messages(&self) -> Vec<Message> {
337        self.active_messages(true)
338    }
339
340    /// Keep the shared prefix and its original stamps. A provisional user
341    /// entry can gain its Engine stamp until another branch shares it.
342    pub fn rebranch_active_messages(&mut self, messages: &[Message]) -> Rebranch {
343        self.rebranch_active_messages_stamped(messages, &[])
344    }
345
346    /// Preserve existing entry identity and timestamps; only append the changed
347    /// suffix, keeping the previous branch reachable.
348    pub fn rebranch_active_messages_stamped(
349        &mut self,
350        messages: &[Message],
351        stamps: &[DateTime<Utc>],
352    ) -> Rebranch {
353        let path = self.root_to_leaf();
354        let previous_active = path.len();
355        let mut shared_prefix: usize = 0;
356        let mut kept_recorded_metadata = false;
357        let mut refresh = HashMap::new();
358        let mut protected_prefix = None;
359        for (index, (entry, incoming)) in path.iter().zip(messages).enumerate() {
360            if !entry.kind.projects_to(incoming) {
361                break;
362            }
363            if let SessionEntryKind::Message { message: stored } = &*entry.kind
364                && stored != incoming
365            {
366                if stored.content.len() > incoming.content.len() {
367                    kept_recorded_metadata = true;
368                } else {
369                    let shared = protected_prefix.get_or_insert_with(|| {
370                        if path.len() == self.entries.len() {
371                            return 0;
372                        }
373                        let mut parents = HashSet::new();
374                        let fork_points: HashSet<_> = self
375                            .entries
376                            .iter()
377                            .filter_map(|entry| entry.parent_id.as_deref())
378                            .filter(|parent| !parents.insert(*parent))
379                            .collect();
380                        path.iter()
381                            .rposition(|entry| fork_points.contains(entry.id.as_str()))
382                            .map_or(0, |index| index + 1)
383                    });
384                    if index < *shared {
385                        break;
386                    }
387                    refresh.insert(entry.id.clone(), incoming);
388                }
389            }
390            shared_prefix += 1;
391        }
392        self.leaf_id = shared_prefix
393            .checked_sub(1)
394            .map(|index| path[index].id.clone());
395        if !refresh.is_empty() {
396            for entry in &mut self.entries {
397                if let Some(&incoming) = refresh.get(&entry.id) {
398                    entry.kind = Arc::new(SessionEntryKind::Message {
399                        message: incoming.clone(),
400                    });
401                }
402            }
403        }
404        for (index, message) in messages.iter().enumerate().skip(shared_prefix) {
405            self.append_stamped(
406                SessionEntryKind::Message {
407                    message: message.clone(),
408                },
409                stamps.get(index).copied().unwrap_or_else(Utc::now),
410            );
411        }
412        Rebranch {
413            previous_active,
414            shared_prefix,
415            kept_recorded_metadata,
416        }
417    }
418
419    /// Ids a bounded save may move out of this journal, in journal order.
420    ///
421    /// Empty until more than `dead_threshold` entries sit off the active
422    /// branch — superseded versions left behind by compaction, undo and
423    /// edits (#6842). Past it, the plan keeps the root→leaf path, then whole
424    /// off-branch chains (an entry with every ancestor) newest first, with
425    /// `Compaction`/`BranchSummary` chains ahead of plain leaves, while the
426    /// kept off-branch total stays within `dead_budget`. A kept entry never
427    /// loses its parent, so the remainder always passes [`Self::validate`].
428    ///
429    /// Pure: callers archive the planned entries durably before removing
430    /// them with [`Self::remove_entries`]. Known limit: the active branch
431    /// itself is never pruned, so a session that never compacts stays as
432    /// long as its conversation.
433    pub fn prune_plan(&self, dead_threshold: usize, dead_budget: usize) -> Vec<EntryId> {
434        let active = self.root_to_leaf();
435        if self.entries.len().saturating_sub(active.len()) <= dead_threshold {
436            return Vec::new();
437        }
438        let index: HashMap<&str, usize> = self
439            .entries
440            .iter()
441            .enumerate()
442            .map(|(i, e)| (e.id.as_str(), i))
443            .collect();
444        let mut keep = vec![false; self.entries.len()];
445        for entry in &active {
446            if let Some(&i) = index.get(entry.id.as_str()) {
447                keep[i] = true;
448            }
449        }
450        let parents: HashSet<&str> = self
451            .entries
452            .iter()
453            .filter_map(|e| e.parent_id.as_deref())
454            .collect();
455        let summary = |e: &SessionEntry| {
456            matches!(
457                *e.kind,
458                SessionEntryKind::Compaction { .. } | SessionEntryKind::BranchSummary { .. }
459            )
460        };
461        // Newest first: journal order is append order.
462        let candidates = self
463            .entries
464            .iter()
465            .enumerate()
466            .rev()
467            .filter(|(_, e)| summary(e))
468            .chain(
469                self.entries
470                    .iter()
471                    .enumerate()
472                    .rev()
473                    .filter(|(_, e)| !parents.contains(e.id.as_str())),
474            );
475        let mut used = 0usize;
476        for (start, _) in candidates {
477            if keep[start] {
478                continue;
479            }
480            let mut chain = Vec::new();
481            let mut seen = HashSet::new();
482            let mut cursor = Some(start);
483            let mut closed = true;
484            while let Some(i) = cursor {
485                if keep[i] {
486                    break;
487                }
488                if !seen.insert(i) || used + chain.len() >= dead_budget {
489                    closed = false;
490                    break;
491                }
492                chain.push(i);
493                cursor = match self.entries[i].parent_id.as_deref() {
494                    None => None,
495                    Some(parent) => match index.get(parent) {
496                        Some(&p) => Some(p),
497                        None => {
498                            closed = false;
499                            None
500                        }
501                    },
502                };
503            }
504            if closed {
505                used += chain.len();
506                for i in chain {
507                    keep[i] = true;
508                }
509            }
510        }
511        self.entries
512            .iter()
513            .zip(keep)
514            .filter(|(_, kept)| !kept)
515            .map(|(e, _)| e.id.clone())
516            .collect()
517    }
518
519    /// Remove `ids` atomically: either every listed entry leaves and the
520    /// remainder still validates, or the journal is left exactly as it was
521    /// and the validation error is returned. Returns how many were removed.
522    pub fn remove_entries(&mut self, ids: &HashSet<EntryId>) -> Result<usize, String> {
523        if ids.is_empty() {
524            return Ok(0);
525        }
526        let original = std::mem::take(&mut self.entries);
527        let mut removed = Vec::new();
528        for (position, entry) in original.into_iter().enumerate() {
529            if ids.contains(&entry.id) {
530                removed.push((position, entry));
531            } else {
532                self.entries.push(entry);
533            }
534        }
535        if let Err(error) = self.validate() {
536            // Ascending positions put every entry back where it was.
537            for (position, entry) in removed {
538                self.entries.insert(position, entry);
539            }
540            return Err(error);
541        }
542        Ok(removed.len())
543    }
544}
545#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
546pub struct SessionImportContainer {
547    pub format_version: u32,
548    pub source: String,
549    pub metadata: Option<serde_json::Value>,
550    pub entries: Vec<SessionEntry>,
551    #[serde(default, skip_serializing_if = "Option::is_none")]
552    pub leaf_id: Option<EntryId>,
553    pub exported_at: DateTime<Utc>,
554    #[serde(default)]
555    pub spawn_depth: u32,
556}
557impl SessionImportContainer {
558    pub fn new(
559        source: String,
560        journal: &SessionJournal,
561        metadata: Option<serde_json::Value>,
562    ) -> Self {
563        Self {
564            format_version: CURRENT_JOURNAL_SCHEMA_VERSION,
565            source,
566            metadata,
567            entries: journal.entries.clone(),
568            leaf_id: journal.leaf_id.clone(),
569            exported_at: Utc::now(),
570            spawn_depth: journal.spawn_depth,
571        }
572    }
573    pub fn into_journal(self) -> Result<SessionJournal, String> {
574        let j = SessionJournal {
575            entries: self.entries,
576            leaf_id: self.leaf_id,
577            schema_version: self.format_version,
578            spawn_depth: self.spawn_depth,
579        };
580        j.validate()?;
581        Ok(j)
582    }
583    pub fn to_json(&self) -> Result<String, serde_json::Error> {
584        serde_json::to_string_pretty(self)
585    }
586    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
587        serde_json::from_str(json)
588    }
589}
590/// The first `chars` characters of `text`. Ids come from imported journals as
591/// well as from this process, so a byte slice could split a character.
592fn char_prefix(text: &str, chars: usize) -> &str {
593    let end = text
594        .char_indices()
595        .nth(chars)
596        .map_or(text.len(), |(index, _)| index);
597    &text[..end]
598}
599
600/// Render the journal as a tree, one line per reachable entry.
601///
602/// Indentation grows only where the history forks: an entry with a single
603/// child is followed by that child at the same depth, so a long linear
604/// session stays flat instead of drawing entry N at depth N. Each fork on the
605/// way down still adds one guide column. Several roots (a rewind to before
606/// the first message starts a new one) are drawn as siblings. The walk uses
607/// an explicit stack, so no session length can exhaust the thread's stack.
608pub fn render_tree(journal: &SessionJournal) -> String {
609    if journal.entries.is_empty() {
610        return "(empty session — no entries yet)".to_string();
611    }
612    let mut out = String::new();
613    let mut children: HashMap<Option<&str>, Vec<usize>> = HashMap::new();
614    for (index, entry) in journal.entries.iter().enumerate() {
615        children
616            .entry(entry.parent_id.as_deref())
617            .or_default()
618            .push(index);
619    }
620    let active_ids: HashSet<&str> = journal
621        .root_to_leaf()
622        .iter()
623        .map(|e| e.id.as_str())
624        .collect();
625    let leaf = journal.leaf_id.as_deref();
626    // (entry index, guide columns inherited from forks above, connector)
627    let mut stack: Vec<(usize, String, &'static str)> = Vec::new();
628    push_tree_children(&mut stack, children.get(&None), "");
629    // Duplicate ids in an imported journal would otherwise revisit a subtree
630    // forever; each entry is drawn at most once.
631    let mut drawn = vec![false; journal.entries.len()];
632    while let Some((index, guide, connector)) = stack.pop() {
633        if std::mem::replace(&mut drawn[index], true) {
634            continue;
635        }
636        let entry = &journal.entries[index];
637        let marker = if Some(entry.id.as_str()) == leaf {
638            "*"
639        } else if active_ids.contains(entry.id.as_str()) {
640            "●"
641        } else {
642            "○"
643        };
644        out.push_str(&format!(
645            "{guide}{connector}{marker} {} [{}] {}\n",
646            entry.short_id(),
647            entry.id,
648            tree_label(&entry.kind)
649        ));
650        let child_guide = match connector {
651            "├─ " => format!("{guide}│  "),
652            "└─ " => format!("{guide}   "),
653            _ => guide,
654        };
655        push_tree_children(
656            &mut stack,
657            children.get(&Some(entry.id.as_str())),
658            &child_guide,
659        );
660    }
661    if let Some(leaf_id) = leaf {
662        out.push_str(&format!(
663            "\nleaf: {leaf_id} (active, {} entries)\n",
664            journal.entries.len()
665        ));
666    }
667    // Entries whose parents form a loop hang off no root and cannot be drawn;
668    // say so instead of letting the total above silently disagree.
669    let unreachable = drawn.iter().filter(|drawn| !**drawn).count();
670    if unreachable > 0 {
671        out.push_str(&format!(
672            "{unreachable} entries not reachable from a root\n"
673        ));
674    }
675    out
676}
677
678/// Queue `nodes` so they pop in journal order. A lone child (or a lone root)
679/// continues its line of history without a connector; siblings get one each.
680fn push_tree_children(
681    stack: &mut Vec<(usize, String, &'static str)>,
682    nodes: Option<&Vec<usize>>,
683    guide: &str,
684) {
685    let Some(nodes) = nodes else {
686        return;
687    };
688    let forked = nodes.len() > 1;
689    for (position, &index) in nodes.iter().enumerate().rev() {
690        let connector = if !forked {
691            ""
692        } else if position + 1 == nodes.len() {
693            "└─ "
694        } else {
695            "├─ "
696        };
697        stack.push((index, guide.to_string(), connector));
698    }
699}
700
701fn tree_label(kind: &SessionEntryKind) -> String {
702    match kind {
703        SessionEntryKind::Message { message } => {
704            let role = &message.role;
705            let meta_index = codewhale_models::turn_classify::turn_metadata_text(message)
706                .filter(|_| message.role == Role::User)
707                .map(|(index, _)| index);
708            let snippet: String = message
709                .content
710                .iter()
711                .enumerate()
712                .filter_map(|(index, b)| match b {
713                    ContentBlock::Text { text, .. } if Some(index) != meta_index => {
714                        Some(text.as_str())
715                    }
716                    _ => None,
717                })
718                .collect::<Vec<_>>()
719                .join(" ");
720            format!("{role}: {}", label_snippet(&snippet))
721        }
722        SessionEntryKind::User { text } => format!("user: {}", label_snippet(text)),
723        SessionEntryKind::Assistant { text } => format!("assistant: {}", label_snippet(text)),
724        SessionEntryKind::Compaction { summary, .. } => {
725            format!("compaction: {}", label_snippet(summary))
726        }
727        SessionEntryKind::BranchSummary {
728            branch_id, summary, ..
729        } => format!(
730            "branch:{} {}",
731            char_prefix(branch_id, 8),
732            label_snippet(summary)
733        ),
734        SessionEntryKind::System { content } => format!("system: {}", label_snippet(content)),
735    }
736}
737
738/// The first 60 characters of an entry, kept on its one tree line: a line
739/// break, tab or other control character reads as a space, and bidirectional
740/// format characters, which would reorder the rest of the row, are dropped.
741fn label_snippet(text: &str) -> String {
742    text.chars()
743        .filter(|ch| {
744            !matches!(
745                ch,
746                '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}'
747            )
748        })
749        .map(|ch| {
750            if ch.is_control() || matches!(ch, '\u{2028}' | '\u{2029}') {
751                ' '
752            } else {
753                ch
754            }
755        })
756        .take(60)
757        .collect()
758}
759#[cfg(test)]
760mod tests {
761    use super::*;
762    use codewhale_models::{ContentBlock, Message, Role};
763    fn msg(role: &str, text: &str) -> Message {
764        Message {
765            role: Role::from(role),
766            content: vec![ContentBlock::Text {
767                text: text.to_string(),
768                cache_control: None,
769            }],
770        }
771    }
772    #[test]
773    fn append_creates_child_of_leaf() {
774        let mut j = SessionJournal::new();
775        let a = j.append(SessionEntryKind::User {
776            text: "hello".into(),
777        });
778        let b = j.append(SessionEntryKind::Assistant {
779            text: "world".into(),
780        });
781        assert_eq!(j.leaf_id.as_deref(), Some(b.as_str()));
782        let be = j.entries.iter().find(|e| e.id == b).unwrap();
783        assert_eq!(be.parent_id.as_deref(), Some(a.as_str()));
784    }
785    #[test]
786    fn branch_moves_leaf_only() {
787        let mut j = SessionJournal::new();
788        let a = j.append(SessionEntryKind::User { text: "a".into() });
789        let b = j.append(SessionEntryKind::User { text: "b".into() });
790        let _c = j.append(SessionEntryKind::User { text: "c".into() });
791        j.branch_to(&a).unwrap();
792        let d = j.append(SessionEntryKind::User { text: "d".into() });
793        assert_eq!(j.entries.len(), 4);
794        assert_eq!(j.leaf_id.as_deref(), Some(d.as_str()));
795        let path: Vec<String> = j.root_to_leaf().iter().map(|e| e.id.clone()).collect();
796        assert_eq!(path, vec![a.clone(), d.clone()]);
797        assert!(j.entries.iter().any(|e| e.id == b));
798    }
799    #[test]
800    fn from_messages_migrates() {
801        let msgs = vec![msg("user", "hi"), msg("assistant", "hello")];
802        let j = SessionJournal::from_messages(msgs, 0);
803        assert_eq!(j.entries.len(), 2);
804        assert!(j.validate().is_ok());
805        assert_eq!(j.root_to_leaf().len(), 2);
806    }
807    #[test]
808    fn repaired_messages_form_an_append_only_sibling_branch() {
809        let original = vec![
810            msg("user", "shared"),
811            msg("assistant", "broken"),
812            msg("user", "old tail"),
813        ];
814        let mut journal = SessionJournal::from_messages(original, 0);
815        let old_leaf = journal.leaf_id.clone().expect("old leaf");
816        let repaired = vec![
817            msg("user", "shared"),
818            msg("assistant", "repaired"),
819            msg("user", "new tail"),
820        ];
821
822        journal.rebranch_active_messages(&repaired);
823
824        assert_eq!(journal.to_messages(), repaired);
825        assert!(journal.contains(&old_leaf), "old evidence must remain");
826        assert_eq!(
827            journal.entries.len(),
828            5,
829            "one shared entry plus two branches"
830        );
831    }
832    #[test]
833    fn stamped_rebranch_keeps_prefix_identity_and_suffix_stamps() {
834        let stamp = |secs: i64| DateTime::from_timestamp(secs, 0).expect("stamp");
835        let mut j = SessionJournal::new();
836        j.append_stamped(
837            SessionEntryKind::Message {
838                message: msg("user", "a"),
839            },
840            stamp(100),
841        );
842        j.append_stamped(
843            SessionEntryKind::Message {
844                message: msg("assistant", "b"),
845            },
846            stamp(200),
847        );
848        let a_id = j.entries[0].id.clone();
849        j.rebranch_active_messages_stamped(
850            &[msg("user", "a"), msg("assistant", "b2")],
851            &[stamp(100), stamp(300)],
852        );
853        assert_eq!(j.entries.len(), 3);
854        assert_eq!(j.entries[0].id, a_id, "shared prefix keeps its id");
855        assert_eq!(j.entries[0].created_at, stamp(100));
856        let path = j.root_to_leaf();
857        assert_eq!(path.len(), 2);
858        assert_eq!(
859            path[1].created_at,
860            stamp(300),
861            "suffix keeps the live stamp"
862        );
863        assert!(
864            j.entries
865                .iter()
866                .any(|e| e.kind.as_message().as_ref() == Some(&msg("assistant", "b"))),
867            "replaced suffix survives as a sibling"
868        );
869    }
870    #[test]
871    fn compaction_fits() {
872        let mut j = SessionJournal::new();
873        let id = j.append_compaction("summary".into(), Some(1000), Some(100), None);
874        assert!(j.contains(&id));
875        assert!(matches!(
876            *j.leaf().unwrap().kind,
877            SessionEntryKind::Compaction { .. }
878        ));
879    }
880    #[test]
881    fn branch_summary_fits() {
882        let mut j = SessionJournal::new();
883        let a = j.append(SessionEntryKind::User {
884            text: "root".into(),
885        });
886        let b = j.append_branch_summary(a.clone(), "branch summary".into(), None);
887        assert!(j.contains(&b));
888    }
889    #[test]
890    fn spawn_depth_fork() {
891        let mut j = SessionJournal::with_spawn_depth(1);
892        let forked = j.fork_from(None).unwrap();
893        assert_eq!(forked.spawn_depth, 2);
894        let a = j.append(SessionEntryKind::User {
895            text: "root".into(),
896        });
897        let fork2 = j.fork_from(Some(&a)).unwrap();
898        assert_eq!(fork2.spawn_depth, 2);
899    }
900    #[test]
901    fn foreign_roundtrip() {
902        let mut j = SessionJournal::new();
903        j.append(SessionEntryKind::User {
904            text: "hello".into(),
905        });
906        let c = SessionImportContainer::new("codewhale".into(), &j, None);
907        let json = c.to_json().unwrap();
908        let back = SessionImportContainer::from_json(&json).unwrap();
909        let j2 = back.into_journal().unwrap();
910        assert_eq!(j.entries.len(), j2.entries.len());
911    }
912    #[test]
913    fn render_marks_active() {
914        let mut j = SessionJournal::new();
915        j.append(SessionEntryKind::User {
916            text: "root".into(),
917        });
918        let tree = render_tree(&j);
919        assert!(tree.contains('*'));
920    }
921    #[test]
922    fn render_keeps_a_linear_session_flat() {
923        let mut j = SessionJournal::new();
924        for i in 0..200 {
925            j.append(SessionEntryKind::User {
926                text: format!("turn {i}"),
927            });
928        }
929        let tree = render_tree(&j);
930        let entry_lines: Vec<&str> = tree.lines().take(200).collect();
931        for (i, line) in entry_lines.iter().enumerate() {
932            assert!(
933                line.ends_with(&format!("user: turn {i}")),
934                "entry {i} out of order: {line:?}"
935            );
936            assert!(
937                line.starts_with(['●', '*']),
938                "a linear history must not indent: {line:?}"
939            );
940        }
941    }
942
943    #[test]
944    fn render_indents_only_at_forks() {
945        let mut j = SessionJournal::new();
946        let a = j.append(SessionEntryKind::User { text: "a".into() });
947        j.append(SessionEntryKind::User { text: "b".into() });
948        j.append(SessionEntryKind::User { text: "c".into() });
949        j.branch_to(&a).unwrap();
950        j.append(SessionEntryKind::User { text: "d".into() });
951        j.append(SessionEntryKind::User { text: "e".into() });
952        let tree = render_tree(&j);
953        let shape: Vec<String> = tree
954            .lines()
955            .take(5)
956            .map(|line| {
957                let (head, label) = line.split_once(" [").unwrap();
958                let prefix: String = head.chars().take_while(|c| !c.is_alphanumeric()).collect();
959                format!("{prefix}{}", label.rsplit(": ").next().unwrap())
960            })
961            .collect();
962        assert_eq!(
963            shape,
964            ["● a", "├─ ○ b", "│  ○ c", "└─ ● d", "   * e"],
965            "{tree}"
966        );
967    }
968
969    #[test]
970    fn render_draws_several_roots_as_siblings() {
971        let mut j = SessionJournal::new();
972        j.append(SessionEntryKind::User { text: "r1".into() });
973        j.append(SessionEntryKind::User { text: "c1".into() });
974        // A rewind to before the first message appends a second root.
975        j.leaf_id = None;
976        j.append(SessionEntryKind::User { text: "r2".into() });
977        j.append(SessionEntryKind::User { text: "d1".into() });
978        let tree = render_tree(&j);
979        let shape: Vec<String> = tree
980            .lines()
981            .take(4)
982            .map(|line| {
983                let (head, label) = line.split_once(" [").unwrap();
984                let prefix: String = head.chars().take_while(|c| !c.is_alphanumeric()).collect();
985                format!("{prefix}{}", label.rsplit(": ").next().unwrap())
986            })
987            .collect();
988        assert_eq!(
989            shape,
990            ["├─ ○ r1", "│  ○ c1", "└─ ● r2", "   * d1"],
991            "{tree}"
992        );
993    }
994
995    #[test]
996    fn render_keeps_each_entry_on_one_line_whatever_its_text_or_id() {
997        let mut j = SessionJournal::new();
998        j.append(SessionEntryKind::User {
999            text: "first line\nsecond line\r\n\tthird\u{202E}".into(),
1000        });
1001        // Imported ids need not be ASCII; a byte slice would split a char.
1002        j.entries[0].id = "会話会話会話会話".into();
1003        j.leaf_id = Some(j.entries[0].id.clone());
1004        j.append(SessionEntryKind::BranchSummary {
1005            branch_id: "枝枝枝枝枝枝枝枝枝".into(),
1006            summary: "multi\nline".into(),
1007            parent_branch_id: None,
1008        });
1009        let tree = render_tree(&j);
1010        let lines: Vec<&str> = tree.lines().collect();
1011        assert_eq!(
1012            lines[0], "● 会話会話会話会話 [会話会話会話会話] user: first line second line   third",
1013            "{tree}"
1014        );
1015        assert!(
1016            lines[1].ends_with("branch:枝枝枝枝枝枝枝枝 multi line"),
1017            "{tree}"
1018        );
1019        assert_eq!(lines.len(), 2 + 2, "two entries plus the footer: {tree}");
1020    }
1021
1022    #[test]
1023    fn render_draws_a_repeated_id_once_and_counts_unreachable_entries() {
1024        let mut j = SessionJournal::new();
1025        let a = j.append(SessionEntryKind::User { text: "a".into() });
1026        j.append(SessionEntryKind::User { text: "b".into() });
1027        // An imported journal repeating `a`'s id under `a` itself: following
1028        // children by id would revisit `a`'s subtree forever.
1029        let mut repeat = j.entries[0].clone();
1030        repeat.parent_id = Some(a.clone());
1031        j.entries.push(repeat);
1032        // Two entries that are each other's parent hang off no root.
1033        let mut x = SessionEntry::new(SessionEntryKind::User { text: "x".into() }, None, 0);
1034        let mut y = SessionEntry::new(SessionEntryKind::User { text: "y".into() }, None, 0);
1035        x.parent_id = Some(y.id.clone());
1036        y.parent_id = Some(x.id.clone());
1037        j.entries.extend([x, y]);
1038
1039        let (tx, rx) = std::sync::mpsc::channel();
1040        std::thread::spawn(move || tx.send(render_tree(&j)).ok());
1041        let tree = rx
1042            .recv_timeout(std::time::Duration::from_secs(2))
1043            .expect("a repeated id must not make the walk revisit a subtree forever");
1044        let entry_lines = tree.lines().take_while(|line| !line.is_empty()).count();
1045        assert_eq!(
1046            entry_lines, 3,
1047            "each journal entry is drawn at most once: {tree}"
1048        );
1049        assert!(
1050            tree.ends_with("2 entries not reachable from a root\n"),
1051            "{tree}"
1052        );
1053    }
1054
1055    #[test]
1056    fn render_handles_a_long_session_on_a_small_stack() {
1057        let mut j = SessionJournal::new();
1058        for i in 0..20_000 {
1059            j.append(SessionEntryKind::User {
1060                text: format!("turn {i}"),
1061            });
1062        }
1063        // One recursion frame per entry overflows this long before the end.
1064        let lines = std::thread::Builder::new()
1065            .stack_size(256 * 1024)
1066            .spawn(move || render_tree(&j).lines().count())
1067            .unwrap()
1068            .join()
1069            .expect("rendering must not exhaust the stack");
1070        assert_eq!(lines, 20_000 + 2);
1071    }
1072
1073    #[test]
1074    fn active_messages_root_to_leaf() {
1075        let mut j = SessionJournal::new();
1076        j.append(SessionEntryKind::User { text: "a".into() });
1077        j.append(SessionEntryKind::User { text: "b".into() });
1078        let msgs = j.active_messages(false);
1079        assert_eq!(msgs.len(), 2);
1080        j.branch_to(&j.entries[0].id.clone()).unwrap();
1081        j.append(SessionEntryKind::User { text: "c".into() });
1082        let msgs2 = j.active_messages(false);
1083        assert_eq!(msgs2.len(), 2);
1084    }
1085
1086    #[test]
1087    fn projects_to_matches_as_message_equality_for_every_kind() {
1088        let kinds = [
1089            SessionEntryKind::Message {
1090                message: msg("assistant", "hi"),
1091            },
1092            SessionEntryKind::User {
1093                text: "hi".to_string(),
1094            },
1095            SessionEntryKind::Assistant {
1096                text: "hi".to_string(),
1097            },
1098            SessionEntryKind::System {
1099                content: "hi".to_string(),
1100            },
1101        ];
1102        let probes = [
1103            msg("assistant", "hi"),
1104            msg("user", "hi"),
1105            msg("system", "hi"),
1106            msg("assistant", "other"),
1107        ];
1108        for kind in &kinds {
1109            for probe in &probes {
1110                assert_eq!(
1111                    kind.projects_to(probe),
1112                    kind.as_message().as_ref() == Some(probe),
1113                    "{kind:?} vs {probe:?}"
1114                );
1115            }
1116        }
1117    }
1118
1119    /// A compaction-heavy session: each round rebranches the whole tail, so
1120    /// superseded copies pile up off the active branch (#6842).
1121    fn compacted_journal(rounds: usize, tail: usize) -> SessionJournal {
1122        let mut j = SessionJournal::new();
1123        for round in 0..rounds {
1124            let messages: Vec<Message> = (0..tail)
1125                .map(|i| msg("user", &format!("round {round} message {i}")))
1126                .collect();
1127            j.rebranch_active_messages(&messages);
1128        }
1129        j
1130    }
1131
1132    #[test]
1133    fn prune_plan_is_empty_under_the_threshold() {
1134        let j = compacted_journal(4, 10);
1135        assert_eq!(j.len(), 40);
1136        assert!(j.prune_plan(30, 5).is_empty());
1137    }
1138
1139    #[test]
1140    fn prune_plan_keeps_active_branch_and_whole_recent_chains() {
1141        let mut j = compacted_journal(50, 10);
1142        let active_before = j.active_messages(true);
1143        let leaf = j.leaf_id.clone();
1144        let plan = j.prune_plan(100, 25);
1145        // 490 dead entries; 2 whole 10-entry chains fit a 25 budget.
1146        assert_eq!(plan.len(), 490 - 20);
1147        let ids: HashSet<EntryId> = plan.into_iter().collect();
1148        assert_eq!(j.remove_entries(&ids).unwrap(), 470);
1149        assert_eq!(j.len(), 30);
1150        j.validate().unwrap();
1151        assert_eq!(j.leaf_id, leaf);
1152        assert_eq!(j.active_messages(true), active_before);
1153        // The newest superseded round survives, not an arbitrary one.
1154        let kept: Vec<String> = j
1155            .entries
1156            .iter()
1157            .filter_map(|e| e.kind.as_message())
1158            .map(|m| match &m.content[0] {
1159                ContentBlock::Text { text, .. } => text.clone(),
1160                _ => String::new(),
1161            })
1162            .collect();
1163        assert!(kept.iter().any(|t| t.starts_with("round 48 ")), "{kept:?}");
1164        assert!(!kept.iter().any(|t| t.starts_with("round 0 ")), "{kept:?}");
1165    }
1166
1167    #[test]
1168    fn prune_plan_prefers_summary_chains() {
1169        let mut j = compacted_journal(30, 4);
1170        let leaf = j.leaf_id.clone().unwrap();
1171        // An old compaction hanging off the very first entry.
1172        let first = j.entries[0].id.clone();
1173        j.branch_to(&first).unwrap();
1174        let summary = j.append_compaction("old summary".into(), None, None, None);
1175        j.branch_to(&leaf).unwrap();
1176        let plan = j.prune_plan(10, 2);
1177        assert!(!plan.contains(&summary));
1178        assert!(!plan.contains(&first));
1179    }
1180
1181    #[test]
1182    fn remove_entries_refuses_to_orphan_and_leaves_journal_untouched() {
1183        let mut j = compacted_journal(3, 3);
1184        let before = j.clone();
1185        let active: HashSet<EntryId> = j
1186            .root_to_leaf()
1187            .iter()
1188            .map(|e| e.id.clone())
1189            .take(1)
1190            .collect();
1191        assert!(j.remove_entries(&active).is_err());
1192        assert_eq!(j, before);
1193    }
1194
1195    #[test]
1196    fn rebranch_refreshes_a_metadata_only_prefix_in_place() {
1197        let mut j = SessionJournal::new();
1198        j.append(SessionEntryKind::Message {
1199            message: msg("user", "hi"),
1200        });
1201        j.append(SessionEntryKind::Message {
1202            message: msg("assistant", "there"),
1203        });
1204        let before = j.entries.len();
1205
1206        let mut stamped = msg("user", "hi");
1207        stamped.content.push(ContentBlock::Text {
1208            text: "<turn_meta>\nCurrent local date: 2026-10-31\nCurrent workspace: /fixture\n</turn_meta>".into(),
1209            cache_control: None,
1210        });
1211        let live = vec![stamped, msg("assistant", "there")];
1212
1213        let report = j.rebranch_active_messages(&live);
1214        assert_eq!(report.shared_prefix, 2);
1215        assert_eq!(j.entries.len(), before);
1216        assert_eq!(j.to_messages(), live);
1217
1218        let again = j.rebranch_active_messages(&live);
1219        assert_eq!(again.shared_prefix, 2);
1220        assert_eq!(j.entries.len(), before);
1221    }
1222
1223    #[test]
1224    fn rebranch_forks_when_the_content_actually_changed() {
1225        let mut j = SessionJournal::new();
1226        j.append(SessionEntryKind::Message {
1227            message: msg("user", "hi"),
1228        });
1229        j.append(SessionEntryKind::Message {
1230            message: msg("assistant", "there"),
1231        });
1232        let before = j.entries.len();
1233
1234        let report =
1235            j.rebranch_active_messages(&[msg("user", "changed"), msg("assistant", "there")]);
1236        assert_eq!(report.shared_prefix, 0);
1237        assert_eq!(j.entries.len(), before + 2);
1238    }
1239
1240    #[test]
1241    fn a_metadata_shaped_payload_never_matches_a_shorter_turn() {
1242        let stored = Message {
1243            role: Role::from("user"),
1244            content: vec![
1245                ContentBlock::Text {
1246                    text: "<turn_meta>{}</turn_meta>REAL CONTENT</turn_meta>".into(),
1247                    cache_control: None,
1248                },
1249                ContentBlock::Text {
1250                    text: "tail".into(),
1251                    cache_control: None,
1252                },
1253            ],
1254        };
1255        let mut j = SessionJournal::new();
1256        j.append(SessionEntryKind::Message {
1257            message: stored.clone(),
1258        });
1259        let before = j.entries.len();
1260
1261        let report = j.rebranch_active_messages(&[msg("user", "tail")]);
1262        assert_eq!(report.shared_prefix, 0);
1263        assert_eq!(j.entries.len(), before + 1);
1264        assert!(
1265            j.entries
1266                .iter()
1267                .any(|entry| matches!(&*entry.kind, SessionEntryKind::Message { message } if message == &stored)),
1268            "the stored payload stays in the journal as its own branch"
1269        );
1270    }
1271}