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