Skip to main content

oxi_store/
session.rs

1//! Session management for the coding agent.
2//!
3//! Manages conversation sessions as append-only trees stored in JSONL files.
4//! Each session entry has an id and parent_id forming a tree structure.
5
6use anyhow::{Context, Result};
7use chrono::{DateTime, Utc};
8use parking_lot::RwLock;
9use serde::{Deserialize, Serialize};
10use std::collections::{HashMap, HashSet};
11use std::fs::{self, File};
12use std::io::{BufRead, BufReader, Write};
13use std::path::{Path, PathBuf};
14use uuid::Uuid;
15
16// ============================================================================
17// Atomic Write Helper
18// ============================================================================
19
20/// Atomically write content to a file by first writing to a temp file,
21/// then renaming it. This avoids corruption if the process crashes mid-write.
22fn atomic_write(path: &Path, content: &str) -> Result<(), std::io::Error> {
23    let tmp_path = path.with_extension(format!("tmp.{}", std::process::id()));
24    std::fs::write(&tmp_path, content)?;
25    std::fs::rename(&tmp_path, path)?;
26    Ok(())
27}
28
29/// Type alias for entry IDs (for backward compatibility)
30pub type EntryId = Uuid;
31
32/// Current session version for migrations
33pub const CURRENT_SESSION_VERSION: i32 = 3;
34
35// ============================================================================
36// Backward Compatibility Layer
37// ============================================================================
38
39/// Session metadata stored separately from entries (backward compatibility)
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct SessionMeta {
42    /// Unique session identifier.
43    pub id: Uuid,
44    /// ID of the parent session this was branched from.
45    pub parent_id: Option<Uuid>,
46    /// ID of the root session in the branch chain.
47    pub root_id: Option<Uuid>,
48    /// Entry ID where this session was branched.
49    pub branch_point: Option<Uuid>,
50    /// Creation timestamp in milliseconds since epoch.
51    pub created_at: i64,
52    /// Last update timestamp in milliseconds since epoch.
53    pub updated_at: i64,
54    /// Optional human-readable session name.
55    pub name: Option<String>,
56}
57
58impl SessionMeta {
59    /// New.
60    pub fn new(id: Uuid) -> Self {
61        let now = Utc::now().timestamp_millis();
62        Self {
63            id,
64            parent_id: None,
65            root_id: None,
66            branch_point: None,
67            created_at: now,
68            updated_at: now,
69            name: None,
70        }
71    }
72
73    /// Branched from.
74    pub fn branched_from(parent_id: Uuid, root_id: Option<Uuid>, branch_point: Uuid) -> Self {
75        let now = Utc::now().timestamp_millis();
76        Self {
77            id: Uuid::new_v4(),
78            parent_id: Some(parent_id),
79            root_id: root_id.or(Some(parent_id)),
80            branch_point: Some(branch_point),
81            created_at: now,
82            updated_at: now,
83            name: None,
84        }
85    }
86}
87
88/// Information about where a session branched from
89#[derive(Debug, Clone)]
90pub struct BranchInfo {
91    /// The session id.
92    pub session_id: Uuid,
93    /// The parent session id.
94    pub parent_session_id: Option<Uuid>,
95    /// The root session id.
96    pub root_session_id: Option<Uuid>,
97    /// The branch point entry id.
98    pub branch_point_entry_id: Option<Uuid>,
99    /// The parent session name.
100    pub parent_session_name: Option<String>,
101}
102
103// ============================================================================
104// Session Header
105// ============================================================================
106
107/// Session header stored as the first line in JSONL files
108#[derive(Debug, Clone, Serialize, Deserialize)]
109pub struct SessionHeader {
110    /// The entry type.
111    #[serde(rename = "type")]
112    pub entry_type: String,
113    /// The version.
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub version: Option<i32>,
116    /// The id.
117    pub id: String,
118    /// The timestamp.
119    pub timestamp: String,
120    /// The cwd.
121    pub cwd: String,
122    /// The parent session.
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub parent_session: Option<String>,
125}
126
127impl SessionHeader {
128    /// New.
129    pub fn new(id: String, cwd: String, parent_session: Option<String>) -> Self {
130        Self {
131            entry_type: "session".to_string(),
132            version: Some(CURRENT_SESSION_VERSION),
133            id,
134            timestamp: Utc::now().to_rfc3339(),
135            cwd,
136            parent_session,
137        }
138    }
139}
140
141// ============================================================================
142// Content Types
143// ============================================================================
144
145/// Content can be string or array of content blocks
146#[derive(Debug, Clone, Serialize, Deserialize)]
147#[serde(untagged)]
148pub enum ContentValue {
149    /// String.
150    String(String),
151    /// Blocks.
152    Blocks(Vec<ContentBlock>),
153}
154
155impl ContentValue {
156    /// As str.
157    pub fn as_str(&self) -> &str {
158        match self {
159            ContentValue::String(s) => s,
160            ContentValue::Blocks(blocks) => {
161                // For blocks, return first text block or empty
162                for block in blocks {
163                    if let ContentBlock::Text { text } = block {
164                        return text;
165                    }
166                }
167                ""
168            }
169        }
170    }
171}
172
173impl From<String> for ContentValue {
174    fn from(s: String) -> Self {
175        ContentValue::String(s)
176    }
177}
178
179impl From<&str> for ContentValue {
180    fn from(s: &str) -> Self {
181        ContentValue::String(s.to_string())
182    }
183}
184
185/// Content block for text or image content
186#[derive(Debug, Clone, Serialize, Deserialize)]
187#[serde(tag = "type")]
188pub enum ContentBlock {
189    /// Plain text content block.
190    #[serde(rename = "text")]
191    Text {
192        /// The text content.
193        text: String,
194    },
195    /// Image content block.
196    #[serde(rename = "image")]
197    Image {
198        /// Base64-encoded image data.
199        data: String,
200        /// MIME type of the image.
201        media_type: Option<String>,
202    },
203}
204
205// ============================================================================
206// Agent Message Types
207// ============================================================================
208
209/// Agent message roles
210#[derive(Debug, Clone, Serialize, Deserialize)]
211#[serde(tag = "role")]
212pub enum AgentMessage {
213    /// User.
214    #[serde(rename = "user")]
215    User {
216        /// The content.
217        #[serde(flatten)]
218        content: ContentValue,
219    },
220    /// Assistant.
221    #[serde(rename = "assistant")]
222    Assistant {
223        /// The content.
224        content: Vec<AssistantContentBlock>,
225        /// The provider.
226        #[serde(skip_serializing_if = "Option::is_none")]
227        provider: Option<String>,
228        /// The model id.
229        #[serde(skip_serializing_if = "Option::is_none")]
230        model_id: Option<String>,
231        /// The usage.
232        #[serde(skip_serializing_if = "Option::is_none")]
233        usage: Option<Usage>,
234        /// The stop reason.
235        #[serde(rename = "stopReason", skip_serializing_if = "Option::is_none")]
236        stop_reason: Option<String>,
237    },
238    /// Tool Result.
239    #[serde(rename = "toolResult")]
240    ToolResult {
241        /// The content.
242        content: ContentValue,
243        /// The tool call id.
244        #[serde(rename = "toolCallId")]
245        tool_call_id: String,
246    },
247    /// System.
248    #[serde(rename = "system")]
249    System {
250        /// The content.
251        #[serde(flatten)]
252        content: ContentValue,
253    },
254    /// Bash Execution.
255    #[serde(rename = "bashExecution")]
256    BashExecution {
257        /// The command.
258        command: String,
259        /// The output.
260        output: String,
261        /// The exit code.
262        #[serde(rename = "exitCode")]
263        exit_code: Option<i32>,
264        /// The cancelled.
265        cancelled: bool,
266        /// The truncated.
267        truncated: bool,
268        /// The full output path.
269        #[serde(rename = "fullOutputPath", skip_serializing_if = "Option::is_none")]
270        full_output_path: Option<String>,
271        /// The exclude from context.
272        #[serde(rename = "excludeFromContext", skip_serializing_if = "Option::is_none")]
273        exclude_from_context: Option<bool>,
274        /// The timestamp.
275        timestamp: i64,
276    },
277    /// Custom.
278    #[serde(rename = "custom")]
279    Custom {
280        /// The custom type.
281        #[serde(rename = "customType")]
282        custom_type: String,
283        /// The content.
284        content: ContentValue,
285        /// The display.
286        display: bool,
287        /// The details.
288        #[serde(skip_serializing_if = "Option::is_none")]
289        details: Option<serde_json::Value>,
290        /// The timestamp.
291        timestamp: i64,
292    },
293    /// Branch Summary.
294    #[serde(rename = "branchSummary")]
295    BranchSummary {
296        /// The summary.
297        summary: String,
298        /// The from id.
299        #[serde(rename = "fromId")]
300        from_id: String,
301        /// The timestamp.
302        timestamp: i64,
303    },
304    /// Compaction Summary.
305    #[serde(rename = "compactionSummary")]
306    CompactionSummary {
307        /// The summary.
308        summary: String,
309        /// The tokens before.
310        #[serde(rename = "tokensBefore")]
311        tokens_before: i64,
312        /// The timestamp.
313        timestamp: i64,
314    },
315}
316
317impl AgentMessage {
318    /// Get the content of the message as a string
319    pub fn content(&self) -> String {
320        match self {
321            AgentMessage::User { content } => content.as_str().to_string(),
322            AgentMessage::Assistant { content, .. } => {
323                let estimated_len = content
324                    .iter()
325                    .map(|b| match b {
326                        AssistantContentBlock::Text { text: t } => t.len(),
327                        _ => 0,
328                    })
329                    .sum::<usize>();
330                let mut text = String::with_capacity(estimated_len.max(256));
331                for block in content {
332                    if let AssistantContentBlock::Text { text: t } = block {
333                        text.push_str(t)
334                    }
335                }
336                text
337            }
338            AgentMessage::ToolResult { content, .. } => content.as_str().to_string(),
339            AgentMessage::System { content } => content.as_str().to_string(),
340            AgentMessage::BashExecution { output, .. } => output.clone(),
341            AgentMessage::Custom { content, .. } => content.as_str().to_string(),
342            AgentMessage::BranchSummary { summary, .. } => summary.clone(),
343            AgentMessage::CompactionSummary { summary, .. } => summary.clone(),
344        }
345    }
346
347    /// Check if this is a user message
348    pub fn is_user(&self) -> bool {
349        matches!(self, AgentMessage::User { .. })
350    }
351
352    /// Check if this is an assistant message
353    pub fn is_assistant(&self) -> bool {
354        matches!(self, AgentMessage::Assistant { .. })
355    }
356}
357
358/// Content block for assistant messages
359#[derive(Debug, Clone, Serialize, Deserialize)]
360#[serde(tag = "type")]
361pub enum AssistantContentBlock {
362    /// Plain text content block.
363    #[serde(rename = "text")]
364    Text {
365        /// The text content.
366        text: String,
367    },
368    /// Extended thinking content block.
369    #[serde(rename = "thinking")]
370    Thinking {
371        /// The thinking content.
372        thinking: String,
373    },
374    /// Tool Call.
375    #[serde(rename = "toolCall")]
376    ToolCall {
377        /// The id.
378        id: String,
379        /// The name.
380        name: String,
381        /// The arguments.
382        arguments: serde_json::Value,
383    },
384    /// Tool Plan.
385    #[serde(rename = "toolPlan")]
386    ToolPlan {
387        /// The content.
388        content: String,
389        /// The tool call id.
390        #[serde(rename = "toolCallId")]
391        tool_call_id: String,
392    },
393    /// Image result content block.
394    #[serde(rename = "image")]
395    ImageResult {
396        /// Base64-encoded image data.
397        data: String,
398        /// MIME type of the image.
399        media_type: String,
400    },
401    /// Refusal content block.
402    #[serde(rename = "refusal")]
403    Refusal {
404        /// The refusal reason.
405        content: String,
406    },
407}
408
409/// Usage statistics from an assistant message
410#[derive(Debug, Clone, Serialize, Deserialize)]
411pub struct Usage {
412    /// The input.
413    #[serde(rename = "inputTokens", skip_serializing_if = "Option::is_none")]
414    pub input: Option<i64>,
415    /// The output.
416    #[serde(rename = "outputTokens", skip_serializing_if = "Option::is_none")]
417    pub output: Option<i64>,
418    /// The cache read.
419    #[serde(rename = "cacheReadTokens", skip_serializing_if = "Option::is_none")]
420    pub cache_read: Option<i64>,
421    /// The cache write.
422    #[serde(rename = "cacheWriteTokens", skip_serializing_if = "Option::is_none")]
423    pub cache_write: Option<i64>,
424    /// The total tokens.
425    #[serde(rename = "totalTokens", skip_serializing_if = "Option::is_none")]
426    pub total_tokens: Option<i64>,
427}
428
429// ============================================================================
430// Session Entry Types
431// ============================================================================
432
433/// Base fields for all session entries (internal use)
434#[derive(Debug, Clone, Serialize, Deserialize)]
435pub struct SessionEntryBase {
436    /// The entry type.
437    #[serde(rename = "type")]
438    pub entry_type: String,
439    /// The id.
440    pub id: String,
441    /// The parent id.
442    #[serde(rename = "parentId")]
443    pub parent_id: Option<String>,
444    /// The timestamp.
445    pub timestamp: String,
446}
447
448/// Message entry with AgentMessage content
449#[derive(Debug, Clone, Serialize, Deserialize)]
450pub struct SessionMessageEntry {
451    /// The base.
452    #[serde(flatten)]
453    pub base: SessionEntryBase,
454    /// The message.
455    pub message: AgentMessage,
456}
457
458/// Thinking level change entry
459#[derive(Debug, Clone, Serialize, Deserialize)]
460pub struct ThinkingLevelChangeEntry {
461    /// The base.
462    #[serde(flatten)]
463    pub base: SessionEntryBase,
464    /// The thinking level.
465    #[serde(rename = "thinkingLevel")]
466    pub thinking_level: String,
467}
468
469/// Model change entry
470#[derive(Debug, Clone, Serialize, Deserialize)]
471pub struct ModelChangeEntry {
472    /// The base.
473    #[serde(flatten)]
474    pub base: SessionEntryBase,
475    /// The provider.
476    pub provider: String,
477    /// The model id.
478    #[serde(rename = "modelId")]
479    pub model_id: String,
480}
481
482/// Compaction entry for context window management
483#[derive(Debug, Clone, Serialize, Deserialize)]
484pub struct CompactionEntry {
485    /// The base.
486    #[serde(flatten)]
487    pub base: SessionEntryBase,
488    /// The summary.
489    pub summary: String,
490    /// The first kept entry id.
491    #[serde(rename = "firstKeptEntryId")]
492    pub first_kept_entry_id: String,
493    /// The tokens before.
494    #[serde(rename = "tokensBefore")]
495    pub tokens_before: i64,
496    /// The details.
497    #[serde(skip_serializing_if = "Option::is_none")]
498    pub details: Option<serde_json::Value>,
499    /// The from hook.
500    #[serde(rename = "fromHook", skip_serializing_if = "Option::is_none")]
501    pub from_hook: Option<bool>,
502}
503
504/// Branch summary entry for abandoned branches
505#[derive(Debug, Clone, Serialize, Deserialize)]
506pub struct BranchSummaryEntry {
507    /// The base.
508    #[serde(flatten)]
509    pub base: SessionEntryBase,
510    /// The from id.
511    #[serde(rename = "fromId")]
512    pub from_id: String,
513    /// The summary.
514    pub summary: String,
515    /// The details.
516    #[serde(skip_serializing_if = "Option::is_none")]
517    pub details: Option<serde_json::Value>,
518    /// The from hook.
519    #[serde(rename = "fromHook", skip_serializing_if = "Option::is_none")]
520    pub from_hook: Option<bool>,
521}
522
523/// Custom entry for extensions to store extension-specific data
524#[derive(Debug, Clone, Serialize, Deserialize)]
525pub struct CustomEntry {
526    /// The base.
527    #[serde(flatten)]
528    pub base: SessionEntryBase,
529    /// The custom type.
530    #[serde(rename = "customType")]
531    pub custom_type: String,
532    /// The data.
533    #[serde(skip_serializing_if = "Option::is_none")]
534    pub data: Option<serde_json::Value>,
535}
536
537/// Label entry for user-defined bookmarks/markers on entries
538#[derive(Debug, Clone, Serialize, Deserialize)]
539pub struct LabelEntry {
540    /// The base.
541    #[serde(flatten)]
542    pub base: SessionEntryBase,
543    /// The target id.
544    #[serde(rename = "targetId")]
545    pub target_id: String,
546    /// The label.
547    pub label: Option<String>,
548}
549
550/// Session metadata entry (e.g., user-defined display name)
551#[derive(Debug, Clone, Serialize, Deserialize)]
552pub struct SessionInfoEntry {
553    /// The base.
554    #[serde(flatten)]
555    pub base: SessionEntryBase,
556    /// The name.
557    pub name: Option<String>,
558}
559
560/// Custom message entry for extensions to inject messages into LLM context
561#[derive(Debug, Clone, Serialize, Deserialize)]
562pub struct CustomMessageEntry {
563    /// The base.
564    #[serde(flatten)]
565    pub base: SessionEntryBase,
566    /// The custom type.
567    #[serde(rename = "customType")]
568    pub custom_type: String,
569    /// The content.
570    pub content: ContentValue,
571    /// The details.
572    #[serde(skip_serializing_if = "Option::is_none")]
573    pub details: Option<serde_json::Value>,
574    /// The display.
575    pub display: bool,
576}
577
578/// All possible session entries (internal enum)
579#[derive(Debug, Clone, Serialize, Deserialize)]
580#[serde(untagged)]
581pub enum SessionEntryEnum {
582    /// Message.
583    Message(SessionMessageEntry),
584    /// Thinking Level Change.
585    ThinkingLevelChange(ThinkingLevelChangeEntry),
586    /// Model Change.
587    ModelChange(ModelChangeEntry),
588    /// Compaction.
589    Compaction(CompactionEntry),
590    /// Branch Summary.
591    BranchSummary(BranchSummaryEntry),
592    /// Custom.
593    Custom(CustomEntry),
594    /// Label.
595    Label(LabelEntry),
596    /// Session Info.
597    SessionInfo(SessionInfoEntry),
598    /// Custom Message.
599    CustomMessage(CustomMessageEntry),
600}
601
602/// Session entry - a simple struct for backward compatibility
603/// This wraps the internal enum representation
604#[derive(Debug, Clone, Serialize, Deserialize)]
605pub struct SessionEntry {
606    /// The id.
607    pub id: String,
608    /// The parent id.
609    pub parent_id: Option<String>,
610    /// The timestamp.
611    pub timestamp: i64,
612    /// The message.
613    pub message: AgentMessage,
614}
615
616impl SessionEntry {
617    /// Create a new session entry
618    pub fn new(message: AgentMessage) -> Self {
619        Self {
620            id: Uuid::new_v4().to_string(),
621            parent_id: None,
622            timestamp: Utc::now().timestamp_millis(),
623            message,
624        }
625    }
626
627    /// Create a simple message entry with a role string and content
628    pub fn simple_message(role: &str, content: &str) -> Self {
629        use crate::session::ContentValue;
630        let message = match role {
631            "user" => AgentMessage::User {
632                content: ContentValue::String(content.to_string()),
633            },
634            "assistant" => AgentMessage::Assistant {
635                content: vec![AssistantContentBlock::Text {
636                    text: content.to_string(),
637                }],
638                provider: None,
639                model_id: None,
640                usage: None,
641                stop_reason: None,
642            },
643            "system" => AgentMessage::System {
644                content: ContentValue::String(content.to_string()),
645            },
646            _ => AgentMessage::System {
647                content: ContentValue::String(content.to_string()),
648            },
649        };
650        Self::new(message)
651    }
652
653    /// Create a branched entry with a parent reference
654    pub fn branched(message: AgentMessage, parent_id: &str) -> Self {
655        Self {
656            id: Uuid::new_v4().to_string(),
657            parent_id: Some(parent_id.to_string()),
658            timestamp: Utc::now().timestamp_millis(),
659            message,
660        }
661    }
662
663    /// Get the message content as a string
664    pub fn content(&self) -> String {
665        self.message.content()
666    }
667}
668
669/// Raw file entry (includes header and internal enum)
670#[derive(Debug, Clone, Serialize, Deserialize)]
671#[serde(untagged)]
672pub enum FileEntry {
673    /// Header.
674    Header(SessionHeader),
675    /// Entry.
676    Entry(SessionEntryEnum),
677}
678
679// ============================================================================
680// Session Context
681// ============================================================================
682
683/// Context built from session entries for the LLM
684#[derive(Debug, Clone)]
685pub struct SessionContext {
686    /// The messages.
687    pub messages: Vec<AgentMessage>,
688    /// The thinking level.
689    pub thinking_level: String,
690    /// The model.
691    pub model: Option<ModelInfo>,
692}
693
694/// Model information
695#[derive(Debug, Clone)]
696pub struct ModelInfo {
697    /// The provider.
698    pub provider: String,
699    /// The model id.
700    pub model_id: String,
701}
702
703// ============================================================================
704// Session Info
705// ============================================================================
706
707/// Session metadata for listing
708#[derive(Debug, Clone)]
709pub struct SessionInfo {
710    /// The path.
711    pub path: String,
712    /// The id.
713    pub id: String,
714    /// The cwd.
715    pub cwd: String,
716    /// The name.
717    pub name: Option<String>,
718    /// The parent session path.
719    pub parent_session_path: Option<String>,
720    /// The created.
721    pub created: DateTime<Utc>,
722    /// The modified.
723    pub modified: DateTime<Utc>,
724    /// The message count.
725    pub message_count: i64,
726    /// The first message.
727    pub first_message: String,
728    /// The all messages text.
729    pub all_messages_text: String,
730}
731
732// ============================================================================
733// Session Tree Node
734// ============================================================================
735
736/// Tree node for get_tree()
737#[derive(Debug, Clone)]
738pub struct SessionTreeNode {
739    /// The entry.
740    pub entry: SessionEntry,
741    /// The children.
742    pub children: Vec<SessionTreeNode>,
743    /// The label.
744    pub label: Option<String>,
745    /// The label timestamp.
746    pub label_timestamp: Option<String>,
747}
748
749// ============================================================================
750// ID Generation
751// ============================================================================
752
753fn generate_id(by_id: &HashSet<String>) -> String {
754    for _ in 0..100 {
755        let id = Uuid::new_v4().to_string()[..8].to_string();
756        if !by_id.contains(&id) {
757            return id;
758        }
759    }
760    // Fallback to full UUID if somehow we have collisions
761    Uuid::new_v4().to_string()
762}
763
764// ============================================================================
765// Version Migration
766// ============================================================================
767
768/// Migrate v1 to v2: add id/parent_id tree structure
769fn migrate_v1_to_v2(entries: &mut [FileEntry]) {
770    let mut ids = HashSet::new();
771    let mut prev_id: Option<String> = None;
772
773    for entry in entries.iter_mut() {
774        match entry {
775            FileEntry::Header(header) => {
776                header.version = Some(2);
777            }
778            FileEntry::Entry(entry) => {
779                let id = match entry {
780                    SessionEntryEnum::Message(e) => {
781                        e.base.id = generate_id(&ids);
782                        e.base.parent_id = prev_id.clone();
783                        e.base.entry_type = "message".to_string();
784                        prev_id = Some(e.base.id.clone());
785                        e.base.id.clone()
786                    }
787                    SessionEntryEnum::ThinkingLevelChange(e) => {
788                        e.base.id = generate_id(&ids);
789                        e.base.parent_id = prev_id.clone();
790                        e.base.entry_type = "thinking_level_change".to_string();
791                        prev_id = Some(e.base.id.clone());
792                        e.base.id.clone()
793                    }
794                    SessionEntryEnum::ModelChange(e) => {
795                        e.base.id = generate_id(&ids);
796                        e.base.parent_id = prev_id.clone();
797                        e.base.entry_type = "model_change".to_string();
798                        prev_id = Some(e.base.id.clone());
799                        e.base.id.clone()
800                    }
801                    SessionEntryEnum::Compaction(e) => {
802                        e.base.id = generate_id(&ids);
803                        e.base.parent_id = prev_id.clone();
804                        e.base.entry_type = "compaction".to_string();
805                        prev_id = Some(e.base.id.clone());
806                        e.base.id.clone()
807                    }
808                    SessionEntryEnum::BranchSummary(e) => {
809                        e.base.id = generate_id(&ids);
810                        e.base.parent_id = prev_id.clone();
811                        e.base.entry_type = "branch_summary".to_string();
812                        prev_id = Some(e.base.id.clone());
813                        e.base.id.clone()
814                    }
815                    SessionEntryEnum::Custom(e) => {
816                        e.base.id = generate_id(&ids);
817                        e.base.parent_id = prev_id.clone();
818                        e.base.entry_type = "custom".to_string();
819                        prev_id = Some(e.base.id.clone());
820                        e.base.id.clone()
821                    }
822                    SessionEntryEnum::Label(e) => {
823                        e.base.id = generate_id(&ids);
824                        e.base.parent_id = prev_id.clone();
825                        e.base.entry_type = "label".to_string();
826                        prev_id = Some(e.base.id.clone());
827                        e.base.id.clone()
828                    }
829                    SessionEntryEnum::SessionInfo(e) => {
830                        e.base.id = generate_id(&ids);
831                        e.base.parent_id = prev_id.clone();
832                        e.base.entry_type = "session_info".to_string();
833                        prev_id = Some(e.base.id.clone());
834                        e.base.id.clone()
835                    }
836                    SessionEntryEnum::CustomMessage(e) => {
837                        e.base.id = generate_id(&ids);
838                        e.base.parent_id = prev_id.clone();
839                        e.base.entry_type = "custom_message".to_string();
840                        prev_id = Some(e.base.id.clone());
841                        e.base.id.clone()
842                    }
843                };
844                ids.insert(id);
845            }
846        }
847    }
848}
849
850/// Migrate v2 to v3: rename hookMessage role to custom
851fn migrate_v2_to_v3(entries: &mut [FileEntry]) {
852    for entry in entries.iter_mut() {
853        match entry {
854            FileEntry::Header(header) => {
855                header.version = Some(3);
856            }
857            FileEntry::Entry(_) => {
858                // v2 to v3 migration handled elsewhere
859            }
860        }
861    }
862}
863
864/// Run all necessary migrations to bring entries to current version
865fn migrate_to_current_version(entries: &mut [FileEntry]) -> bool {
866    let header = entries.iter().find_map(|e| match e {
867        FileEntry::Header(h) => Some(h),
868        _ => None,
869    });
870    let version = header.and_then(|h| h.version).unwrap_or(1);
871
872    if version >= CURRENT_SESSION_VERSION {
873        return false;
874    }
875
876    if version < 2 {
877        migrate_v1_to_v2(entries);
878    }
879    if version < 3 {
880        migrate_v2_to_v3(entries);
881    }
882
883    true
884}
885
886// ============================================================================
887// Session Manager
888// ============================================================================
889
890/// Manages conversation sessions as append-only trees stored in JSONL files.
891///
892/// SessionManager handles session persistence, branching, and tree traversal.
893/// Each session is stored as a JSONL file where each line is a session entry.
894/// Entries form a tree structure allowing for session branching and history.
895pub struct SessionManager {
896    session_id: String,
897    session_file: Option<String>,
898    session_dir: String,
899    cwd: String,
900    persist: bool,
901    flushed: bool,
902    /// Tracks how many agent messages have been persisted so far,
903    /// so that `persist_session()` only appends new messages.
904    persisted_count: RwLock<usize>,
905    file_entries: RwLock<Vec<FileEntry>>,
906    by_id: RwLock<HashMap<String, SessionEntry>>,
907    labels_by_id: RwLock<HashMap<String, String>>,
908    label_timestamps_by_id: RwLock<HashMap<String, String>>,
909    leaf_id: RwLock<Option<String>>,
910}
911
912// Manual Clone implementation — only copies internal pointers, not file handles
913impl Clone for SessionManager {
914    fn clone(&self) -> Self {
915        Self {
916            session_id: self.session_id.clone(),
917            session_file: self.session_file.clone(),
918            session_dir: self.session_dir.clone(),
919            cwd: self.cwd.clone(),
920            persist: self.persist,
921            flushed: self.flushed,
922            persisted_count: RwLock::new(*self.persisted_count.read()),
923            file_entries: RwLock::new(self.file_entries.read().clone()),
924            by_id: RwLock::new(self.by_id.read().clone()),
925            labels_by_id: RwLock::new(self.labels_by_id.read().clone()),
926            label_timestamps_by_id: RwLock::new(self.label_timestamps_by_id.read().clone()),
927            leaf_id: RwLock::new(self.leaf_id.read().clone()),
928        }
929    }
930}
931
932impl SessionManager {
933    /// Create a new session and persist it to disk.
934    pub fn create(cwd: &str, session_dir: Option<&str>) -> Self {
935        let dir = session_dir
936            .map(|s| s.to_string())
937            .unwrap_or_else(|| get_default_session_dir(cwd));
938
939        let mut manager = Self::new_internal(cwd, &dir, None, true);
940        manager.persist = true;
941        manager
942    }
943
944    /// Open an existing session from a file path.
945    pub fn open(path: &str, session_dir: Option<&str>, cwd_override: Option<&str>) -> Self {
946        let entries = load_entries_from_file(path);
947        let header = entries.iter().find_map(|e| match e {
948            FileEntry::Header(h) => Some(h),
949            _ => None,
950        });
951        let cwd = cwd_override
952            .map(|s| s.to_string())
953            .or_else(|| header.as_ref().map(|h| h.cwd.clone()))
954            .unwrap_or_else(|| {
955                std::env::current_dir()
956                    .unwrap_or_else(|_| PathBuf::from("."))
957                    .to_string_lossy()
958                    .to_string()
959            });
960        let dir = session_dir.map(|s| s.to_string()).unwrap_or_else(|| {
961            Path::new(path)
962                .parent()
963                .map(|p| p.to_string_lossy().to_string())
964                .unwrap_or_else(|| ".".to_string())
965        });
966
967        let mut manager = Self::new_internal(&cwd, &dir, Some(path), true);
968        manager.persist = true;
969        manager
970    }
971
972    /// Continue the most recent session, or create a new one if none exists.
973    pub fn continue_recent(cwd: &str, session_dir: Option<&str>) -> Self {
974        let dir = session_dir
975            .map(|s| s.to_string())
976            .unwrap_or_else(|| get_default_session_dir(cwd));
977
978        if let Some(most_recent) = find_most_recent_session(&dir) {
979            return Self::open(&most_recent, None, None);
980        }
981        Self::create(cwd, None)
982    }
983
984    /// Create an in-memory session without file persistence.
985    pub fn in_memory(cwd: &str) -> Self {
986        let cwd = cwd.to_string();
987        Self::new_internal(&cwd, "", None, false)
988    }
989
990    fn new_internal(
991        cwd: &str,
992        session_dir: &str,
993        session_file: Option<&str>,
994        persist: bool,
995    ) -> Self {
996        let cwd = cwd.to_string();
997        let session_dir = session_dir.to_string();
998
999        if persist && !session_dir.is_empty() && !Path::new(&session_dir).exists() {
1000            let _ = fs::create_dir_all(&session_dir);
1001        }
1002
1003        let mut manager = Self {
1004            session_id: Uuid::new_v4().to_string(),
1005            session_file: session_file.map(|s| s.to_string()),
1006            session_dir,
1007            cwd,
1008            persist,
1009            flushed: false,
1010            persisted_count: RwLock::new(0),
1011            file_entries: RwLock::new(Vec::new()),
1012            by_id: RwLock::new(HashMap::new()),
1013            labels_by_id: RwLock::new(HashMap::new()),
1014            label_timestamps_by_id: RwLock::new(HashMap::new()),
1015            leaf_id: RwLock::new(None),
1016        };
1017
1018        if let Some(file) = session_file {
1019            manager.set_session_file(file);
1020        } else {
1021            manager.new_session(None);
1022        }
1023
1024        manager
1025    }
1026
1027    /// Switch to a different session file
1028    pub fn set_session_file(&mut self, session_file: &str) {
1029        let path = Path::new(session_file)
1030            .canonicalize()
1031            .unwrap_or_else(|_| PathBuf::from(session_file));
1032        let path_str = path.to_string_lossy().to_string();
1033        self.session_file = Some(path_str.clone());
1034
1035        if path.exists() {
1036            let mut entries = load_entries_from_file(&path_str);
1037
1038            // If file was empty or corrupted (no valid header), truncate and start fresh
1039            if entries.is_empty() {
1040                let explicit_path = self.session_file.take();
1041                self.new_session(None);
1042                self.session_file = explicit_path;
1043                self._rewrite_file();
1044                self.flushed = true;
1045                return;
1046            }
1047
1048            let header = entries.iter().find_map(|e| match e {
1049                FileEntry::Header(h) => Some(h),
1050                _ => None,
1051            });
1052            self.session_id = header
1053                .map(|h| h.id.clone())
1054                .unwrap_or_else(|| Uuid::new_v4().to_string());
1055
1056            if migrate_to_current_version(&mut entries) {
1057                self._rewrite_file();
1058            }
1059
1060            *self.file_entries.write() = entries;
1061            self._build_index();
1062            self.flushed = true;
1063        } else {
1064            let explicit_path = self.session_file.take();
1065            self.new_session(None);
1066            self.session_file = explicit_path;
1067        }
1068    }
1069
1070    /// Create a new session with optional ID and parent
1071    pub fn new_session(&mut self, options: Option<NewSessionOptions>) {
1072        self.session_id = options
1073            .as_ref()
1074            .and_then(|o| o.id.clone())
1075            .unwrap_or_else(|| Uuid::new_v4().to_string());
1076        let timestamp = Utc::now().to_rfc3339();
1077        let header = SessionHeader::new(
1078            self.session_id.clone(),
1079            self.cwd.clone(),
1080            options.and_then(|o| o.parent_session),
1081        );
1082
1083        self.file_entries = RwLock::new(vec![FileEntry::Header(header)]);
1084        self.by_id.write().clear();
1085        self.labels_by_id.write().clear();
1086        self.label_timestamps_by_id.write().clear();
1087        *self.leaf_id.write() = None;
1088        *self.persisted_count.write() = 0;
1089        self.flushed = false;
1090
1091        if self.persist {
1092            let file_timestamp = timestamp.replace([':', '.', 'T', '-', ':', '+'], "-");
1093            let short_id = &self.session_id[..8];
1094            self.session_file = Some(format!(
1095                "{}/{}_{}.jsonl",
1096                self.session_dir, file_timestamp, short_id
1097            ));
1098        }
1099    }
1100
1101    fn _build_index(&mut self) {
1102        let mut by_id = self.by_id.write();
1103        let mut labels = self.labels_by_id.write();
1104        let mut label_timestamps = self.label_timestamps_by_id.write();
1105        let mut leaf_id = self.leaf_id.write();
1106
1107        by_id.clear();
1108        labels.clear();
1109        label_timestamps.clear();
1110        *leaf_id = None;
1111
1112        for entry in self.file_entries.read().iter() {
1113            if let FileEntry::Entry(e) = entry {
1114                // Convert internal enum to simple SessionEntry struct
1115                if let Some(session_entry) = convert_to_session_entry(e) {
1116                    by_id.insert(session_entry.id.clone(), session_entry.clone());
1117                    *leaf_id = Some(session_entry.id.clone());
1118                }
1119
1120                // Handle labels
1121                if let SessionEntryEnum::Label(l) = e {
1122                    if let Some(ref label) = l.label {
1123                        labels.insert(l.target_id.clone(), label.clone());
1124                        label_timestamps.insert(l.target_id.clone(), l.base.timestamp.clone());
1125                    } else {
1126                        labels.remove(&l.target_id);
1127                        label_timestamps.remove(&l.target_id);
1128                    }
1129                }
1130            }
1131        }
1132    }
1133
1134    fn _rewrite_file(&self) {
1135        if !self.persist || self.session_file.is_none() {
1136            return;
1137        }
1138
1139        let file = match self.session_file.as_ref() {
1140            Some(f) => f,
1141            None => return,
1142        };
1143
1144        let content: String = self
1145            .file_entries
1146            .read()
1147            .iter()
1148            .map(|e| serde_json::to_string(e).unwrap_or_default())
1149            .collect::<Vec<_>>()
1150            .join("\n")
1151            + "\n";
1152
1153        if let Err(e) = atomic_write(Path::new(file), &content) {
1154            tracing::warn!("Failed to rewrite session file {}: {}", file, e);
1155        }
1156    }
1157
1158    /// Check if session is persisted to disk
1159    pub fn is_persisted(&self) -> bool {
1160        self.persist
1161    }
1162
1163    /// Get the number of agent messages that have already been persisted.
1164    pub fn persisted_count(&self) -> usize {
1165        *self.persisted_count.read()
1166    }
1167
1168    /// Set the number of agent messages that have been persisted.
1169    pub fn set_persisted_count(&self, count: usize) {
1170        *self.persisted_count.write() = count;
1171    }
1172
1173    /// Get working directory
1174    pub fn get_cwd(&self) -> String {
1175        self.cwd.clone()
1176    }
1177
1178    /// Get session directory
1179    pub fn get_session_dir(&self) -> String {
1180        self.session_dir.clone()
1181    }
1182
1183    /// Get session ID
1184    pub fn get_session_id(&self) -> String {
1185        self.session_id.clone()
1186    }
1187
1188    /// Get session file path
1189    pub fn get_session_file(&self) -> Option<String> {
1190        self.session_file.clone()
1191    }
1192
1193    fn _persist(&mut self, entry: &SessionEntry) {
1194        if !self.persist {
1195            return;
1196        }
1197        let Some(file) = &self.session_file else {
1198            return;
1199        };
1200
1201        let has_assistant = self.file_entries.read().iter().any(|e| {
1202            matches!(
1203                e,
1204                FileEntry::Entry(SessionEntryEnum::Message(m)) if m.message.is_assistant()
1205            )
1206        });
1207
1208        if !has_assistant {
1209            // Mark as not flushed so when assistant arrives, all entries get written
1210            self.flushed = false;
1211            return;
1212        }
1213
1214        let mut handle = match fs::OpenOptions::new().create(true).append(true).open(file) {
1215            Ok(h) => h,
1216            Err(e) => {
1217                tracing::warn!("Failed to open session file for append {}: {}", file, e);
1218                return;
1219            }
1220        };
1221
1222        if !self.flushed {
1223            for e in self.file_entries.read().iter() {
1224                if let Ok(line) = serde_json::to_string(e) {
1225                    let _ = writeln!(&mut handle, "{}", line);
1226                }
1227            }
1228            self.flushed = true;
1229        } else {
1230            // Convert SessionEntry back to FileEntry for writing
1231            let file_entry = convert_from_session_entry(entry);
1232            if let Ok(line) = serde_json::to_string(&file_entry) {
1233                let _ = writeln!(&mut handle, "{}", line);
1234            }
1235        }
1236    }
1237
1238    // LOCK ORDERING CONVENTION (must be followed to prevent deadlock):
1239    // 1. file_entries  2. by_id  3. labels_by_id  4. label_timestamps_by_id  5. leaf_id
1240    // Always acquire locks in this order. Never acquire an earlier lock after a later one.
1241    fn _append_entry(&mut self, entry: SessionEntry) {
1242        let file_entry = convert_from_session_entry(&entry);
1243        self.file_entries.write().push(FileEntry::Entry(file_entry));
1244        self.by_id.write().insert(entry.id.clone(), entry.clone());
1245        *self.leaf_id.write() = Some(entry.id.clone());
1246        self._persist(&entry);
1247    }
1248
1249    /// Append a message as child of current leaf
1250    pub fn append_message(&mut self, message: AgentMessage) -> String {
1251        let leaf = self.leaf_id.read().clone();
1252        let id = Uuid::new_v4().to_string();
1253        let entry = SessionEntry {
1254            id: id.clone(),
1255            parent_id: leaf,
1256            timestamp: Utc::now().timestamp_millis(),
1257            message,
1258        };
1259        self._append_entry(entry);
1260        id
1261    }
1262
1263    /// Append a thinking level change
1264    pub fn append_thinking_level_change(&mut self, thinking_level: &str) -> String {
1265        let leaf = self.leaf_id.read().clone();
1266        let id = Uuid::new_v4().to_string();
1267        let entry = SessionEntry {
1268            id: id.clone(),
1269            parent_id: leaf,
1270            timestamp: Utc::now().timestamp_millis(),
1271            message: AgentMessage::Custom {
1272                custom_type: "thinking_level_change".to_string(),
1273                content: ContentValue::String(thinking_level.to_string()),
1274                display: false,
1275                details: None,
1276                timestamp: Utc::now().timestamp_millis(),
1277            },
1278        };
1279        self._append_entry(entry);
1280        id
1281    }
1282
1283    /// Append a model change
1284    pub fn append_model_change(&mut self, provider: &str, model_id: &str) -> String {
1285        let leaf = self.leaf_id.read().clone();
1286        let id = Uuid::new_v4().to_string();
1287        let entry = SessionEntry {
1288            id: id.clone(),
1289            parent_id: leaf,
1290            timestamp: Utc::now().timestamp_millis(),
1291            message: AgentMessage::Custom {
1292                custom_type: "model_change".to_string(),
1293                content: ContentValue::String(format!("{}:{}", provider, model_id)),
1294                display: false,
1295                details: None,
1296                timestamp: Utc::now().timestamp_millis(),
1297            },
1298        };
1299        self._append_entry(entry);
1300        id
1301    }
1302
1303    /// Append a compaction summary
1304    pub fn append_compaction(
1305        &mut self,
1306        summary: &str,
1307        _first_kept_entry_id: &str,
1308        tokens_before: i64,
1309        _details: Option<serde_json::Value>,
1310        _from_hook: Option<bool>,
1311    ) -> String {
1312        let leaf = self.leaf_id.read().clone();
1313        let id = Uuid::new_v4().to_string();
1314        let entry = SessionEntry {
1315            id: id.clone(),
1316            parent_id: leaf,
1317            timestamp: Utc::now().timestamp_millis(),
1318            message: AgentMessage::CompactionSummary {
1319                summary: summary.to_string(),
1320                tokens_before,
1321                timestamp: Utc::now().timestamp_millis(),
1322            },
1323        };
1324        self._append_entry(entry);
1325        id
1326    }
1327
1328    /// Append a custom entry (for extensions)
1329    pub fn append_custom_entry(
1330        &mut self,
1331        custom_type: &str,
1332        data: Option<serde_json::Value>,
1333    ) -> String {
1334        let leaf = self.leaf_id.read().clone();
1335        let id = Uuid::new_v4().to_string();
1336        let entry = SessionEntry {
1337            id: id.clone(),
1338            parent_id: leaf,
1339            timestamp: Utc::now().timestamp_millis(),
1340            message: AgentMessage::Custom {
1341                custom_type: custom_type.to_string(),
1342                content: data
1343                    .as_ref()
1344                    .map(|d| ContentValue::String(d.to_string()))
1345                    .unwrap_or(ContentValue::String(String::new())),
1346                display: false,
1347                details: data.clone(),
1348                timestamp: Utc::now().timestamp_millis(),
1349            },
1350        };
1351        self._append_entry(entry);
1352        id
1353    }
1354
1355    /// Append a session info entry (e.g., display name)
1356    pub fn append_session_info(&mut self, name: &str) -> String {
1357        let leaf = self.leaf_id.read().clone();
1358        let id = Uuid::new_v4().to_string();
1359        let entry = SessionEntry {
1360            id: id.clone(),
1361            parent_id: leaf,
1362            timestamp: Utc::now().timestamp_millis(),
1363            message: AgentMessage::Custom {
1364                custom_type: "session_info".to_string(),
1365                content: ContentValue::String(name.trim().to_string()),
1366                display: false,
1367                details: None,
1368                timestamp: Utc::now().timestamp_millis(),
1369            },
1370        };
1371        self._append_entry(entry);
1372        id
1373    }
1374
1375    /// Get the current session name from the latest session_info entry
1376    pub fn get_session_name(&self) -> Option<String> {
1377        let entries = self.get_entries();
1378        for entry in entries.iter().rev() {
1379            if let AgentMessage::Custom {
1380                custom_type,
1381                content,
1382                ..
1383            } = &entry.message
1384            {
1385                if custom_type == "session_info" {
1386                    return Some(content.as_str().trim().to_string()).filter(|s| !s.is_empty());
1387                }
1388            }
1389        }
1390        None
1391    }
1392
1393    /// Append a custom message entry (for extensions) that participates in LLM context
1394    pub fn append_custom_message_entry(
1395        &mut self,
1396        custom_type: &str,
1397        content: ContentValue,
1398        display: bool,
1399        details: Option<serde_json::Value>,
1400    ) -> String {
1401        let leaf = self.leaf_id.read().clone();
1402        let id = Uuid::new_v4().to_string();
1403        let entry = SessionEntry {
1404            id: id.clone(),
1405            parent_id: leaf,
1406            timestamp: Utc::now().timestamp_millis(),
1407            message: AgentMessage::Custom {
1408                custom_type: custom_type.to_string(),
1409                content,
1410                display,
1411                details,
1412                timestamp: Utc::now().timestamp_millis(),
1413            },
1414        };
1415        self._append_entry(entry);
1416        id
1417    }
1418
1419    // =========================================================================
1420    // Tree Traversal
1421    // =========================================================================
1422
1423    /// Get the current leaf ID
1424    pub fn get_leaf_id(&self) -> Option<String> {
1425        self.leaf_id.read().clone()
1426    }
1427
1428    /// Get the current leaf entry
1429    pub fn get_leaf_entry(&self) -> Option<SessionEntry> {
1430        self.leaf_id
1431            .read()
1432            .as_ref()
1433            .and_then(|id| self.by_id.read().get(id).cloned())
1434    }
1435
1436    /// Get an entry by ID
1437    pub fn get_entry(&self, id: &str) -> Option<SessionEntry> {
1438        self.by_id.read().get(id).cloned()
1439    }
1440
1441    /// Get all direct children of an entry
1442    pub fn get_children(&self, parent_id: &str) -> Vec<SessionEntry> {
1443        self.by_id
1444            .read()
1445            .values()
1446            .filter(|e| e.parent_id.as_deref() == Some(parent_id))
1447            .cloned()
1448            .collect()
1449    }
1450
1451    /// Get the parent of an entry
1452    pub fn get_parent(&self, id: &str) -> Option<SessionEntry> {
1453        self.by_id
1454            .read()
1455            .get(id)
1456            .and_then(|e| e.parent_id.as_deref())
1457            .and_then(|pid| self.by_id.read().get(pid).cloned())
1458    }
1459
1460    /// Get the label for an entry
1461    pub fn get_label(&self, id: &str) -> Option<String> {
1462        self.labels_by_id.read().get(id).cloned()
1463    }
1464
1465    /// Set or clear a label on an entry
1466    pub fn append_label_change(
1467        &mut self,
1468        target_id: &str,
1469        label: Option<&str>,
1470    ) -> Result<String, String> {
1471        if !self.by_id.read().contains_key(target_id) {
1472            return Err(format!("Entry {} not found", target_id));
1473        }
1474
1475        let leaf = self.leaf_id.read().clone();
1476        let id = Uuid::new_v4().to_string();
1477        let entry = SessionEntry {
1478            id: id.clone(),
1479            parent_id: leaf,
1480            timestamp: Utc::now().timestamp_millis(),
1481            message: AgentMessage::Custom {
1482                custom_type: "label".to_string(),
1483                content: ContentValue::String(label.unwrap_or("").to_string()),
1484                display: false,
1485                details: Some(serde_json::json!({ "targetId": target_id })),
1486                timestamp: Utc::now().timestamp_millis(),
1487            },
1488        };
1489
1490        self._append_entry(entry);
1491
1492        if let Some(l) = label {
1493            self.labels_by_id
1494                .write()
1495                .insert(target_id.to_string(), l.to_string());
1496            self.label_timestamps_by_id
1497                .write()
1498                .insert(target_id.to_string(), Utc::now().to_rfc3339());
1499        } else {
1500            self.labels_by_id.write().remove(target_id);
1501            self.label_timestamps_by_id.write().remove(target_id);
1502        }
1503
1504        Ok(id)
1505    }
1506
1507    /// Walk from entry to root, returning all entries in path order
1508    pub fn get_branch(&self, from_id: Option<&str>) -> Vec<SessionEntry> {
1509        let mut path = Vec::new();
1510        let leaf_fallback = self.leaf_id.read().clone();
1511        let start_id = from_id.or(leaf_fallback.as_deref());
1512        let Some(start_id) = start_id else {
1513            return path;
1514        };
1515
1516        // Acquire the lock once and reuse it for the entire traversal
1517        let by_id = self.by_id.read();
1518        let mut current = by_id.get(start_id).cloned();
1519        while let Some(entry) = current {
1520            path.insert(0, entry.clone());
1521            current = entry
1522                .parent_id
1523                .as_ref()
1524                .and_then(|pid| by_id.get(pid).cloned());
1525        }
1526        path
1527    }
1528
1529    /// Get path to root for a given entry
1530    pub fn get_path_to_root(&self, from_id: &str) -> Vec<SessionEntry> {
1531        self.get_branch(Some(from_id))
1532    }
1533
1534    /// Get ancestry (same as path to root)
1535    pub fn get_ancestry(&self, from_id: &str) -> Vec<SessionEntry> {
1536        self.get_branch(Some(from_id))
1537    }
1538
1539    /// Get depth of an entry
1540    pub fn get_depth(&self, id: &str) -> i64 {
1541        let mut depth = 0;
1542        let mut current = self.by_id.read().get(id).cloned();
1543        while let Some(entry) = current {
1544            depth += 1;
1545            current = entry
1546                .parent_id
1547                .as_ref()
1548                .and_then(|pid| self.by_id.read().get(pid).cloned());
1549        }
1550        depth - 1 // Root has depth 0
1551    }
1552
1553    /// Build the session context (what gets sent to the LLM)
1554    pub fn build_session_context(&self) -> SessionContext {
1555        let entries = self.get_entries();
1556        let leaf_id = self.leaf_id.read().clone();
1557        build_session_context_internal(&entries, leaf_id, None)
1558    }
1559
1560    /// Get session header
1561    pub fn get_header(&self) -> Option<SessionHeader> {
1562        self.file_entries.read().iter().find_map(|e| match e {
1563            FileEntry::Header(h) => Some(h.clone()),
1564            _ => None,
1565        })
1566    }
1567
1568    /// Get all session entries (excludes header)
1569    pub fn get_entries(&self) -> Vec<SessionEntry> {
1570        self.by_id.read().values().cloned().collect()
1571    }
1572
1573    /// Get the session as a tree structure
1574    /// If id is provided, returns tree for that session (backward compat)
1575    pub fn get_tree(&self, _id: Uuid) -> anyhow::Result<Vec<SessionTreeNode>> {
1576        let entries = self.get_entries();
1577        let labels: HashMap<String, String> = self.labels_by_id.read().clone();
1578        let label_timestamps: HashMap<String, String> = self.label_timestamps_by_id.read().clone();
1579
1580        let mut adj: HashMap<String, Vec<String>> = HashMap::new();
1581        let mut root_ids: Vec<String> = Vec::new();
1582
1583        // Build adjacency list
1584        for entry in &entries {
1585            adj.insert(entry.id.clone(), Vec::new());
1586        }
1587
1588        // Determine parent-child relationships
1589        for entry in &entries {
1590            let is_root = match entry.parent_id.as_deref() {
1591                Some(pid) if pid != entry.id => !adj.contains_key(pid),
1592                _ => true,
1593            };
1594            if is_root {
1595                root_ids.push(entry.id.clone());
1596            } else if let Some(ref pid) = entry.parent_id {
1597                if let Some(children) = adj.get_mut(pid.as_str()) {
1598                    children.push(entry.id.clone());
1599                } else {
1600                    root_ids.push(entry.id.clone());
1601                }
1602            }
1603        }
1604
1605        // Build entries map
1606        let entries_map: HashMap<String, SessionEntry> =
1607            entries.into_iter().map(|e| (e.id.clone(), e)).collect();
1608
1609        // Recursively build tree nodes
1610        fn build(
1611            id: &str,
1612            adj: &HashMap<String, Vec<String>>,
1613            entries_map: &HashMap<String, SessionEntry>,
1614            labels: &HashMap<String, String>,
1615            label_timestamps: &HashMap<String, String>,
1616        ) -> anyhow::Result<SessionTreeNode> {
1617            let entry = entries_map
1618                .get(id)
1619                .ok_or_else(|| anyhow::anyhow!("Corrupted session: entry {} not found", id))?
1620                .clone();
1621            let child_ids = adj.get(id).cloned().unwrap_or_default();
1622            let children: Vec<SessionTreeNode> = child_ids
1623                .iter()
1624                .map(|cid| build(cid, adj, entries_map, labels, label_timestamps))
1625                .collect::<Result<Vec<_>, _>>()?;
1626            Ok(SessionTreeNode {
1627                entry,
1628                children,
1629                label: labels.get(id).cloned(),
1630                label_timestamp: label_timestamps.get(id).cloned(),
1631            })
1632        }
1633
1634        let mut roots = root_ids
1635            .into_iter()
1636            .map(|rid| build(&rid, &adj, &entries_map, &labels, &label_timestamps))
1637            .collect::<anyhow::Result<Vec<_>>>()?;
1638
1639        sort_tree_by_timestamp(&mut roots);
1640        Ok(roots)
1641    }
1642
1643    // =========================================================================
1644    // Branching
1645    // =========================================================================
1646
1647    /// Start a new branch from an earlier entry
1648    pub fn branch(&mut self, branch_from_id: &str) -> Result<(), String> {
1649        if !self.by_id.read().contains_key(branch_from_id) {
1650            return Err(format!("Entry {} not found", branch_from_id));
1651        }
1652        *self.leaf_id.write() = Some(branch_from_id.to_string());
1653        Ok(())
1654    }
1655
1656    /// Reset the leaf pointer to null (before any entries)
1657    pub fn reset_leaf(&mut self) {
1658        *self.leaf_id.write() = None;
1659    }
1660
1661    /// Start a new branch with a summary of the abandoned path
1662    pub fn branch_with_summary(
1663        &mut self,
1664        branch_from_id: Option<&str>,
1665        summary: &str,
1666        _details: Option<serde_json::Value>,
1667        _from_hook: Option<bool>,
1668    ) -> String {
1669        if let Some(id) = branch_from_id {
1670            if !self.by_id.read().contains_key(id) {
1671                return String::new();
1672            }
1673        }
1674
1675        *self.leaf_id.write() = branch_from_id.map(|s| s.to_string());
1676
1677        let id = Uuid::new_v4().to_string();
1678        let entry = SessionEntry {
1679            id: id.clone(),
1680            parent_id: branch_from_id.map(|s| s.to_string()),
1681            timestamp: Utc::now().timestamp_millis(),
1682            message: AgentMessage::BranchSummary {
1683                summary: summary.to_string(),
1684                from_id: branch_from_id.unwrap_or("root").to_string(),
1685                timestamp: Utc::now().timestamp_millis(),
1686            },
1687        };
1688
1689        self._append_entry(entry);
1690        id
1691    }
1692
1693    /// Add a label to the session
1694    pub fn add_label(&mut self, target_id: &str, label: &str) -> Result<String, String> {
1695        self.append_label_change(target_id, Some(label))
1696    }
1697
1698    /// Remove a label from an entry
1699    pub fn remove_label(&mut self, target_id: &str) -> Result<String, String> {
1700        self.append_label_change(target_id, None)
1701    }
1702
1703    // =========================================================================
1704    // Compaction Support
1705    // =========================================================================
1706
1707    /// Get the latest compaction entry
1708    pub fn get_latest_compaction_entry(&self) -> Option<SessionEntry> {
1709        let entries = self.get_entries();
1710        for entry in entries.iter().rev() {
1711            if let AgentMessage::CompactionSummary { .. } = &entry.message {
1712                return Some(entry.clone());
1713            }
1714        }
1715        None
1716    }
1717
1718    /// Get all compaction entries
1719    pub fn get_compaction_entries(&self) -> Vec<SessionEntry> {
1720        self.get_entries()
1721            .iter()
1722            .filter(|e| matches!(&e.message, AgentMessage::CompactionSummary { .. }))
1723            .cloned()
1724            .collect()
1725    }
1726
1727    // =========================================================================
1728    // Session Statistics
1729    // =========================================================================
1730
1731    /// Get session statistics
1732    pub fn get_session_stats(&self) -> SessionStats {
1733        let entries = self.get_entries();
1734        let mut message_count = 0i64;
1735        let mut user_message_count = 0i64;
1736        let mut assistant_message_count = 0i64;
1737        let mut total_chars = 0i64;
1738        let mut total_tokens_estimate = 0i64;
1739
1740        for entry in &entries {
1741            if let AgentMessage::User { .. } = &entry.message {
1742                user_message_count += 1;
1743            }
1744            if let AgentMessage::Assistant { .. } = &entry.message {
1745                assistant_message_count += 1;
1746            }
1747            if entry.message.is_user() || entry.message.is_assistant() {
1748                message_count += 1;
1749                // Estimate tokens from message
1750                let content = entry.content();
1751                let chars = content.len() as i64;
1752                total_chars += chars;
1753                total_tokens_estimate += (chars as f64 / 4.0).ceil() as i64;
1754            }
1755        }
1756
1757        SessionStats {
1758            message_count,
1759            user_message_count,
1760            assistant_message_count,
1761            total_chars,
1762            estimated_tokens: total_tokens_estimate,
1763        }
1764    }
1765
1766    // =========================================================================
1767    // Static Methods
1768    // =========================================================================
1769
1770    /// List all sessions for a directory
1771    pub async fn list(cwd: &str, session_dir: Option<&str>) -> Result<Vec<SessionInfo>> {
1772        let dir = session_dir
1773            .map(|s| s.to_string())
1774            .unwrap_or_else(|| get_default_session_dir(cwd));
1775        list_sessions_from_dir(&dir).await
1776    }
1777
1778    /// List all sessions across all project directories
1779    pub async fn list_all() -> Result<Vec<SessionInfo>> {
1780        let sessions_dir = get_sessions_dir();
1781
1782        if !Path::new(&sessions_dir).exists() {
1783            return Ok(Vec::new());
1784        }
1785
1786        let mut all_sessions = Vec::new();
1787        let entries = fs::read_dir(&sessions_dir)?;
1788
1789        for entry in entries {
1790            let entry = entry?;
1791            let path = entry.path();
1792            if path.is_dir() {
1793                if let Ok(sessions) = list_sessions_from_dir(&path.to_string_lossy()).await {
1794                    all_sessions.extend(sessions);
1795                }
1796            }
1797        }
1798
1799        all_sessions.sort_by_key(|b| std::cmp::Reverse(b.modified));
1800        Ok(all_sessions)
1801    }
1802
1803    /// Fork a session from another project directory into the current project
1804    pub fn fork_from(
1805        source_path: &str,
1806        target_cwd: &str,
1807        session_dir: Option<&str>,
1808    ) -> Result<Self, String> {
1809        let source_entries = load_entries_from_file(source_path);
1810        if source_entries.is_empty() {
1811            return Err(format!(
1812                "Cannot fork: source session file is empty or invalid: {}",
1813                source_path
1814            ));
1815        }
1816
1817        let source_header = source_entries.iter().find_map(|e| match e {
1818            FileEntry::Header(h) => Some(h),
1819            _ => None,
1820        });
1821        if source_header.is_none() {
1822            return Err(format!(
1823                "Cannot fork: source session has no header: {}",
1824                source_path
1825            ));
1826        }
1827
1828        let dir = session_dir
1829            .map(|s| s.to_string())
1830            .unwrap_or_else(|| get_default_session_dir(target_cwd));
1831
1832        if !Path::new(&dir).exists() {
1833            let _ = fs::create_dir_all(&dir);
1834        }
1835
1836        let new_session_id = Uuid::new_v4().to_string();
1837        let timestamp = Utc::now().to_rfc3339();
1838        let file_timestamp = timestamp.replace([':', '.', 'T', '-', ':', '+'], "-");
1839        let short_id = &new_session_id[..8];
1840        let new_session_file = format!("{}/{}_{}.jsonl", dir, file_timestamp, short_id);
1841
1842        // Write new header pointing to source as parent
1843        let new_header = SessionHeader {
1844            entry_type: "session".to_string(),
1845            version: Some(CURRENT_SESSION_VERSION),
1846            id: new_session_id.clone(),
1847            timestamp: timestamp.clone(),
1848            cwd: target_cwd.to_string(),
1849            parent_session: Some(source_path.to_string()),
1850        };
1851
1852        let mut handle = fs::OpenOptions::new()
1853            .create(true)
1854            .truncate(true)
1855            .write(true)
1856            .open(&new_session_file)
1857            .map_err(|e| e.to_string())?;
1858        writeln!(
1859            &mut handle,
1860            "{}",
1861            serde_json::to_string(&new_header).expect("session header serializable")
1862        )
1863        .map_err(|e| e.to_string())?;
1864
1865        // Copy all non-header entries from source
1866        for file_entry in &source_entries {
1867            if let FileEntry::Entry(_) = file_entry {
1868                writeln!(
1869                    &mut handle,
1870                    "{}",
1871                    serde_json::to_string(file_entry).expect("session entry serializable")
1872                )
1873                .map_err(|e| e.to_string())?;
1874            }
1875        }
1876
1877        Ok(Self::open(&new_session_file, Some(&dir), Some(target_cwd)))
1878    }
1879
1880    /// Delete a session
1881    pub fn delete_session(path: &str) -> Result<()> {
1882        fs::remove_file(path).context("Failed to delete session file")?;
1883        Ok(())
1884    }
1885
1886    /// Rename a session (set its display name)
1887    pub fn rename_session(&mut self, name: &str) -> String {
1888        self.append_session_info(name)
1889    }
1890
1891    // =========================================================================
1892    // Backward Compatibility Methods
1893    // =========================================================================
1894
1895    /// Create a new SessionManager (async for backward compatibility)
1896    pub async fn new() -> Result<Self> {
1897        Self::new_async().await
1898    }
1899
1900    /// Create a new SessionManager (async for backward compatibility)
1901    pub async fn new_async() -> Result<Self> {
1902        let home = dirs::home_dir().context("Cannot find home directory")?;
1903        let base_dir = home.join(".oxi");
1904        let sessions_dir = base_dir.join("sessions");
1905        tokio::fs::create_dir_all(&sessions_dir).await?;
1906        let cwd = std::env::current_dir()
1907            .unwrap_or_else(|_| PathBuf::from("."))
1908            .to_string_lossy()
1909            .to_string();
1910        Ok(Self::in_memory(&cwd))
1911    }
1912
1913    /// Get the session file path for a given session ID
1914    pub fn session_path(&self, id: &Uuid) -> PathBuf {
1915        if let Some(file) = &self.session_file {
1916            PathBuf::from(file)
1917        } else {
1918            PathBuf::from(format!("{}/{}.jsonl", self.session_dir, id))
1919        }
1920    }
1921
1922    /// List all sessions (backward compat)
1923    pub async fn list_sessions(&self) -> Result<Vec<SessionMeta>> {
1924        // Simple implementation: scan the session dir for jsonl files
1925        let mut metas = Vec::new();
1926        let session_dir = Path::new(&self.session_dir);
1927        if !session_dir.exists() {
1928            return Ok(metas);
1929        }
1930        let entries = fs::read_dir(session_dir)?;
1931        for entry in entries {
1932            let entry = entry?;
1933            let path = entry.path();
1934            if path.extension().map(|e| e == "jsonl").unwrap_or(false) {
1935                let file_name = path
1936                    .file_stem()
1937                    .unwrap_or_else(|| std::ffi::OsStr::new(""))
1938                    .to_string_lossy()
1939                    .to_string();
1940                // Try to extract uuid from filename
1941                if let Some(uuid_part) = file_name.split('_').next_back() {
1942                    if let Ok(uuid) = Uuid::parse_str(uuid_part) {
1943                        let mtime = entry.metadata().ok().and_then(|m| m.modified().ok());
1944                        let now_ts = Utc::now().timestamp_millis();
1945                        metas.push(SessionMeta {
1946                            id: uuid,
1947                            parent_id: None,
1948                            root_id: None,
1949                            branch_point: None,
1950                            created_at: now_ts,
1951                            updated_at: mtime
1952                                .map(|t| {
1953                                    let dt: DateTime<Utc> = DateTime::from(t);
1954                                    dt.timestamp_millis()
1955                                })
1956                                .unwrap_or(now_ts),
1957                            name: None,
1958                        });
1959                    }
1960                }
1961            }
1962        }
1963        metas.sort_by_key(|b| std::cmp::Reverse(b.updated_at));
1964        Ok(metas)
1965    }
1966
1967    /// Save entries (backward compat)
1968    pub async fn save(&self, _id: Uuid, _entries: &[SessionEntry]) -> Result<()> {
1969        self._rewrite_file();
1970        Ok(())
1971    }
1972
1973    /// Load entries (backward compat)
1974    pub async fn load(&self, _id: Uuid) -> Result<Vec<SessionEntry>> {
1975        Ok(self.get_entries())
1976    }
1977
1978    /// Delete a session (backward compat)
1979    pub async fn delete(&self, id: Uuid) -> Result<()> {
1980        let path = self.session_path(&id);
1981        if path.exists() {
1982            fs::remove_file(path).context("Failed to delete session file")?;
1983        }
1984        Ok(())
1985    }
1986
1987    /// Create a branch from an existing session at a given entry
1988    pub async fn branch_from(
1989        &self,
1990        parent_id: Uuid,
1991        entry_id: Uuid,
1992    ) -> Result<(Uuid, Vec<SessionEntry>)> {
1993        let _entry_id_str = entry_id.to_string();
1994        let _parent_id_str = parent_id.to_string();
1995
1996        // Get entries up to the branch point
1997        let _entries = self.get_entries();
1998        let path = self.get_branch(Some(&entry_id.to_string()));
1999
2000        let new_id = Uuid::new_v4();
2001        let new_entries: Vec<SessionEntry> = path
2002            .into_iter()
2003            .map(|e| {
2004                let mut new_entry = e.clone();
2005                new_entry.id = Uuid::new_v4().to_string();
2006                new_entry
2007            })
2008            .collect();
2009
2010        // Update the last entry to have parent reference
2011        // (simplified version of the original branch_from)
2012        Ok((new_id, new_entries))
2013    }
2014
2015    /// Get branch info for a session
2016    pub async fn get_branch_info(&self, _id: Uuid) -> Result<Option<BranchInfo>> {
2017        // Simplified implementation
2018        Ok(None)
2019    }
2020
2021    /// Get tree for a specific session (backward compat)
2022    pub async fn get_tree_async(&self, _id: Uuid) -> Result<Vec<SessionTreeNode>> {
2023        self.get_tree(Uuid::nil())
2024    }
2025
2026    /// Save metadata (backward compat)
2027    pub async fn save_meta(&self, _meta: &SessionMeta) -> Result<()> {
2028        Ok(())
2029    }
2030
2031    /// Load metadata (backward compat)
2032    pub async fn load_meta(&self, _id: Uuid) -> Result<Option<SessionMeta>> {
2033        Ok(None)
2034    }
2035
2036    /// Create a new session (backward compat)
2037    pub async fn create_session(&mut self) -> Result<SessionMeta> {
2038        let id = Uuid::new_v4();
2039        let meta = SessionMeta::new(id);
2040        Ok(meta)
2041    }
2042
2043    /// Fork from current session at a specific entry, creating a new session file. Synchronous.
2044    pub fn branch_from_entry(&self, entry_id: &str) -> Result<String, String> {
2045        let path = self
2046            .get_session_file()
2047            .ok_or_else(|| "No session file path".to_string())?;
2048        let source_entries = load_entries_from_file(&path);
2049        if source_entries.is_empty() {
2050            return Err("Cannot fork: source session is empty".to_string());
2051        }
2052        // Validate header exists (content will be replaced with fresh header below)
2053        let _header = source_entries
2054            .iter()
2055            .find_map(|e| match e {
2056                FileEntry::Header(h) => Some(h),
2057                _ => None,
2058            })
2059            .ok_or_else(|| "Missing session header".to_string())?;
2060        let new_id = Uuid::new_v4().to_string();
2061        let timestamp = chrono::Utc::now().to_rfc3339();
2062        let file_timestamp = timestamp.replace([':', '.', 'T', '-', ':', '+'], "-");
2063        let short_id = &new_id[..8];
2064        let dir = std::path::Path::new(&path)
2065            .parent()
2066            .map(|p| p.to_string_lossy().into_owned())
2067            .unwrap_or_else(|| ".".to_string());
2068        let new_file = format!("{}/{}_{}.jsonl", dir, file_timestamp, short_id);
2069        let mut found = false;
2070        let mut new_entries = vec![FileEntry::Header(SessionHeader {
2071            entry_type: "session".to_string(),
2072            version: Some(CURRENT_SESSION_VERSION),
2073            id: new_id.clone(),
2074            timestamp,
2075            cwd: self.get_cwd(),
2076            parent_session: Some(path),
2077        })];
2078        for file_entry in &source_entries {
2079            if let FileEntry::Entry(entry) = file_entry {
2080                let eid = match entry {
2081                    SessionEntryEnum::Message(m) => m.base.id.clone(),
2082                    SessionEntryEnum::ThinkingLevelChange(m) => m.base.id.clone(),
2083                    SessionEntryEnum::ModelChange(m) => m.base.id.clone(),
2084                    SessionEntryEnum::Compaction(m) => m.base.id.clone(),
2085                    SessionEntryEnum::BranchSummary(m) => m.base.id.clone(),
2086                    SessionEntryEnum::Custom(m) => m.base.id.clone(),
2087                    SessionEntryEnum::Label(m) => m.base.id.clone(),
2088                    SessionEntryEnum::SessionInfo(m) => m.base.id.clone(),
2089                    SessionEntryEnum::CustomMessage(m) => m.base.id.clone(),
2090                };
2091                if eid == entry_id {
2092                    found = true;
2093                }
2094                if found {
2095                    new_entries.push(FileEntry::Entry(entry.clone()));
2096                }
2097            }
2098        }
2099        if !found {
2100            return Err(format!("Entry not found: {}", entry_id));
2101        }
2102        let mut handle = std::fs::OpenOptions::new()
2103            .create(true)
2104            .truncate(true)
2105            .write(true)
2106            .open(&new_file)
2107            .map_err(|e| e.to_string())?;
2108        for entry in &new_entries {
2109            let line = serde_json::to_string(entry).map_err(|e| e.to_string())?;
2110            writeln!(&mut handle, "{}", line).map_err(|e| e.to_string())?;
2111        }
2112        Ok(new_file)
2113    }
2114}
2115
2116// ============================================================================
2117// Internal Conversion Functions
2118// ============================================================================
2119
2120/// Convert internal enum to simple SessionEntry struct
2121fn convert_to_session_entry(entry: &SessionEntryEnum) -> Option<SessionEntry> {
2122    match entry {
2123        SessionEntryEnum::Message(m) => Some(SessionEntry {
2124            id: m.base.id.clone(),
2125            parent_id: m.base.parent_id.clone(),
2126            timestamp: DateTime::parse_from_rfc3339(&m.base.timestamp)
2127                .map(|dt| dt.timestamp_millis())
2128                .unwrap_or(0),
2129            message: m.message.clone(),
2130        }),
2131        _ => None, // For now, we only convert message entries to the simple struct
2132    }
2133}
2134
2135/// Convert simple SessionEntry to internal FileEntry for persistence
2136fn convert_from_session_entry(entry: &SessionEntry) -> SessionEntryEnum {
2137    let timestamp = DateTime::from_timestamp_millis(entry.timestamp)
2138        .map(|dt| dt.to_rfc3339())
2139        .unwrap_or_else(|| Utc::now().to_rfc3339());
2140
2141    SessionEntryEnum::Message(SessionMessageEntry {
2142        base: SessionEntryBase {
2143            entry_type: "message".to_string(),
2144            id: entry.id.clone(),
2145            parent_id: entry.parent_id.clone(),
2146            timestamp,
2147        },
2148        message: entry.message.clone(),
2149    })
2150}
2151
2152// ============================================================================
2153// Session Statistics
2154// ============================================================================
2155
2156/// Session Stats.
2157#[derive(Debug, Clone)]
2158pub struct SessionStats {
2159    /// The message count.
2160    pub message_count: i64,
2161    /// The user message count.
2162    pub user_message_count: i64,
2163    /// The assistant message count.
2164    pub assistant_message_count: i64,
2165    /// The total chars.
2166    pub total_chars: i64,
2167    /// The estimated tokens.
2168    pub estimated_tokens: i64,
2169}
2170
2171// ============================================================================
2172// NewSessionOptions
2173// ============================================================================
2174
2175/// New Session Options.
2176#[derive(Debug, Clone)]
2177pub struct NewSessionOptions {
2178    /// The id.
2179    pub id: Option<String>,
2180    /// The parent session.
2181    pub parent_session: Option<String>,
2182}
2183
2184// ============================================================================
2185// Helper Functions
2186// ============================================================================
2187
2188/// Get default session dir.
2189pub fn get_default_session_dir(cwd: &str) -> String {
2190    let agent_dir = get_agent_dir();
2191    let safe_path = format!("--{}--", cwd.replace(['/', '\\', ':'], "-"));
2192    let session_dir = format!("{}/sessions/{}", agent_dir, safe_path);
2193
2194    if !Path::new(&session_dir).exists() {
2195        let _ = fs::create_dir_all(&session_dir);
2196    }
2197
2198    session_dir
2199}
2200
2201fn get_agent_dir() -> String {
2202    dirs::home_dir()
2203        .map(|h| h.join(".oxi").to_string_lossy().to_string())
2204        .unwrap_or_else(|| ".oxi".to_string())
2205}
2206
2207fn get_sessions_dir() -> String {
2208    format!("{}/sessions", get_agent_dir())
2209}
2210
2211/// Load entries from a JSONL file
2212fn load_entries_from_file(file_path: &str) -> Vec<FileEntry> {
2213    if !Path::new(file_path).exists() {
2214        return Vec::new();
2215    }
2216
2217    let file = match File::open(file_path) {
2218        Ok(f) => f,
2219        Err(_) => return Vec::new(),
2220    };
2221
2222    let reader = BufReader::new(file);
2223    let mut entries = Vec::new();
2224
2225    for line in reader.lines() {
2226        let line = match line {
2227            Ok(l) => l,
2228            Err(_) => continue,
2229        };
2230        if line.trim().is_empty() {
2231            continue;
2232        }
2233        match serde_json::from_str::<FileEntry>(&line) {
2234            Ok(entry) => entries.push(entry),
2235            Err(_) => continue,
2236        }
2237    }
2238
2239    // Validate session header
2240    if entries.is_empty() {
2241        return entries;
2242    }
2243    let header = match &entries[0] {
2244        FileEntry::Header(h) => h,
2245        _ => return Vec::new(),
2246    };
2247    if header.entry_type != "session" || header.id.is_empty() {
2248        return Vec::new();
2249    }
2250
2251    entries
2252}
2253
2254/// Check if a file is a valid session file
2255fn is_valid_session_file(file_path: &str) -> bool {
2256    if let Ok(mut file) = File::open(file_path) {
2257        use std::io::Read;
2258        let mut buffer = vec![0u8; 512];
2259        if let Ok(bytes_read) = file.read(&mut buffer) {
2260            if let Ok(content) = String::from_utf8(buffer[..bytes_read].to_vec()) {
2261                if let Some(first_line) = content.split('\n').next() {
2262                    if let Ok(header) = serde_json::from_str::<SessionHeader>(first_line) {
2263                        return header.entry_type == "session" && !header.id.is_empty();
2264                    }
2265                }
2266            }
2267        }
2268    }
2269    false
2270}
2271
2272/// Find the path of the most recent session for the given working directory.
2273pub fn find_recent_session_path(cwd: &str) -> Option<String> {
2274    let dir = get_default_session_dir(cwd);
2275    find_most_recent_session(&dir)
2276}
2277
2278fn find_most_recent_session(session_dir: &str) -> Option<String> {
2279    if !Path::new(session_dir).exists() {
2280        return None;
2281    }
2282
2283    let mut files: Vec<(String, std::time::SystemTime)> = Vec::new();
2284
2285    if let Ok(entries) = fs::read_dir(session_dir) {
2286        for entry in entries.flatten() {
2287            let path = entry.path();
2288            if path.extension().map(|e| e == "jsonl").unwrap_or(false) {
2289                if let Some(path_str) = path.to_str() {
2290                    if is_valid_session_file(path_str) {
2291                        if let Ok(metadata) = entry.metadata() {
2292                            if let Ok(mtime) = metadata.modified() {
2293                                files.push((path_str.to_string(), mtime));
2294                            }
2295                        }
2296                    }
2297                }
2298            }
2299        }
2300    }
2301
2302    files.sort_by_key(|b| std::cmp::Reverse(b.1));
2303    files.into_iter().next().map(|(p, _)| p)
2304}
2305
2306/// Resolve a session file path from user input, handling relative paths and ~.
2307pub fn resolve_session_path(input: &str, cwd: &str) -> Result<String, String> {
2308    let path = input.trim();
2309    if path.is_empty() {
2310        return Err("Empty path".to_string());
2311    }
2312    let resolved = if let Some(rest) = path.strip_prefix('~') {
2313        if rest.is_empty() {
2314            let home = dirs::home_dir().ok_or_else(|| "Cannot find home directory".to_string())?;
2315            home.to_string_lossy().into_owned()
2316        } else if let Some(rest) = rest.strip_prefix('/') {
2317            let home = dirs::home_dir().ok_or_else(|| "Cannot find home directory".to_string())?;
2318            format!("{}/{}", home.to_string_lossy(), rest)
2319        } else {
2320            let home = dirs::home_dir().ok_or_else(|| "Cannot find home directory".to_string())?;
2321            format!("{}/{}", home.to_string_lossy(), rest)
2322        }
2323    } else if path.starts_with('/') || path.contains(':') {
2324        path.to_string()
2325    } else {
2326        if let Some(stripped) = path.strip_prefix("./") {
2327            format!("{}/{}", cwd.trim_end_matches('/'), stripped)
2328        } else {
2329            format!("{}/{}", cwd.trim_end_matches('/'), path)
2330        }
2331    };
2332    let p = std::path::Path::new(&resolved);
2333    p.canonicalize()
2334        .map(|c| c.to_string_lossy().into_owned())
2335        .or(Ok(resolved))
2336}
2337
2338/// Build session context from entries using tree traversal
2339fn build_session_context_internal(
2340    entries: &[SessionEntry],
2341    leaf_id: Option<String>,
2342    _by_id: Option<&RwLock<HashMap<String, SessionEntry>>>,
2343) -> SessionContext {
2344    // Find leaf
2345    let leaf: Option<&SessionEntry> = leaf_id
2346        .as_ref()
2347        .and_then(|id| entries.iter().find(|e| e.id == *id));
2348
2349    let leaf = leaf.or_else(|| entries.last());
2350
2351    let Some(leaf) = leaf else {
2352        return SessionContext {
2353            messages: Vec::new(),
2354            thinking_level: "off".to_string(),
2355            model: None,
2356        };
2357    };
2358
2359    // Walk from leaf to root, collecting path
2360    let mut path: Vec<&SessionEntry> = Vec::new();
2361    let mut current: Option<&SessionEntry> = Some(leaf);
2362    while let Some(entry) = current {
2363        path.insert(0, entry);
2364        current = entry
2365            .parent_id
2366            .as_ref()
2367            .and_then(|pid| entries.iter().find(|e| e.id == *pid));
2368    }
2369
2370    // Extract settings
2371    let mut thinking_level = "off".to_string();
2372    let mut model: Option<ModelInfo> = None;
2373
2374    for entry in &path {
2375        if let AgentMessage::Assistant {
2376            provider, model_id, ..
2377        } = &entry.message
2378        {
2379            model = Some(ModelInfo {
2380                provider: provider.clone().unwrap_or_default(),
2381                model_id: model_id.clone().unwrap_or_default(),
2382            });
2383        }
2384        if let AgentMessage::Custom {
2385            custom_type,
2386            content,
2387            ..
2388        } = &entry.message
2389        {
2390            if custom_type == "thinking_level_change" {
2391                thinking_level = content.as_str().to_string();
2392            }
2393        }
2394    }
2395
2396    // Build messages - include all messages in the path
2397    let messages: Vec<AgentMessage> = path
2398        .iter()
2399        .filter(|e| {
2400            e.message.is_user()
2401                || e.message.is_assistant()
2402                || matches!(&e.message, AgentMessage::BranchSummary { .. })
2403                || matches!(&e.message, AgentMessage::CompactionSummary { .. })
2404        })
2405        .map(|e| e.message.clone())
2406        .collect();
2407
2408    SessionContext {
2409        messages,
2410        thinking_level,
2411        model,
2412    }
2413}
2414
2415/// Sort tree nodes by timestamp
2416fn sort_tree_by_timestamp(nodes: &mut Vec<SessionTreeNode>) {
2417    nodes.sort_by_key(|a| a.entry.timestamp);
2418
2419    for node in nodes {
2420        sort_tree_by_timestamp(&mut node.children);
2421    }
2422}
2423
2424/// List sessions from a directory
2425async fn list_sessions_from_dir(dir: &str) -> Result<Vec<SessionInfo>> {
2426    if !Path::new(dir).exists() {
2427        return Ok(Vec::new());
2428    }
2429
2430    let mut sessions = Vec::new();
2431
2432    let entries = fs::read_dir(dir)?;
2433    let files: Vec<String> = entries
2434        .filter_map(|e| e.ok())
2435        .filter(|e| {
2436            e.path()
2437                .extension()
2438                .map(|ext| ext == "jsonl")
2439                .unwrap_or(false)
2440        })
2441        .filter_map(|e| e.path().to_str().map(|s| s.to_string()))
2442        .collect();
2443
2444    for file in files {
2445        if let Some(info) = build_session_info(&file).await {
2446            sessions.push(info);
2447        }
2448    }
2449
2450    Ok(sessions)
2451}
2452
2453/// Build session info from a file
2454async fn build_session_info(file_path: &str) -> Option<SessionInfo> {
2455    let content = fs::read_to_string(file_path).ok()?;
2456    let entries = parse_session_entries(&content)?;
2457
2458    if entries.is_empty() {
2459        return None;
2460    }
2461
2462    let header = match &entries[0] {
2463        FileEntry::Header(h) => h,
2464        _ => return None,
2465    };
2466
2467    let stats = fs::metadata(file_path).ok()?;
2468    let mut message_count = 0i64;
2469    let mut first_message = String::new();
2470    let mut all_messages = Vec::new();
2471    let mut name: Option<String> = None;
2472
2473    for entry in &entries {
2474        if let FileEntry::Entry(e) = entry {
2475            // Check for session_info
2476            if let SessionEntryEnum::SessionInfo(si) = e {
2477                name = si
2478                    .name
2479                    .clone()
2480                    .map(|n| n.trim().to_string())
2481                    .filter(|n| !n.is_empty());
2482            }
2483            // Check for messages
2484            if let SessionEntryEnum::Message(m) = e {
2485                if m.message.is_user() {
2486                    message_count += 1;
2487                    let text = m.message.content();
2488                    if !text.is_empty() {
2489                        all_messages.push(text.clone());
2490                        if first_message.is_empty() {
2491                            first_message = text;
2492                        }
2493                    }
2494                }
2495            }
2496        }
2497    }
2498
2499    let cwd = header.cwd.clone();
2500    let parent_session_path = header.parent_session.clone();
2501    let created = chrono::DateTime::parse_from_rfc3339(&header.timestamp)
2502        .map(|dt| dt.with_timezone(&Utc))
2503        .unwrap_or_else(|_| Utc::now());
2504    let modified = get_session_modified_date(&entries, &header.timestamp, &stats);
2505
2506    Some(SessionInfo {
2507        path: file_path.to_string(),
2508        id: header.id.clone(),
2509        cwd,
2510        name,
2511        parent_session_path,
2512        created,
2513        modified,
2514        message_count,
2515        first_message: if first_message.is_empty() {
2516            "(no messages)".to_string()
2517        } else {
2518            first_message
2519        },
2520        all_messages_text: all_messages.join(" "),
2521    })
2522}
2523
2524/// Parse session entries from content
2525fn parse_session_entries(content: &str) -> Option<Vec<FileEntry>> {
2526    let mut entries = Vec::new();
2527
2528    for line in content.trim().lines() {
2529        if line.trim().is_empty() {
2530            continue;
2531        }
2532        if let Ok(entry) = serde_json::from_str::<FileEntry>(line) {
2533            entries.push(entry);
2534        }
2535    }
2536
2537    Some(entries)
2538}
2539
2540/// Get session modified date
2541fn get_session_modified_date(
2542    entries: &[FileEntry],
2543    header_timestamp: &str,
2544    stats: &std::fs::Metadata,
2545) -> DateTime<Utc> {
2546    let last_activity_time = get_last_activity_time(entries);
2547    if let Some(t) = last_activity_time {
2548        if t > 0 {
2549            return DateTime::from_timestamp_millis(t).unwrap_or_else(Utc::now);
2550        }
2551    }
2552
2553    let header_time = chrono::DateTime::parse_from_rfc3339(header_timestamp)
2554        .map(|dt| dt.timestamp_millis())
2555        .unwrap_or(-1);
2556
2557    if header_time > 0 {
2558        return DateTime::from_timestamp_millis(header_time).unwrap_or_else(Utc::now);
2559    }
2560
2561    if let Ok(mtime) = stats.modified() {
2562        return DateTime::from(mtime);
2563    }
2564
2565    Utc::now()
2566}
2567
2568/// Get last activity time from entries
2569fn get_last_activity_time(entries: &[FileEntry]) -> Option<i64> {
2570    let mut last_activity: Option<i64> = None;
2571
2572    for entry in entries {
2573        let entry = match entry {
2574            FileEntry::Entry(e) => e,
2575            _ => continue,
2576        };
2577
2578        if let SessionEntryEnum::Message(m) = entry {
2579            if m.message.is_user() || m.message.is_assistant() {
2580                last_activity = Some(std::cmp::max(
2581                    last_activity.unwrap_or(0),
2582                    m.base.timestamp.parse().unwrap_or(0),
2583                ));
2584            }
2585        }
2586    }
2587
2588    last_activity
2589}
2590
2591// ============================================================================
2592// Tests
2593// ============================================================================
2594
2595#[cfg(test)]
2596mod tests {
2597    use super::*;
2598
2599    #[test]
2600    fn test_session_creation() {
2601        let manager = SessionManager::in_memory("/tmp");
2602        assert!(!manager.get_session_id().is_empty());
2603        assert_eq!(manager.get_entries().len(), 0);
2604    }
2605
2606    #[test]
2607    fn test_append_message() {
2608        let mut manager = SessionManager::in_memory("/tmp");
2609        let id = manager.append_message(AgentMessage::User {
2610            content: ContentValue::String("Hello".to_string()),
2611        });
2612        assert!(!id.is_empty());
2613        assert_eq!(manager.get_entries().len(), 1);
2614        assert_eq!(manager.get_leaf_id(), Some(id));
2615    }
2616
2617    #[test]
2618    fn test_tree_traversal() {
2619        let mut manager = SessionManager::in_memory("/tmp");
2620        let id1 = manager.append_message(AgentMessage::User {
2621            content: ContentValue::String("Hello".to_string()),
2622        });
2623        let id2 = manager.append_message(AgentMessage::Assistant {
2624            content: vec![],
2625            provider: None,
2626            model_id: None,
2627            usage: None,
2628            stop_reason: None,
2629        });
2630
2631        // Get branch from root
2632        let branch = manager.get_branch(None);
2633        assert_eq!(branch.len(), 2);
2634
2635        // Get branch from specific entry
2636        let branch = manager.get_branch(Some(&id1));
2637        assert_eq!(branch.len(), 1);
2638
2639        // Get children
2640        let children = manager.get_children(&id1);
2641        assert_eq!(children.len(), 1);
2642
2643        // Get parent
2644        let parent = manager.get_parent(&id2);
2645        assert!(parent.is_some());
2646        assert_eq!(parent.unwrap().id, id1);
2647    }
2648
2649    #[test]
2650    fn test_branching() {
2651        let mut manager = SessionManager::in_memory("/tmp");
2652        let id1 = manager.append_message(AgentMessage::User {
2653            content: ContentValue::String("Hello".to_string()),
2654        });
2655        let _id2 = manager.append_message(AgentMessage::Assistant {
2656            content: vec![],
2657            provider: None,
2658            model_id: None,
2659            usage: None,
2660            stop_reason: None,
2661        });
2662        let _id3 = manager.append_message(AgentMessage::User {
2663            content: ContentValue::String("How are you?".to_string()),
2664        });
2665
2666        // Branch from first message
2667        manager.branch(&id1).unwrap();
2668        assert_eq!(manager.get_leaf_id(), Some(id1.clone()));
2669
2670        // Add new message on branch
2671        let id4 = manager.append_message(AgentMessage::Assistant {
2672            content: vec![],
2673            provider: None,
2674            model_id: None,
2675            usage: None,
2676            stop_reason: None,
2677        });
2678
2679        // Should have 4 entries total (3 original + 1 new branch)
2680        assert_eq!(manager.get_entries().len(), 4);
2681
2682        // Leaf should be the new message
2683        assert_eq!(manager.get_leaf_id(), Some(id4));
2684
2685        // Get tree - 1 root (id1), with 2 children (id2 and id4)
2686        let tree = manager.get_tree(Uuid::nil()).unwrap();
2687        assert_eq!(tree.len(), 1); // One root
2688        assert_eq!(tree[0].children.len(), 2); // id1 has 2 children: id2 and id4
2689    }
2690
2691    #[test]
2692    fn test_session_context() {
2693        let mut manager = SessionManager::in_memory("/tmp");
2694        manager.append_message(AgentMessage::User {
2695            content: ContentValue::String("Hello".to_string()),
2696        });
2697        manager.append_message(AgentMessage::Assistant {
2698            content: vec![AssistantContentBlock::Text {
2699                text: "Hi there!".to_string(),
2700            }],
2701            provider: Some("test".to_string()),
2702            model_id: Some("model".to_string()),
2703            usage: None,
2704            stop_reason: None,
2705        });
2706
2707        let context = manager.build_session_context();
2708        assert_eq!(context.messages.len(), 2);
2709        assert!(context.model.is_some());
2710    }
2711
2712    #[test]
2713    fn test_compaction_entry() {
2714        let mut manager = SessionManager::in_memory("/tmp");
2715        let id1 = manager.append_message(AgentMessage::User {
2716            content: ContentValue::String("First message".to_string()),
2717        });
2718        let _id2 = manager.append_message(AgentMessage::Assistant {
2719            content: vec![],
2720            provider: None,
2721            model_id: None,
2722            usage: None,
2723            stop_reason: None,
2724        });
2725
2726        let id3 = manager.append_compaction("Summarized conversation", &id1, 1000, None, None);
2727        assert!(!id3.is_empty());
2728
2729        let latest = manager.get_latest_compaction_entry();
2730        assert!(latest.is_some());
2731    }
2732
2733    #[test]
2734    fn test_labels() {
2735        let mut manager = SessionManager::in_memory("/tmp");
2736        let id1 = manager.append_message(AgentMessage::User {
2737            content: ContentValue::String("Hello".to_string()),
2738        });
2739
2740        manager.add_label(&id1, "important").unwrap();
2741        assert_eq!(manager.get_label(&id1), Some("important".to_string()));
2742
2743        manager.remove_label(&id1).unwrap();
2744        assert_eq!(manager.get_label(&id1), None);
2745    }
2746
2747    // ========================================================================
2748    // Session tree and branching tests
2749    // ========================================================================
2750
2751    /// Helper: create a user message
2752    fn user_msg(text: &str) -> AgentMessage {
2753        AgentMessage::User {
2754            content: ContentValue::String(text.to_string()),
2755        }
2756    }
2757
2758    /// Helper: create an assistant message
2759    fn assistant_msg(text: &str) -> AgentMessage {
2760        AgentMessage::Assistant {
2761            content: vec![AssistantContentBlock::Text {
2762                text: text.to_string(),
2763            }],
2764            provider: Some("anthropic".to_string()),
2765            model_id: Some("claude-test".to_string()),
2766            usage: None,
2767            stop_reason: None,
2768        }
2769    }
2770
2771    /// Helper: create a bare assistant message (no content/metadata)
2772    fn bare_assistant_msg() -> AgentMessage {
2773        AgentMessage::Assistant {
2774            content: vec![],
2775            provider: None,
2776            model_id: None,
2777            usage: None,
2778            stop_reason: None,
2779        }
2780    }
2781
2782    // ------------------------------------------------------------------------
2783    // append operations integration into tree
2784    // ------------------------------------------------------------------------
2785
2786    #[test]
2787    fn test_append_thinking_level_change_integrates() {
2788        let mut manager = SessionManager::in_memory("/tmp");
2789        let msg_id = manager.append_message(user_msg("hello"));
2790        let thinking_id = manager.append_thinking_level_change("high");
2791        let msg2_id = manager.append_message(assistant_msg("response"));
2792
2793        let entries = manager.get_entries();
2794        assert_eq!(entries.len(), 3);
2795
2796        // Thinking entry should be between the two messages
2797        let thinking_entry = entries.iter().find(|e| e.id == thinking_id).unwrap();
2798        assert_eq!(thinking_entry.parent_id, Some(msg_id));
2799
2800        let msg2 = entries.iter().find(|e| e.id == msg2_id).unwrap();
2801        assert_eq!(msg2.parent_id, Some(thinking_id));
2802    }
2803
2804    #[test]
2805    fn test_append_model_change_integrates() {
2806        let mut manager = SessionManager::in_memory("/tmp");
2807        let msg_id = manager.append_message(user_msg("hello"));
2808        let model_id = manager.append_model_change("openai", "gpt-4");
2809        let msg2_id = manager.append_message(assistant_msg("response"));
2810
2811        let entries = manager.get_entries();
2812        let model_entry = entries.iter().find(|e| e.id == model_id).unwrap();
2813        assert_eq!(model_entry.parent_id, Some(msg_id));
2814
2815        let msg2 = entries.iter().find(|e| e.id == msg2_id).unwrap();
2816        assert_eq!(msg2.parent_id, Some(model_id));
2817    }
2818
2819    #[test]
2820    fn test_append_compaction_integrates_into_tree() {
2821        let mut manager = SessionManager::in_memory("/tmp");
2822        let id1 = manager.append_message(user_msg("1"));
2823        let id2 = manager.append_message(assistant_msg("2"));
2824        let compaction_id = manager.append_compaction("summary", &id1, 1000, None, None);
2825        let id3 = manager.append_message(user_msg("3"));
2826
2827        let entries = manager.get_entries();
2828        let compaction = entries.iter().find(|e| e.id == compaction_id).unwrap();
2829        assert_eq!(compaction.parent_id, Some(id2));
2830
2831        let msg3 = entries.iter().find(|e| e.id == id3).unwrap();
2832        assert_eq!(msg3.parent_id, Some(compaction_id));
2833
2834        // Verify compaction content
2835        if let AgentMessage::CompactionSummary {
2836            summary,
2837            tokens_before,
2838            ..
2839        } = &compaction.message
2840        {
2841            assert_eq!(summary, "summary");
2842            assert_eq!(*tokens_before, 1000);
2843        } else {
2844            panic!("Expected CompactionSummary");
2845        }
2846    }
2847
2848    #[test]
2849    fn test_leaf_pointer_advances() {
2850        let mut manager = SessionManager::in_memory("/tmp");
2851        assert!(manager.get_leaf_id().is_none());
2852
2853        let id1 = manager.append_message(user_msg("1"));
2854        assert_eq!(manager.get_leaf_id(), Some(id1.clone()));
2855
2856        let id2 = manager.append_message(assistant_msg("2"));
2857        assert_eq!(manager.get_leaf_id(), Some(id2.clone()));
2858
2859        let id3 = manager.append_thinking_level_change("high");
2860        assert_eq!(manager.get_leaf_id(), Some(id3));
2861    }
2862
2863    #[test]
2864    fn test_get_entry() {
2865        let mut manager = SessionManager::in_memory("/tmp");
2866        assert!(manager.get_entry("nonexistent").is_none());
2867
2868        let id1 = manager.append_message(user_msg("first"));
2869        let id2 = manager.append_message(assistant_msg("second"));
2870
2871        let entry1 = manager.get_entry(&id1);
2872        assert!(entry1.is_some());
2873        assert!(entry1.unwrap().message.is_user());
2874
2875        let entry2 = manager.get_entry(&id2);
2876        assert!(entry2.is_some());
2877        assert!(entry2.unwrap().message.is_assistant());
2878    }
2879
2880    #[test]
2881    fn test_get_leaf_entry() {
2882        let manager = SessionManager::in_memory("/tmp");
2883        assert!(manager.get_leaf_entry().is_none());
2884
2885        let mut manager = SessionManager::in_memory("/tmp");
2886        manager.append_message(user_msg("1"));
2887        let id2 = manager.append_message(assistant_msg("2"));
2888
2889        let leaf = manager.get_leaf_entry();
2890        assert!(leaf.is_some());
2891        assert_eq!(leaf.unwrap().id, id2);
2892    }
2893
2894    // ------------------------------------------------------------------------
2895    // getBranch / getPath
2896    // ------------------------------------------------------------------------
2897
2898    #[test]
2899    fn test_get_branch_full_path_root_to_leaf() {
2900        let mut manager = SessionManager::in_memory("/tmp");
2901        let id1 = manager.append_message(user_msg("1"));
2902        let id2 = manager.append_message(assistant_msg("2"));
2903        let id3 = manager.append_thinking_level_change("high");
2904        let id4 = manager.append_message(user_msg("3"));
2905
2906        let branch = manager.get_branch(None);
2907        assert_eq!(branch.len(), 4);
2908        assert_eq!(branch[0].id, id1);
2909        assert_eq!(branch[1].id, id2);
2910        assert_eq!(branch[2].id, id3);
2911        assert_eq!(branch[3].id, id4);
2912    }
2913
2914    #[test]
2915    fn test_get_branch_from_specific_entry() {
2916        let mut manager = SessionManager::in_memory("/tmp");
2917        let id1 = manager.append_message(user_msg("1"));
2918        let id2 = manager.append_message(assistant_msg("2"));
2919        manager.append_message(user_msg("3"));
2920        manager.append_message(assistant_msg("4"));
2921
2922        let branch = manager.get_branch(Some(&id2));
2923        assert_eq!(branch.len(), 2);
2924        assert_eq!(branch[0].id, id1);
2925        assert_eq!(branch[1].id, id2);
2926    }
2927
2928    // ------------------------------------------------------------------------
2929    // Multiple branches at same point (3 siblings)
2930    // ------------------------------------------------------------------------
2931
2932    #[test]
2933    fn test_multiple_branches_at_same_point() {
2934        let mut manager = SessionManager::in_memory("/tmp");
2935        manager.append_message(user_msg("root"));
2936        let id2 = manager.append_message(bare_assistant_msg());
2937
2938        // Branch A
2939        manager.branch(&id2).unwrap();
2940        let id_a = manager.append_message(user_msg("branch-A"));
2941
2942        // Branch B
2943        manager.branch(&id2).unwrap();
2944        let id_b = manager.append_message(user_msg("branch-B"));
2945
2946        // Branch C
2947        manager.branch(&id2).unwrap();
2948        let id_c = manager.append_message(user_msg("branch-C"));
2949
2950        let tree = manager.get_tree(Uuid::nil()).unwrap();
2951        let node2 = &tree[0].children[0];
2952        assert_eq!(node2.entry.id, id2);
2953        assert_eq!(node2.children.len(), 3);
2954
2955        let mut branch_ids: Vec<String> =
2956            node2.children.iter().map(|c| c.entry.id.clone()).collect();
2957        branch_ids.sort();
2958        let mut expected = vec![id_a, id_b, id_c];
2959        expected.sort();
2960        assert_eq!(branch_ids, expected);
2961    }
2962
2963    // ------------------------------------------------------------------------
2964    // Deep branching
2965    // ------------------------------------------------------------------------
2966
2967    #[test]
2968    fn test_deep_branching() {
2969        let mut manager = SessionManager::in_memory("/tmp");
2970
2971        // Main path: 1 -> 2 -> 3 -> 4
2972        manager.append_message(user_msg("1"));
2973        let id2 = manager.append_message(bare_assistant_msg());
2974        let id3 = manager.append_message(user_msg("3"));
2975        manager.append_message(bare_assistant_msg());
2976
2977        // Branch from 2: 2 -> 5 -> 6
2978        manager.branch(&id2).unwrap();
2979        let id5 = manager.append_message(user_msg("5"));
2980        manager.append_message(bare_assistant_msg());
2981
2982        // Branch from 5: 5 -> 7
2983        manager.branch(&id5).unwrap();
2984        manager.append_message(user_msg("7"));
2985
2986        let tree = manager.get_tree(Uuid::nil()).unwrap();
2987
2988        // node2 has 2 children: id3 and id5
2989        let node2 = &tree[0].children[0];
2990        assert_eq!(node2.children.len(), 2);
2991
2992        let node5 = node2.children.iter().find(|c| c.entry.id == id5).unwrap();
2993        assert_eq!(node5.children.len(), 2); // id6 and id7
2994
2995        let node3 = node2.children.iter().find(|c| c.entry.id == id3).unwrap();
2996        assert_eq!(node3.children.len(), 1); // id4
2997    }
2998
2999    // ------------------------------------------------------------------------
3000    // branch_with_summary
3001    // ------------------------------------------------------------------------
3002
3003    #[test]
3004    fn test_branch_with_summary_inserts_and_advances() {
3005        let mut manager = SessionManager::in_memory("/tmp");
3006        let id1 = manager.append_message(user_msg("1"));
3007        manager.append_message(bare_assistant_msg());
3008        manager.append_message(user_msg("3"));
3009
3010        let summary_id =
3011            manager.branch_with_summary(Some(&id1), "Summary of abandoned work", None, None);
3012        assert!(!summary_id.is_empty());
3013        assert_eq!(manager.get_leaf_id(), Some(summary_id.clone()));
3014
3015        // Verify branch_summary entry
3016        let entries = manager.get_entries();
3017        let summary_entry = entries.iter().find(|e| e.id == summary_id).unwrap();
3018        assert_eq!(summary_entry.parent_id, Some(id1));
3019
3020        if let AgentMessage::BranchSummary { summary, .. } = &summary_entry.message {
3021            assert_eq!(summary, "Summary of abandoned work");
3022        } else {
3023            panic!("Expected BranchSummary");
3024        }
3025    }
3026
3027    // ------------------------------------------------------------------------
3028    // build_session_context with branches
3029    // ------------------------------------------------------------------------
3030
3031    #[test]
3032    fn test_build_session_context_returns_branch_messages() {
3033        let mut manager = SessionManager::in_memory("/tmp");
3034
3035        // Main: 1 -> 2 -> 3
3036        manager.append_message(user_msg("msg1"));
3037        let id2 = manager.append_message(bare_assistant_msg());
3038        manager.append_message(user_msg("msg3"));
3039
3040        // Branch from 2: 2 -> 4
3041        manager.branch(&id2).unwrap();
3042        manager.append_message(assistant_msg("msg4-branch"));
3043
3044        let ctx = manager.build_session_context();
3045        // Should have msg1, msg2, msg4-branch (NOT msg3)
3046        assert_eq!(ctx.messages.len(), 3);
3047        assert!(ctx.messages[0].is_user());
3048        assert!(ctx.messages[1].is_assistant());
3049        assert!(ctx.messages[2].is_assistant());
3050    }
3051
3052    #[test]
3053    fn test_build_session_context_follows_branch_path() {
3054        // Tree: 1 -> 2 -> 3 (branch A)
3055        //             \-> 4 (branch B)
3056        let mut manager = SessionManager::in_memory("/tmp");
3057        manager.append_message(user_msg("start"));
3058        let id2 = manager.append_message(bare_assistant_msg());
3059        manager.append_message(user_msg("branch A"));
3060
3061        // Switch to branch B
3062        manager.branch(&id2).unwrap();
3063        manager.append_message(user_msg("branch B"));
3064
3065        let ctx = manager.build_session_context();
3066        assert_eq!(ctx.messages.len(), 3);
3067        // Last message should be "branch B"
3068        let last = ctx.messages.last().unwrap();
3069        assert_eq!(last.content(), "branch B");
3070    }
3071
3072    #[test]
3073    fn test_build_session_context_includes_branch_summary() {
3074        let mut manager = SessionManager::in_memory("/tmp");
3075        manager.append_message(user_msg("start"));
3076        let id2 = manager.append_message(bare_assistant_msg());
3077        manager.append_message(user_msg("abandoned path"));
3078
3079        // Branch with summary
3080        manager.branch_with_summary(Some(&id2), "Summary of abandoned work", None, None);
3081        manager.append_message(user_msg("new direction"));
3082
3083        let ctx = manager.build_session_context();
3084        // Should include: start, response, branch_summary, new direction
3085        assert!(ctx.messages.len() >= 3);
3086
3087        // Branch summary should be in messages
3088        let has_summary = ctx.messages.iter().any(|m| {
3089            if let AgentMessage::BranchSummary { summary, .. } = m {
3090                summary == "Summary of abandoned work"
3091            } else {
3092                false
3093            }
3094        });
3095        assert!(has_summary, "Branch summary should be in context messages");
3096    }
3097
3098    #[test]
3099    fn test_build_session_context_with_compaction() {
3100        let mut manager = SessionManager::in_memory("/tmp");
3101
3102        // Build conversation
3103        let id1 = manager.append_message(user_msg("first"));
3104        manager.append_message(assistant_msg("response1"));
3105        manager.append_message(user_msg("second"));
3106        manager.append_message(assistant_msg("response2"));
3107
3108        // Add compaction
3109        manager.append_compaction("Summary of first two turns", &id1, 1000, None, None);
3110
3111        // Continue after compaction
3112        manager.append_message(user_msg("third"));
3113        manager.append_message(assistant_msg("response3"));
3114
3115        let ctx = manager.build_session_context();
3116        // CompactionSummary is NOT included in context messages (only user/assistant/branch_summary)
3117        // but the path from leaf should include all entries
3118        assert!(ctx.messages.len() >= 4); // at minimum: user, assistant, user, assistant from after-compaction path
3119
3120        // Compaction entry should exist in the entries
3121        let compaction_entries = manager.get_compaction_entries();
3122        assert_eq!(compaction_entries.len(), 1);
3123    }
3124
3125    #[test]
3126    fn test_build_session_context_tracks_thinking_level() {
3127        let mut manager = SessionManager::in_memory("/tmp");
3128        manager.append_message(user_msg("hello"));
3129        manager.append_thinking_level_change("high");
3130        manager.append_message(assistant_msg("thinking hard"));
3131
3132        let ctx = manager.build_session_context();
3133        assert_eq!(ctx.thinking_level, "high");
3134    }
3135
3136    // ------------------------------------------------------------------------
3137    // Labels in tree nodes
3138    // ------------------------------------------------------------------------
3139
3140    #[test]
3141    fn test_labels_in_tree_nodes() {
3142        let mut manager = SessionManager::in_memory("/tmp");
3143        let id1 = manager.append_message(user_msg("hello"));
3144        let id2 = manager.append_message(assistant_msg("hi"));
3145
3146        manager.add_label(&id1, "start").unwrap();
3147        manager.add_label(&id2, "response").unwrap();
3148
3149        let tree = manager.get_tree(Uuid::nil()).unwrap();
3150        let node1 = &tree[0];
3151        assert_eq!(node1.label, Some("start".to_string()));
3152
3153        let node2 = &node1.children[0];
3154        assert_eq!(node2.label, Some("response".to_string()));
3155    }
3156
3157    #[test]
3158    fn test_last_label_wins() {
3159        let mut manager = SessionManager::in_memory("/tmp");
3160        let id1 = manager.append_message(user_msg("hello"));
3161
3162        manager.add_label(&id1, "first").unwrap();
3163        manager.add_label(&id1, "second").unwrap();
3164        manager.add_label(&id1, "third").unwrap();
3165
3166        assert_eq!(manager.get_label(&id1), Some("third".to_string()));
3167    }
3168
3169    // ------------------------------------------------------------------------
3170    // branch throws for non-existent
3171    // ------------------------------------------------------------------------
3172
3173    #[test]
3174    fn test_branch_throws_for_nonexistent() {
3175        let mut manager = SessionManager::in_memory("/tmp");
3176        manager.append_message(user_msg("hello"));
3177
3178        let result = manager.branch("nonexistent");
3179        assert!(result.is_err());
3180    }
3181
3182    // ------------------------------------------------------------------------
3183    // Labels not included in buildSessionContext
3184    // ------------------------------------------------------------------------
3185
3186    #[test]
3187    fn test_labels_not_in_session_context() {
3188        let mut manager = SessionManager::in_memory("/tmp");
3189        let msg_id = manager.append_message(user_msg("hello"));
3190        manager.add_label(&msg_id, "checkpoint").unwrap();
3191
3192        let ctx = manager.build_session_context();
3193        // Should only have the user message, not label entries
3194        assert_eq!(ctx.messages.len(), 1);
3195        assert!(ctx.messages[0].is_user());
3196    }
3197
3198    // ------------------------------------------------------------------------
3199    // appendCustomEntry integration
3200    // ------------------------------------------------------------------------
3201
3202    #[test]
3203    fn test_custom_entry_integrates_into_tree() {
3204        let mut manager = SessionManager::in_memory("/tmp");
3205        let msg_id = manager.append_message(user_msg("hello"));
3206        let custom_id =
3207            manager.append_custom_entry("my_data", Some(serde_json::json!({"foo": "bar"})));
3208        let msg2_id = manager.append_message(assistant_msg("response"));
3209
3210        let entries = manager.get_entries();
3211        let custom = entries.iter().find(|e| e.id == custom_id).unwrap();
3212        assert_eq!(custom.parent_id, Some(msg_id));
3213
3214        if let AgentMessage::Custom { custom_type, .. } = &custom.message {
3215            assert_eq!(custom_type, "my_data");
3216        } else {
3217            panic!("Expected Custom message");
3218        }
3219
3220        let msg2 = entries.iter().find(|e| e.id == msg2_id).unwrap();
3221        assert_eq!(msg2.parent_id, Some(custom_id));
3222
3223        // buildSessionContext should work (custom entries skipped in messages)
3224        let ctx = manager.build_session_context();
3225        // Only the 2 real messages; custom entry is not user/assistant/branch_summary
3226        assert_eq!(ctx.messages.len(), 2);
3227    }
3228
3229    // ------------------------------------------------------------------------
3230    // Empty session edge cases
3231    // ------------------------------------------------------------------------
3232
3233    #[test]
3234    fn test_get_branch_empty_session() {
3235        let manager = SessionManager::in_memory("/tmp");
3236        let branch = manager.get_branch(None);
3237        assert!(branch.is_empty());
3238    }
3239
3240    #[test]
3241    fn test_get_tree_empty_session() {
3242        let manager = SessionManager::in_memory("/tmp");
3243        let tree = manager.get_tree(Uuid::nil()).unwrap();
3244        assert!(tree.is_empty());
3245    }
3246
3247    // ------------------------------------------------------------------------
3248    // Complex tree with branches and compaction
3249    // ------------------------------------------------------------------------
3250
3251    #[test]
3252    fn test_complex_tree_with_branches_and_compaction() {
3253        let mut manager = SessionManager::in_memory("/tmp");
3254
3255        // Main path: 1 -> 2 -> 3 -> 4 -> compaction(5) -> 6 -> 7
3256        manager.append_message(user_msg("start"));
3257        manager.append_message(assistant_msg("r1"));
3258        let id3 = manager.append_message(user_msg("q2"));
3259        manager.append_message(assistant_msg("r2"));
3260        manager.append_compaction("Compacted history", &id3, 1000, None, None);
3261        manager.append_message(user_msg("q3"));
3262        manager.append_message(assistant_msg("r3"));
3263
3264        // Abandoned branch from 3
3265        manager.branch(&id3).unwrap();
3266        manager.append_message(user_msg("wrong path"));
3267        manager.append_message(assistant_msg("wrong response"));
3268
3269        // Branch summary resuming from 3
3270        manager.branch_with_summary(Some(&id3), "Tried wrong approach", None, None);
3271        manager.append_message(user_msg("better approach"));
3272
3273        let tree = manager.get_tree(Uuid::nil()).unwrap();
3274        // Root node
3275        assert_eq!(tree.len(), 1);
3276
3277        // Walk tree to verify structure
3278        let root = &tree[0];
3279        assert!(root.entry.message.is_user());
3280    }
3281
3282    // ------------------------------------------------------------------------
3283    // get_latest_compaction_entry returns the most recent
3284    // ------------------------------------------------------------------------
3285
3286    #[test]
3287    fn test_multiple_compactions_returns_latest() {
3288        let mut manager = SessionManager::in_memory("/tmp");
3289        let id1 = manager.append_message(user_msg("a"));
3290        manager.append_message(bare_assistant_msg());
3291        manager.append_compaction("First summary", &id1, 1000, None, None);
3292        manager.append_message(user_msg("c"));
3293        manager.append_message(bare_assistant_msg());
3294        manager.append_compaction("Second summary", &id1, 2000, None, None);
3295
3296        // get_compaction_entries returns all compaction entries
3297        let compactions = manager.get_compaction_entries();
3298        assert_eq!(compactions.len(), 2);
3299
3300        // At least one should exist with the second summary
3301        let latest = manager.get_latest_compaction_entry();
3302        assert!(latest.is_some());
3303    }
3304
3305    // ------------------------------------------------------------------------
3306    // get_compaction_entries returns all
3307    // ------------------------------------------------------------------------
3308
3309    #[test]
3310    fn test_get_all_compaction_entries() {
3311        let mut manager = SessionManager::in_memory("/tmp");
3312        let id1 = manager.append_message(user_msg("a"));
3313        manager.append_message(bare_assistant_msg());
3314        manager.append_compaction("First", &id1, 1000, None, None);
3315        manager.append_message(user_msg("b"));
3316        manager.append_message(bare_assistant_msg());
3317        manager.append_compaction("Second", &id1, 2000, None, None);
3318
3319        let compactions = manager.get_compaction_entries();
3320        assert_eq!(compactions.len(), 2);
3321    }
3322}