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    /// Validate a session ID format.
1164    ///
1165    /// Checks that the session_id conforms to the expected UUID format.
1166    /// Returns `true` if valid.
1167    pub fn validate_session_id(id: &str) -> bool {
1168        Uuid::parse_str(id).is_ok()
1169    }
1170
1171    /// Returns `true` if this session is in read-only mode.
1172    ///
1173    /// A session is read-only when:
1174    /// - It was opened without write permissions
1175    /// - Its underlying file is set to read-only on the filesystem
1176    ///
1177    /// Read-only sessions reject any append/branch operations.
1178    pub fn is_readonly(&self) -> bool {
1179        if !self.persist {
1180            // In-memory sessions start mutable, but can be marked readonly
1181            return false;
1182        }
1183        if let Some(ref file) = self.session_file {
1184            let path = Path::new(file);
1185            if path.exists() {
1186                if let Ok(metadata) = fs::metadata(path) {
1187                    #[cfg(unix)]
1188                    {
1189                        use std::os::unix::fs::PermissionsExt;
1190                        let perm = metadata.permissions().mode();
1191                        // 0o200 = write bit for owner removed
1192                        return perm & 0o200 == 0;
1193                    }
1194                    #[cfg(not(unix))]
1195                    {
1196                        let _ = metadata;
1197                        return false;
1198                    }
1199                }
1200            }
1201        }
1202        false
1203    }
1204
1205    /// Check if appending to this session is allowed.
1206    ///
1207    /// Combination of `!is_readonly()` + in-memory or writable backing file.
1208    pub fn can_append(&self) -> bool {
1209        !self.is_readonly() && self.persist
1210    }
1211
1212    /// Get the number of agent messages that have already been persisted.
1213    pub fn persisted_count(&self) -> usize {
1214        *self.persisted_count.read()
1215    }
1216
1217    /// Set the number of agent messages that have been persisted.
1218    pub fn set_persisted_count(&self, count: usize) {
1219        *self.persisted_count.write() = count;
1220    }
1221
1222    /// Get working directory
1223    pub fn get_cwd(&self) -> String {
1224        self.cwd.clone()
1225    }
1226
1227    /// Get session directory
1228    pub fn get_session_dir(&self) -> String {
1229        self.session_dir.clone()
1230    }
1231
1232    /// Get session ID
1233    pub fn get_session_id(&self) -> String {
1234        self.session_id.clone()
1235    }
1236
1237    /// Get session file path
1238    pub fn get_session_file(&self) -> Option<String> {
1239        self.session_file.clone()
1240    }
1241
1242    /// Remove the session file from disk if the session has no real conversation
1243    /// (i.e., no user message was ever persisted).
1244    /// Called before switching to a new session or quitting.
1245    pub fn cleanup_if_empty(&self) {
1246        if !self.persist {
1247            return;
1248        }
1249        let Some(file) = &self.session_file else {
1250            return;
1251        };
1252
1253        let has_user = self.file_entries.read().iter().any(|e| {
1254            matches!(
1255                e,
1256                FileEntry::Entry(SessionEntryEnum::Message(m)) if m.message.is_user()
1257            )
1258        });
1259
1260        if !has_user {
1261            let path = Path::new(file);
1262            if path.exists() {
1263                if let Err(e) = fs::remove_file(path) {
1264                    tracing::warn!("Failed to remove empty session file {}: {}", file, e);
1265                } else {
1266                    tracing::debug!("Removed empty session file: {}", file);
1267                }
1268            }
1269        }
1270    }
1271
1272    fn _persist(&mut self, entry: &SessionEntry) {
1273        if !self.persist {
1274            return;
1275        }
1276        let Some(file) = &self.session_file else {
1277            return;
1278        };
1279
1280        // Only persist once we have at least one message entry.
1281        // This avoids writing header-only stubs to disk.
1282        let has_message = self
1283            .file_entries
1284            .read()
1285            .iter()
1286            .any(|e| matches!(e, FileEntry::Entry(SessionEntryEnum::Message(_))));
1287
1288        if !has_message {
1289            self.flushed = false;
1290            return;
1291        }
1292
1293        let mut handle = match fs::OpenOptions::new().create(true).append(true).open(file) {
1294            Ok(h) => h,
1295            Err(e) => {
1296                tracing::warn!("Failed to open session file for append {}: {}", file, e);
1297                return;
1298            }
1299        };
1300
1301        if !self.flushed {
1302            for e in self.file_entries.read().iter() {
1303                if let Ok(line) = serde_json::to_string(e) {
1304                    let _ = writeln!(&mut handle, "{}", line);
1305                }
1306            }
1307            self.flushed = true;
1308        } else {
1309            // Convert SessionEntry back to FileEntry for writing
1310            let file_entry = convert_from_session_entry(entry);
1311            if let Ok(line) = serde_json::to_string(&file_entry) {
1312                let _ = writeln!(&mut handle, "{}", line);
1313            }
1314        }
1315    }
1316
1317    // LOCK ORDERING CONVENTION (must be followed to prevent deadlock):
1318    // 1. file_entries  2. by_id  3. labels_by_id  4. label_timestamps_by_id  5. leaf_id
1319    // Always acquire locks in this order. Never acquire an earlier lock after a later one.
1320    fn _append_entry(&mut self, entry: SessionEntry) {
1321        let file_entry = convert_from_session_entry(&entry);
1322        self.file_entries.write().push(FileEntry::Entry(file_entry));
1323        self.by_id.write().insert(entry.id.clone(), entry.clone());
1324        *self.leaf_id.write() = Some(entry.id.clone());
1325        self._persist(&entry);
1326    }
1327
1328    /// Append a message as child of current leaf
1329    pub fn append_message(&mut self, message: AgentMessage) -> String {
1330        let leaf = self.leaf_id.read().clone();
1331        let id = Uuid::new_v4().to_string();
1332        let entry = SessionEntry {
1333            id: id.clone(),
1334            parent_id: leaf,
1335            timestamp: Utc::now().timestamp_millis(),
1336            message,
1337        };
1338        self._append_entry(entry);
1339        id
1340    }
1341
1342    /// Append a thinking level change
1343    pub fn append_thinking_level_change(&mut self, thinking_level: &str) -> String {
1344        let leaf = self.leaf_id.read().clone();
1345        let id = Uuid::new_v4().to_string();
1346        let entry = SessionEntry {
1347            id: id.clone(),
1348            parent_id: leaf,
1349            timestamp: Utc::now().timestamp_millis(),
1350            message: AgentMessage::Custom {
1351                custom_type: "thinking_level_change".to_string(),
1352                content: ContentValue::String(thinking_level.to_string()),
1353                display: false,
1354                details: None,
1355                timestamp: Utc::now().timestamp_millis(),
1356            },
1357        };
1358        self._append_entry(entry);
1359        id
1360    }
1361
1362    /// Append a model change
1363    pub fn append_model_change(&mut self, provider: &str, model_id: &str) -> String {
1364        let leaf = self.leaf_id.read().clone();
1365        let id = Uuid::new_v4().to_string();
1366        let entry = SessionEntry {
1367            id: id.clone(),
1368            parent_id: leaf,
1369            timestamp: Utc::now().timestamp_millis(),
1370            message: AgentMessage::Custom {
1371                custom_type: "model_change".to_string(),
1372                content: ContentValue::String(format!("{}:{}", provider, model_id)),
1373                display: false,
1374                details: None,
1375                timestamp: Utc::now().timestamp_millis(),
1376            },
1377        };
1378        self._append_entry(entry);
1379        id
1380    }
1381
1382    /// Append a compaction summary
1383    pub fn append_compaction(
1384        &mut self,
1385        summary: &str,
1386        _first_kept_entry_id: &str,
1387        tokens_before: i64,
1388        _details: Option<serde_json::Value>,
1389        _from_hook: Option<bool>,
1390    ) -> String {
1391        let leaf = self.leaf_id.read().clone();
1392        let id = Uuid::new_v4().to_string();
1393        let entry = SessionEntry {
1394            id: id.clone(),
1395            parent_id: leaf,
1396            timestamp: Utc::now().timestamp_millis(),
1397            message: AgentMessage::CompactionSummary {
1398                summary: summary.to_string(),
1399                tokens_before,
1400                timestamp: Utc::now().timestamp_millis(),
1401            },
1402        };
1403        self._append_entry(entry);
1404        id
1405    }
1406
1407    /// Append a custom entry (for extensions)
1408    pub fn append_custom_entry(
1409        &mut self,
1410        custom_type: &str,
1411        data: Option<serde_json::Value>,
1412    ) -> String {
1413        let leaf = self.leaf_id.read().clone();
1414        let id = Uuid::new_v4().to_string();
1415        let entry = SessionEntry {
1416            id: id.clone(),
1417            parent_id: leaf,
1418            timestamp: Utc::now().timestamp_millis(),
1419            message: AgentMessage::Custom {
1420                custom_type: custom_type.to_string(),
1421                content: data
1422                    .as_ref()
1423                    .map(|d| ContentValue::String(d.to_string()))
1424                    .unwrap_or(ContentValue::String(String::new())),
1425                display: false,
1426                details: data.clone(),
1427                timestamp: Utc::now().timestamp_millis(),
1428            },
1429        };
1430        self._append_entry(entry);
1431        id
1432    }
1433
1434    /// Append a session info entry (e.g., display name)
1435    pub fn append_session_info(&mut self, name: &str) -> String {
1436        let leaf = self.leaf_id.read().clone();
1437        let id = Uuid::new_v4().to_string();
1438        let entry = SessionEntry {
1439            id: id.clone(),
1440            parent_id: leaf,
1441            timestamp: Utc::now().timestamp_millis(),
1442            message: AgentMessage::Custom {
1443                custom_type: "session_info".to_string(),
1444                content: ContentValue::String(name.trim().to_string()),
1445                display: false,
1446                details: None,
1447                timestamp: Utc::now().timestamp_millis(),
1448            },
1449        };
1450        self._append_entry(entry);
1451        id
1452    }
1453
1454    /// Get the current session name from the latest session_info entry
1455    pub fn get_session_name(&self) -> Option<String> {
1456        let entries = self.get_entries();
1457        for entry in entries.iter().rev() {
1458            if let AgentMessage::Custom {
1459                custom_type,
1460                content,
1461                ..
1462            } = &entry.message
1463            {
1464                if custom_type == "session_info" {
1465                    return Some(content.as_str().trim().to_string()).filter(|s| !s.is_empty());
1466                }
1467            }
1468        }
1469        None
1470    }
1471
1472    /// Append a custom message entry (for extensions) that participates in LLM context
1473    pub fn append_custom_message_entry(
1474        &mut self,
1475        custom_type: &str,
1476        content: ContentValue,
1477        display: bool,
1478        details: Option<serde_json::Value>,
1479    ) -> String {
1480        let leaf = self.leaf_id.read().clone();
1481        let id = Uuid::new_v4().to_string();
1482        let entry = SessionEntry {
1483            id: id.clone(),
1484            parent_id: leaf,
1485            timestamp: Utc::now().timestamp_millis(),
1486            message: AgentMessage::Custom {
1487                custom_type: custom_type.to_string(),
1488                content,
1489                display,
1490                details,
1491                timestamp: Utc::now().timestamp_millis(),
1492            },
1493        };
1494        self._append_entry(entry);
1495        id
1496    }
1497
1498    // =========================================================================
1499    // Tree Traversal
1500    // =========================================================================
1501
1502    /// Get the current leaf ID
1503    pub fn get_leaf_id(&self) -> Option<String> {
1504        self.leaf_id.read().clone()
1505    }
1506
1507    /// Get the current leaf entry
1508    pub fn get_leaf_entry(&self) -> Option<SessionEntry> {
1509        self.leaf_id
1510            .read()
1511            .as_ref()
1512            .and_then(|id| self.by_id.read().get(id).cloned())
1513    }
1514
1515    /// Get an entry by ID
1516    pub fn get_entry(&self, id: &str) -> Option<SessionEntry> {
1517        self.by_id.read().get(id).cloned()
1518    }
1519
1520    /// Get all direct children of an entry
1521    pub fn get_children(&self, parent_id: &str) -> Vec<SessionEntry> {
1522        self.by_id
1523            .read()
1524            .values()
1525            .filter(|e| e.parent_id.as_deref() == Some(parent_id))
1526            .cloned()
1527            .collect()
1528    }
1529
1530    /// Get the parent of an entry
1531    pub fn get_parent(&self, id: &str) -> Option<SessionEntry> {
1532        self.by_id
1533            .read()
1534            .get(id)
1535            .and_then(|e| e.parent_id.as_deref())
1536            .and_then(|pid| self.by_id.read().get(pid).cloned())
1537    }
1538
1539    /// Get the label for an entry
1540    pub fn get_label(&self, id: &str) -> Option<String> {
1541        self.labels_by_id.read().get(id).cloned()
1542    }
1543
1544    /// Set or clear a label on an entry
1545    pub fn append_label_change(
1546        &mut self,
1547        target_id: &str,
1548        label: Option<&str>,
1549    ) -> Result<String, String> {
1550        if !self.by_id.read().contains_key(target_id) {
1551            return Err(format!("Entry {} not found", target_id));
1552        }
1553
1554        let leaf = self.leaf_id.read().clone();
1555        let id = Uuid::new_v4().to_string();
1556        let entry = SessionEntry {
1557            id: id.clone(),
1558            parent_id: leaf,
1559            timestamp: Utc::now().timestamp_millis(),
1560            message: AgentMessage::Custom {
1561                custom_type: "label".to_string(),
1562                content: ContentValue::String(label.unwrap_or("").to_string()),
1563                display: false,
1564                details: Some(serde_json::json!({ "targetId": target_id })),
1565                timestamp: Utc::now().timestamp_millis(),
1566            },
1567        };
1568
1569        self._append_entry(entry);
1570
1571        if let Some(l) = label {
1572            self.labels_by_id
1573                .write()
1574                .insert(target_id.to_string(), l.to_string());
1575            self.label_timestamps_by_id
1576                .write()
1577                .insert(target_id.to_string(), Utc::now().to_rfc3339());
1578        } else {
1579            self.labels_by_id.write().remove(target_id);
1580            self.label_timestamps_by_id.write().remove(target_id);
1581        }
1582
1583        Ok(id)
1584    }
1585
1586    /// Walk from entry to root, returning all entries in path order
1587    pub fn get_branch(&self, from_id: Option<&str>) -> Vec<SessionEntry> {
1588        let mut path = Vec::new();
1589        let leaf_fallback = self.leaf_id.read().clone();
1590        let start_id = from_id.or(leaf_fallback.as_deref());
1591        let Some(start_id) = start_id else {
1592            return path;
1593        };
1594
1595        // Acquire the lock once and reuse it for the entire traversal
1596        let by_id = self.by_id.read();
1597        let mut current = by_id.get(start_id).cloned();
1598        while let Some(entry) = current {
1599            path.insert(0, entry.clone());
1600            current = entry
1601                .parent_id
1602                .as_ref()
1603                .and_then(|pid| by_id.get(pid).cloned());
1604        }
1605        path
1606    }
1607
1608    /// Get path to root for a given entry
1609    pub fn get_path_to_root(&self, from_id: &str) -> Vec<SessionEntry> {
1610        self.get_branch(Some(from_id))
1611    }
1612
1613    /// Get ancestry (same as path to root)
1614    pub fn get_ancestry(&self, from_id: &str) -> Vec<SessionEntry> {
1615        self.get_branch(Some(from_id))
1616    }
1617
1618    /// Get depth of an entry
1619    pub fn get_depth(&self, id: &str) -> i64 {
1620        let mut depth = 0;
1621        let mut current = self.by_id.read().get(id).cloned();
1622        while let Some(entry) = current {
1623            depth += 1;
1624            current = entry
1625                .parent_id
1626                .as_ref()
1627                .and_then(|pid| self.by_id.read().get(pid).cloned());
1628        }
1629        depth - 1 // Root has depth 0
1630    }
1631
1632    /// Build the session context (what gets sent to the LLM)
1633    pub fn build_session_context(&self) -> SessionContext {
1634        let entries = self.get_entries();
1635        let leaf_id = self.leaf_id.read().clone();
1636        build_session_context_internal(&entries, leaf_id, None)
1637    }
1638
1639    /// Get session header
1640    pub fn get_header(&self) -> Option<SessionHeader> {
1641        self.file_entries.read().iter().find_map(|e| match e {
1642            FileEntry::Header(h) => Some(h.clone()),
1643            _ => None,
1644        })
1645    }
1646
1647    /// Get all session entries (excludes header)
1648    pub fn get_entries(&self) -> Vec<SessionEntry> {
1649        self.by_id.read().values().cloned().collect()
1650    }
1651
1652    /// Get the session as a tree structure
1653    /// If id is provided, returns tree for that session (backward compat)
1654    pub fn get_tree(&self, _id: Uuid) -> anyhow::Result<Vec<SessionTreeNode>> {
1655        let entries = self.get_entries();
1656        let labels: HashMap<String, String> = self.labels_by_id.read().clone();
1657        let label_timestamps: HashMap<String, String> = self.label_timestamps_by_id.read().clone();
1658
1659        let mut adj: HashMap<String, Vec<String>> = HashMap::new();
1660        let mut root_ids: Vec<String> = Vec::new();
1661
1662        // Build adjacency list
1663        for entry in &entries {
1664            adj.insert(entry.id.clone(), Vec::new());
1665        }
1666
1667        // Determine parent-child relationships
1668        for entry in &entries {
1669            let is_root = match entry.parent_id.as_deref() {
1670                Some(pid) if pid != entry.id => !adj.contains_key(pid),
1671                _ => true,
1672            };
1673            if is_root {
1674                root_ids.push(entry.id.clone());
1675            } else if let Some(ref pid) = entry.parent_id {
1676                if let Some(children) = adj.get_mut(pid.as_str()) {
1677                    children.push(entry.id.clone());
1678                } else {
1679                    root_ids.push(entry.id.clone());
1680                }
1681            }
1682        }
1683
1684        // Build entries map
1685        let entries_map: HashMap<String, SessionEntry> =
1686            entries.into_iter().map(|e| (e.id.clone(), e)).collect();
1687
1688        // Recursively build tree nodes
1689        fn build(
1690            id: &str,
1691            adj: &HashMap<String, Vec<String>>,
1692            entries_map: &HashMap<String, SessionEntry>,
1693            labels: &HashMap<String, String>,
1694            label_timestamps: &HashMap<String, String>,
1695        ) -> anyhow::Result<SessionTreeNode> {
1696            let entry = entries_map
1697                .get(id)
1698                .ok_or_else(|| anyhow::anyhow!("Corrupted session: entry {} not found", id))?
1699                .clone();
1700            let child_ids = adj.get(id).cloned().unwrap_or_default();
1701            let children: Vec<SessionTreeNode> = child_ids
1702                .iter()
1703                .map(|cid| build(cid, adj, entries_map, labels, label_timestamps))
1704                .collect::<Result<Vec<_>, _>>()?;
1705            Ok(SessionTreeNode {
1706                entry,
1707                children,
1708                label: labels.get(id).cloned(),
1709                label_timestamp: label_timestamps.get(id).cloned(),
1710            })
1711        }
1712
1713        let mut roots = root_ids
1714            .into_iter()
1715            .map(|rid| build(&rid, &adj, &entries_map, &labels, &label_timestamps))
1716            .collect::<anyhow::Result<Vec<_>>>()?;
1717
1718        sort_tree_by_timestamp(&mut roots);
1719        Ok(roots)
1720    }
1721
1722    // =========================================================================
1723    // Branching
1724    // =========================================================================
1725
1726    /// Start a new branch from an earlier entry
1727    pub fn branch(&mut self, branch_from_id: &str) -> Result<(), String> {
1728        if !self.by_id.read().contains_key(branch_from_id) {
1729            return Err(format!("Entry {} not found", branch_from_id));
1730        }
1731        *self.leaf_id.write() = Some(branch_from_id.to_string());
1732        Ok(())
1733    }
1734
1735    /// Reset the leaf pointer to null (before any entries)
1736    pub fn reset_leaf(&mut self) {
1737        *self.leaf_id.write() = None;
1738    }
1739
1740    /// Start a new branch with a summary of the abandoned path
1741    pub fn branch_with_summary(
1742        &mut self,
1743        branch_from_id: Option<&str>,
1744        summary: &str,
1745        _details: Option<serde_json::Value>,
1746        _from_hook: Option<bool>,
1747    ) -> String {
1748        if let Some(id) = branch_from_id {
1749            if !self.by_id.read().contains_key(id) {
1750                return String::new();
1751            }
1752        }
1753
1754        *self.leaf_id.write() = branch_from_id.map(|s| s.to_string());
1755
1756        let id = Uuid::new_v4().to_string();
1757        let entry = SessionEntry {
1758            id: id.clone(),
1759            parent_id: branch_from_id.map(|s| s.to_string()),
1760            timestamp: Utc::now().timestamp_millis(),
1761            message: AgentMessage::BranchSummary {
1762                summary: summary.to_string(),
1763                from_id: branch_from_id.unwrap_or("root").to_string(),
1764                timestamp: Utc::now().timestamp_millis(),
1765            },
1766        };
1767
1768        self._append_entry(entry);
1769        id
1770    }
1771
1772    /// Add a label to the session
1773    pub fn add_label(&mut self, target_id: &str, label: &str) -> Result<String, String> {
1774        self.append_label_change(target_id, Some(label))
1775    }
1776
1777    /// Remove a label from an entry
1778    pub fn remove_label(&mut self, target_id: &str) -> Result<String, String> {
1779        self.append_label_change(target_id, None)
1780    }
1781
1782    // =========================================================================
1783    // Compaction Support
1784    // =========================================================================
1785
1786    /// Get the latest compaction entry
1787    pub fn get_latest_compaction_entry(&self) -> Option<SessionEntry> {
1788        let entries = self.get_entries();
1789        for entry in entries.iter().rev() {
1790            if let AgentMessage::CompactionSummary { .. } = &entry.message {
1791                return Some(entry.clone());
1792            }
1793        }
1794        None
1795    }
1796
1797    /// Get all compaction entries
1798    pub fn get_compaction_entries(&self) -> Vec<SessionEntry> {
1799        self.get_entries()
1800            .iter()
1801            .filter(|e| matches!(&e.message, AgentMessage::CompactionSummary { .. }))
1802            .cloned()
1803            .collect()
1804    }
1805
1806    // =========================================================================
1807    // Session Statistics
1808    // =========================================================================
1809
1810    /// Get session statistics
1811    pub fn get_session_stats(&self) -> SessionStats {
1812        let entries = self.get_entries();
1813        let mut message_count = 0i64;
1814        let mut user_message_count = 0i64;
1815        let mut assistant_message_count = 0i64;
1816        let mut total_chars = 0i64;
1817        let mut total_tokens_estimate = 0i64;
1818
1819        for entry in &entries {
1820            if let AgentMessage::User { .. } = &entry.message {
1821                user_message_count += 1;
1822            }
1823            if let AgentMessage::Assistant { .. } = &entry.message {
1824                assistant_message_count += 1;
1825            }
1826            if entry.message.is_user() || entry.message.is_assistant() {
1827                message_count += 1;
1828                // Estimate tokens from message
1829                let content = entry.content();
1830                let chars = content.len() as i64;
1831                total_chars += chars;
1832                total_tokens_estimate += (chars as f64 / 4.0).ceil() as i64;
1833            }
1834        }
1835
1836        SessionStats {
1837            message_count,
1838            user_message_count,
1839            assistant_message_count,
1840            total_chars,
1841            estimated_tokens: total_tokens_estimate,
1842        }
1843    }
1844
1845    // =========================================================================
1846    // Static Methods
1847    // =========================================================================
1848
1849    /// List all sessions for a directory
1850    pub async fn list(cwd: &str, session_dir: Option<&str>) -> Result<Vec<SessionInfo>> {
1851        let dir = session_dir
1852            .map(|s| s.to_string())
1853            .unwrap_or_else(|| get_default_session_dir(cwd));
1854        list_sessions_from_dir(&dir).await
1855    }
1856
1857    /// List all sessions across all project directories
1858    pub async fn list_all() -> Result<Vec<SessionInfo>> {
1859        let sessions_dir = get_sessions_dir();
1860
1861        if !Path::new(&sessions_dir).exists() {
1862            return Ok(Vec::new());
1863        }
1864
1865        let mut all_sessions = Vec::new();
1866        let entries = fs::read_dir(&sessions_dir)?;
1867
1868        for entry in entries {
1869            let entry = entry?;
1870            let path = entry.path();
1871            if path.is_dir() {
1872                if let Ok(sessions) = list_sessions_from_dir(&path.to_string_lossy()).await {
1873                    all_sessions.extend(sessions);
1874                }
1875            }
1876        }
1877
1878        all_sessions.sort_by_key(|b| std::cmp::Reverse(b.modified));
1879        Ok(all_sessions)
1880    }
1881
1882    /// Fork a session from another project directory into the current project
1883    pub fn fork_from(
1884        source_path: &str,
1885        target_cwd: &str,
1886        session_dir: Option<&str>,
1887    ) -> Result<Self, String> {
1888        let source_entries = load_entries_from_file(source_path);
1889        if source_entries.is_empty() {
1890            return Err(format!(
1891                "Cannot fork: source session file is empty or invalid: {}",
1892                source_path
1893            ));
1894        }
1895
1896        let source_header = source_entries.iter().find_map(|e| match e {
1897            FileEntry::Header(h) => Some(h),
1898            _ => None,
1899        });
1900        if source_header.is_none() {
1901            return Err(format!(
1902                "Cannot fork: source session has no header: {}",
1903                source_path
1904            ));
1905        }
1906
1907        let dir = session_dir
1908            .map(|s| s.to_string())
1909            .unwrap_or_else(|| get_default_session_dir(target_cwd));
1910
1911        if !Path::new(&dir).exists() {
1912            let _ = fs::create_dir_all(&dir);
1913        }
1914
1915        let new_session_id = Uuid::new_v4().to_string();
1916        let timestamp = Utc::now().to_rfc3339();
1917        let file_timestamp = timestamp.replace([':', '.', 'T', '-', ':', '+'], "-");
1918        let short_id = &new_session_id[..8];
1919        let new_session_file = format!("{}/{}_{}.jsonl", dir, file_timestamp, short_id);
1920
1921        // Write new header pointing to source as parent
1922        let new_header = SessionHeader {
1923            entry_type: "session".to_string(),
1924            version: Some(CURRENT_SESSION_VERSION),
1925            id: new_session_id.clone(),
1926            timestamp: timestamp.clone(),
1927            cwd: target_cwd.to_string(),
1928            parent_session: Some(source_path.to_string()),
1929        };
1930
1931        let mut handle = fs::OpenOptions::new()
1932            .create(true)
1933            .truncate(true)
1934            .write(true)
1935            .open(&new_session_file)
1936            .map_err(|e| e.to_string())?;
1937        writeln!(
1938            &mut handle,
1939            "{}",
1940            serde_json::to_string(&new_header).expect("session header serializable")
1941        )
1942        .map_err(|e| e.to_string())?;
1943
1944        // Copy all non-header entries from source
1945        for file_entry in &source_entries {
1946            if let FileEntry::Entry(_) = file_entry {
1947                writeln!(
1948                    &mut handle,
1949                    "{}",
1950                    serde_json::to_string(file_entry).expect("session entry serializable")
1951                )
1952                .map_err(|e| e.to_string())?;
1953            }
1954        }
1955
1956        Ok(Self::open(&new_session_file, Some(&dir), Some(target_cwd)))
1957    }
1958
1959    /// Delete a session
1960    pub fn delete_session(path: &str) -> Result<()> {
1961        fs::remove_file(path).context("Failed to delete session file")?;
1962        Ok(())
1963    }
1964
1965    /// Rename a session (set its display name)
1966    pub fn rename_session(&mut self, name: &str) -> String {
1967        self.append_session_info(name)
1968    }
1969
1970    // =========================================================================
1971    // Backward Compatibility Methods
1972    // =========================================================================
1973
1974    /// Create a new SessionManager (async for backward compatibility)
1975    pub async fn new() -> Result<Self> {
1976        Self::new_async().await
1977    }
1978
1979    /// Create a new SessionManager (async for backward compatibility)
1980    pub async fn new_async() -> Result<Self> {
1981        let home = dirs::home_dir().context("Cannot find home directory")?;
1982        let base_dir = home.join(".oxi");
1983        let sessions_dir = base_dir.join("sessions");
1984        tokio::fs::create_dir_all(&sessions_dir).await?;
1985        let cwd = std::env::current_dir()
1986            .unwrap_or_else(|_| PathBuf::from("."))
1987            .to_string_lossy()
1988            .to_string();
1989        Ok(Self::in_memory(&cwd))
1990    }
1991
1992    /// Get the session file path for a given session ID
1993    pub fn session_path(&self, id: &Uuid) -> PathBuf {
1994        if let Some(file) = &self.session_file {
1995            PathBuf::from(file)
1996        } else {
1997            PathBuf::from(format!("{}/{}.jsonl", self.session_dir, id))
1998        }
1999    }
2000
2001    /// List all sessions (backward compat)
2002    pub async fn list_sessions(&self) -> Result<Vec<SessionMeta>> {
2003        // Simple implementation: scan the session dir for jsonl files
2004        let mut metas = Vec::new();
2005        let session_dir = Path::new(&self.session_dir);
2006        if !session_dir.exists() {
2007            return Ok(metas);
2008        }
2009        let entries = fs::read_dir(session_dir)?;
2010        for entry in entries {
2011            let entry = entry?;
2012            let path = entry.path();
2013            if path.extension().map(|e| e == "jsonl").unwrap_or(false) {
2014                let file_name = path
2015                    .file_stem()
2016                    .unwrap_or_else(|| std::ffi::OsStr::new(""))
2017                    .to_string_lossy()
2018                    .to_string();
2019                // Try to extract uuid from filename
2020                if let Some(uuid_part) = file_name.split('_').next_back() {
2021                    if let Ok(uuid) = Uuid::parse_str(uuid_part) {
2022                        let mtime = entry.metadata().ok().and_then(|m| m.modified().ok());
2023                        let now_ts = Utc::now().timestamp_millis();
2024                        metas.push(SessionMeta {
2025                            id: uuid,
2026                            parent_id: None,
2027                            root_id: None,
2028                            branch_point: None,
2029                            created_at: now_ts,
2030                            updated_at: mtime
2031                                .map(|t| {
2032                                    let dt: DateTime<Utc> = DateTime::from(t);
2033                                    dt.timestamp_millis()
2034                                })
2035                                .unwrap_or(now_ts),
2036                            name: None,
2037                        });
2038                    }
2039                }
2040            }
2041        }
2042        metas.sort_by_key(|b| std::cmp::Reverse(b.updated_at));
2043        Ok(metas)
2044    }
2045
2046    /// Save entries (backward compat)
2047    pub async fn save(&self, _id: Uuid, _entries: &[SessionEntry]) -> Result<()> {
2048        self._rewrite_file();
2049        Ok(())
2050    }
2051
2052    /// Load entries (backward compat)
2053    pub async fn load(&self, _id: Uuid) -> Result<Vec<SessionEntry>> {
2054        Ok(self.get_entries())
2055    }
2056
2057    /// Delete a session (backward compat)
2058    pub async fn delete(&self, id: Uuid) -> Result<()> {
2059        let path = self.session_path(&id);
2060        if path.exists() {
2061            fs::remove_file(path).context("Failed to delete session file")?;
2062        }
2063        Ok(())
2064    }
2065
2066    /// Create a branch from an existing session at a given entry
2067    pub async fn branch_from(
2068        &self,
2069        parent_id: Uuid,
2070        entry_id: Uuid,
2071    ) -> Result<(Uuid, Vec<SessionEntry>)> {
2072        let _entry_id_str = entry_id.to_string();
2073        let _parent_id_str = parent_id.to_string();
2074
2075        // Get entries up to the branch point
2076        let _entries = self.get_entries();
2077        let path = self.get_branch(Some(&entry_id.to_string()));
2078
2079        let new_id = Uuid::new_v4();
2080        let new_entries: Vec<SessionEntry> = path
2081            .into_iter()
2082            .map(|e| {
2083                let mut new_entry = e.clone();
2084                new_entry.id = Uuid::new_v4().to_string();
2085                new_entry
2086            })
2087            .collect();
2088
2089        // Update the last entry to have parent reference
2090        // (simplified version of the original branch_from)
2091        Ok((new_id, new_entries))
2092    }
2093
2094    /// Get branch info for a session
2095    pub async fn get_branch_info(&self, _id: Uuid) -> Result<Option<BranchInfo>> {
2096        // Simplified implementation
2097        Ok(None)
2098    }
2099
2100    /// Get tree for a specific session (backward compat)
2101    pub async fn get_tree_async(&self, _id: Uuid) -> Result<Vec<SessionTreeNode>> {
2102        self.get_tree(Uuid::nil())
2103    }
2104
2105    /// Save metadata (backward compat)
2106    pub async fn save_meta(&self, _meta: &SessionMeta) -> Result<()> {
2107        Ok(())
2108    }
2109
2110    /// Load metadata (backward compat)
2111    pub async fn load_meta(&self, _id: Uuid) -> Result<Option<SessionMeta>> {
2112        Ok(None)
2113    }
2114
2115    /// Create a new session (backward compat)
2116    pub async fn create_session(&mut self) -> Result<SessionMeta> {
2117        let id = Uuid::new_v4();
2118        let meta = SessionMeta::new(id);
2119        Ok(meta)
2120    }
2121
2122    /// Fork from current session at a specific entry, creating a new session file. Synchronous.
2123    pub fn branch_from_entry(&self, entry_id: &str) -> Result<String, String> {
2124        let path = self
2125            .get_session_file()
2126            .ok_or_else(|| "No session file path".to_string())?;
2127        let source_entries = load_entries_from_file(&path);
2128        if source_entries.is_empty() {
2129            return Err("Cannot fork: source session is empty".to_string());
2130        }
2131        // Validate header exists (content will be replaced with fresh header below)
2132        let _header = source_entries
2133            .iter()
2134            .find_map(|e| match e {
2135                FileEntry::Header(h) => Some(h),
2136                _ => None,
2137            })
2138            .ok_or_else(|| "Missing session header".to_string())?;
2139        let new_id = Uuid::new_v4().to_string();
2140        let timestamp = chrono::Utc::now().to_rfc3339();
2141        let file_timestamp = timestamp.replace([':', '.', 'T', '-', ':', '+'], "-");
2142        let short_id = &new_id[..8];
2143        let dir = std::path::Path::new(&path)
2144            .parent()
2145            .map(|p| p.to_string_lossy().into_owned())
2146            .unwrap_or_else(|| ".".to_string());
2147        let new_file = format!("{}/{}_{}.jsonl", dir, file_timestamp, short_id);
2148        let mut found = false;
2149        let mut new_entries = vec![FileEntry::Header(SessionHeader {
2150            entry_type: "session".to_string(),
2151            version: Some(CURRENT_SESSION_VERSION),
2152            id: new_id.clone(),
2153            timestamp,
2154            cwd: self.get_cwd(),
2155            parent_session: Some(path),
2156        })];
2157        for file_entry in &source_entries {
2158            if let FileEntry::Entry(entry) = file_entry {
2159                let eid = match entry {
2160                    SessionEntryEnum::Message(m) => m.base.id.clone(),
2161                    SessionEntryEnum::ThinkingLevelChange(m) => m.base.id.clone(),
2162                    SessionEntryEnum::ModelChange(m) => m.base.id.clone(),
2163                    SessionEntryEnum::Compaction(m) => m.base.id.clone(),
2164                    SessionEntryEnum::BranchSummary(m) => m.base.id.clone(),
2165                    SessionEntryEnum::Custom(m) => m.base.id.clone(),
2166                    SessionEntryEnum::Label(m) => m.base.id.clone(),
2167                    SessionEntryEnum::SessionInfo(m) => m.base.id.clone(),
2168                    SessionEntryEnum::CustomMessage(m) => m.base.id.clone(),
2169                };
2170                if eid == entry_id {
2171                    found = true;
2172                    // First entry in the fork: clear parent_id so the chain
2173                    // starts fresh in the new file (the old parent doesn't exist here).
2174                    let mut entry = entry.clone();
2175                    clear_entry_parent_id(&mut entry);
2176                    new_entries.push(FileEntry::Entry(entry));
2177                } else if found {
2178                    new_entries.push(FileEntry::Entry(entry.clone()));
2179                }
2180            }
2181        }
2182        if !found {
2183            return Err(format!("Entry not found: {}", entry_id));
2184        }
2185        let mut handle = std::fs::OpenOptions::new()
2186            .create(true)
2187            .truncate(true)
2188            .write(true)
2189            .open(&new_file)
2190            .map_err(|e| e.to_string())?;
2191        for entry in &new_entries {
2192            let line = serde_json::to_string(entry).map_err(|e| e.to_string())?;
2193            writeln!(&mut handle, "{}", line).map_err(|e| e.to_string())?;
2194        }
2195        Ok(new_file)
2196    }
2197}
2198
2199// ============================================================================
2200// Internal Conversion Functions
2201// ============================================================================
2202
2203/// Clear the parent_id of a session entry so it becomes a root entry.
2204/// Used by `branch_from_entry` to fix the parent chain in forked sessions.
2205fn clear_entry_parent_id(entry: &mut SessionEntryEnum) {
2206    match entry {
2207        SessionEntryEnum::Message(m) => m.base.parent_id = None,
2208        SessionEntryEnum::ThinkingLevelChange(m) => m.base.parent_id = None,
2209        SessionEntryEnum::ModelChange(m) => m.base.parent_id = None,
2210        SessionEntryEnum::Compaction(m) => m.base.parent_id = None,
2211        SessionEntryEnum::BranchSummary(m) => m.base.parent_id = None,
2212        SessionEntryEnum::Custom(m) => m.base.parent_id = None,
2213        SessionEntryEnum::Label(m) => m.base.parent_id = None,
2214        SessionEntryEnum::SessionInfo(m) => m.base.parent_id = None,
2215        SessionEntryEnum::CustomMessage(m) => m.base.parent_id = None,
2216    }
2217}
2218
2219/// Convert internal enum to simple SessionEntry struct
2220fn convert_to_session_entry(entry: &SessionEntryEnum) -> Option<SessionEntry> {
2221    match entry {
2222        SessionEntryEnum::Message(m) => Some(SessionEntry {
2223            id: m.base.id.clone(),
2224            parent_id: m.base.parent_id.clone(),
2225            timestamp: DateTime::parse_from_rfc3339(&m.base.timestamp)
2226                .map(|dt| dt.timestamp_millis())
2227                .unwrap_or(0),
2228            message: m.message.clone(),
2229        }),
2230        _ => None, // For now, we only convert message entries to the simple struct
2231    }
2232}
2233
2234/// Convert simple SessionEntry to internal FileEntry for persistence
2235fn convert_from_session_entry(entry: &SessionEntry) -> SessionEntryEnum {
2236    let timestamp = DateTime::from_timestamp_millis(entry.timestamp)
2237        .map(|dt| dt.to_rfc3339())
2238        .unwrap_or_else(|| Utc::now().to_rfc3339());
2239
2240    SessionEntryEnum::Message(SessionMessageEntry {
2241        base: SessionEntryBase {
2242            entry_type: "message".to_string(),
2243            id: entry.id.clone(),
2244            parent_id: entry.parent_id.clone(),
2245            timestamp,
2246        },
2247        message: entry.message.clone(),
2248    })
2249}
2250
2251// ============================================================================
2252// Session Statistics
2253// ============================================================================
2254
2255/// Session Stats.
2256#[derive(Debug, Clone)]
2257pub struct SessionStats {
2258    /// The message count.
2259    pub message_count: i64,
2260    /// The user message count.
2261    pub user_message_count: i64,
2262    /// The assistant message count.
2263    pub assistant_message_count: i64,
2264    /// The total chars.
2265    pub total_chars: i64,
2266    /// The estimated tokens.
2267    pub estimated_tokens: i64,
2268}
2269
2270// ============================================================================
2271// NewSessionOptions
2272// ============================================================================
2273
2274/// New Session Options.
2275#[derive(Debug, Clone)]
2276pub struct NewSessionOptions {
2277    /// The id.
2278    pub id: Option<String>,
2279    /// The parent session.
2280    pub parent_session: Option<String>,
2281}
2282
2283// ============================================================================
2284// Helper Functions
2285// ============================================================================
2286
2287/// Get default session dir.
2288pub fn get_default_session_dir(cwd: &str) -> String {
2289    let agent_dir = get_agent_dir();
2290    let safe_path = format!("--{}--", cwd.replace(['/', '\\', ':'], "-"));
2291    let session_dir = format!("{}/sessions/{}", agent_dir, safe_path);
2292
2293    if !Path::new(&session_dir).exists() {
2294        let _ = fs::create_dir_all(&session_dir);
2295    }
2296
2297    session_dir
2298}
2299
2300fn get_agent_dir() -> String {
2301    dirs::home_dir()
2302        .map(|h| h.join(".oxi").to_string_lossy().to_string())
2303        .unwrap_or_else(|| ".oxi".to_string())
2304}
2305
2306fn get_sessions_dir() -> String {
2307    format!("{}/sessions", get_agent_dir())
2308}
2309
2310/// Load entries from a JSONL file
2311fn load_entries_from_file(file_path: &str) -> Vec<FileEntry> {
2312    if !Path::new(file_path).exists() {
2313        return Vec::new();
2314    }
2315
2316    let file = match File::open(file_path) {
2317        Ok(f) => f,
2318        Err(_) => return Vec::new(),
2319    };
2320
2321    let reader = BufReader::new(file);
2322    let mut entries = Vec::new();
2323
2324    for line in reader.lines() {
2325        let line = match line {
2326            Ok(l) => l,
2327            Err(_) => continue,
2328        };
2329        if line.trim().is_empty() {
2330            continue;
2331        }
2332        match serde_json::from_str::<FileEntry>(&line) {
2333            Ok(entry) => entries.push(entry),
2334            Err(_) => continue,
2335        }
2336    }
2337
2338    // Validate session header
2339    if entries.is_empty() {
2340        return entries;
2341    }
2342    let header = match &entries[0] {
2343        FileEntry::Header(h) => h,
2344        _ => return Vec::new(),
2345    };
2346    if header.entry_type != "session" || header.id.is_empty() {
2347        return Vec::new();
2348    }
2349
2350    entries
2351}
2352
2353/// Check if a file is a valid session file
2354fn is_valid_session_file(file_path: &str) -> bool {
2355    if let Ok(mut file) = File::open(file_path) {
2356        use std::io::Read;
2357        let mut buffer = vec![0u8; 512];
2358        if let Ok(bytes_read) = file.read(&mut buffer) {
2359            if let Ok(content) = String::from_utf8(buffer[..bytes_read].to_vec()) {
2360                if let Some(first_line) = content.split('\n').next() {
2361                    if let Ok(header) = serde_json::from_str::<SessionHeader>(first_line) {
2362                        return header.entry_type == "session" && !header.id.is_empty();
2363                    }
2364                }
2365            }
2366        }
2367    }
2368    false
2369}
2370
2371/// Find the path of the most recent session for the given working directory.
2372pub fn find_recent_session_path(cwd: &str) -> Option<String> {
2373    let dir = get_default_session_dir(cwd);
2374    find_most_recent_session(&dir)
2375}
2376
2377fn find_most_recent_session(session_dir: &str) -> Option<String> {
2378    if !Path::new(session_dir).exists() {
2379        return None;
2380    }
2381
2382    let mut files: Vec<(String, std::time::SystemTime)> = Vec::new();
2383
2384    if let Ok(entries) = fs::read_dir(session_dir) {
2385        for entry in entries.flatten() {
2386            let path = entry.path();
2387            if path.extension().map(|e| e == "jsonl").unwrap_or(false) {
2388                if let Some(path_str) = path.to_str() {
2389                    if is_valid_session_file(path_str) {
2390                        if let Ok(metadata) = entry.metadata() {
2391                            if let Ok(mtime) = metadata.modified() {
2392                                files.push((path_str.to_string(), mtime));
2393                            }
2394                        }
2395                    }
2396                }
2397            }
2398        }
2399    }
2400
2401    files.sort_by_key(|b| std::cmp::Reverse(b.1));
2402    files.into_iter().next().map(|(p, _)| p)
2403}
2404
2405/// Resolve a session file path from user input, handling relative paths and ~.
2406pub fn resolve_session_path(input: &str, cwd: &str) -> Result<String, String> {
2407    let path = input.trim();
2408    if path.is_empty() {
2409        return Err("Empty path".to_string());
2410    }
2411    let resolved = if let Some(rest) = path.strip_prefix('~') {
2412        if rest.is_empty() {
2413            let home = dirs::home_dir().ok_or_else(|| "Cannot find home directory".to_string())?;
2414            home.to_string_lossy().into_owned()
2415        } else if let Some(rest) = rest.strip_prefix('/') {
2416            let home = dirs::home_dir().ok_or_else(|| "Cannot find home directory".to_string())?;
2417            format!("{}/{}", home.to_string_lossy(), rest)
2418        } else {
2419            let home = dirs::home_dir().ok_or_else(|| "Cannot find home directory".to_string())?;
2420            format!("{}/{}", home.to_string_lossy(), rest)
2421        }
2422    } else if path.starts_with('/') || path.contains(':') {
2423        path.to_string()
2424    } else {
2425        if let Some(stripped) = path.strip_prefix("./") {
2426            format!("{}/{}", cwd.trim_end_matches('/'), stripped)
2427        } else {
2428            format!("{}/{}", cwd.trim_end_matches('/'), path)
2429        }
2430    };
2431    let p = std::path::Path::new(&resolved);
2432    p.canonicalize()
2433        .map(|c| c.to_string_lossy().into_owned())
2434        .or(Ok(resolved))
2435}
2436
2437/// Build session context from entries using tree traversal
2438fn build_session_context_internal(
2439    entries: &[SessionEntry],
2440    leaf_id: Option<String>,
2441    _by_id: Option<&RwLock<HashMap<String, SessionEntry>>>,
2442) -> SessionContext {
2443    // Find leaf
2444    let leaf: Option<&SessionEntry> = leaf_id
2445        .as_ref()
2446        .and_then(|id| entries.iter().find(|e| e.id == *id));
2447
2448    let leaf = leaf.or_else(|| entries.last());
2449
2450    let Some(leaf) = leaf else {
2451        return SessionContext {
2452            messages: Vec::new(),
2453            thinking_level: "off".to_string(),
2454            model: None,
2455        };
2456    };
2457
2458    // Walk from leaf to root, collecting path
2459    let mut path: Vec<&SessionEntry> = Vec::new();
2460    let mut current: Option<&SessionEntry> = Some(leaf);
2461    while let Some(entry) = current {
2462        path.insert(0, entry);
2463        current = entry
2464            .parent_id
2465            .as_ref()
2466            .and_then(|pid| entries.iter().find(|e| e.id == *pid));
2467    }
2468
2469    // Extract settings
2470    let mut thinking_level = "off".to_string();
2471    let mut model: Option<ModelInfo> = None;
2472
2473    for entry in &path {
2474        if let AgentMessage::Assistant {
2475            provider, model_id, ..
2476        } = &entry.message
2477        {
2478            model = Some(ModelInfo {
2479                provider: provider.clone().unwrap_or_default(),
2480                model_id: model_id.clone().unwrap_or_default(),
2481            });
2482        }
2483        if let AgentMessage::Custom {
2484            custom_type,
2485            content,
2486            ..
2487        } = &entry.message
2488        {
2489            if custom_type == "thinking_level_change" {
2490                thinking_level = content.as_str().to_string();
2491            }
2492        }
2493    }
2494
2495    // Build messages - include all messages in the path
2496    let messages: Vec<AgentMessage> = path
2497        .iter()
2498        .filter(|e| {
2499            e.message.is_user()
2500                || e.message.is_assistant()
2501                || matches!(&e.message, AgentMessage::BranchSummary { .. })
2502                || matches!(&e.message, AgentMessage::CompactionSummary { .. })
2503        })
2504        .map(|e| e.message.clone())
2505        .collect();
2506
2507    SessionContext {
2508        messages,
2509        thinking_level,
2510        model,
2511    }
2512}
2513
2514/// Sort tree nodes by timestamp
2515fn sort_tree_by_timestamp(nodes: &mut Vec<SessionTreeNode>) {
2516    nodes.sort_by_key(|a| a.entry.timestamp);
2517
2518    for node in nodes {
2519        sort_tree_by_timestamp(&mut node.children);
2520    }
2521}
2522
2523/// List sessions from a directory
2524async fn list_sessions_from_dir(dir: &str) -> Result<Vec<SessionInfo>> {
2525    if !Path::new(dir).exists() {
2526        return Ok(Vec::new());
2527    }
2528
2529    let mut sessions = Vec::new();
2530
2531    let entries = fs::read_dir(dir)?;
2532    let files: Vec<String> = entries
2533        .filter_map(|e| e.ok())
2534        .filter(|e| {
2535            e.path()
2536                .extension()
2537                .map(|ext| ext == "jsonl")
2538                .unwrap_or(false)
2539        })
2540        .filter_map(|e| e.path().to_str().map(|s| s.to_string()))
2541        .collect();
2542
2543    for file in files {
2544        if let Some(info) = build_session_info(&file).await {
2545            sessions.push(info);
2546        }
2547    }
2548
2549    Ok(sessions)
2550}
2551
2552/// Build session info from a file
2553async fn build_session_info(file_path: &str) -> Option<SessionInfo> {
2554    let content = fs::read_to_string(file_path).ok()?;
2555    let entries = parse_session_entries(&content)?;
2556
2557    if entries.is_empty() {
2558        return None;
2559    }
2560
2561    let header = match &entries[0] {
2562        FileEntry::Header(h) => h,
2563        _ => return None,
2564    };
2565
2566    let stats = fs::metadata(file_path).ok()?;
2567    let mut message_count = 0i64;
2568    let mut first_message = String::new();
2569    let mut all_messages = Vec::new();
2570    let mut name: Option<String> = None;
2571
2572    for entry in &entries {
2573        if let FileEntry::Entry(e) = entry {
2574            // Check for session_info
2575            if let SessionEntryEnum::SessionInfo(si) = e {
2576                name = si
2577                    .name
2578                    .clone()
2579                    .map(|n| n.trim().to_string())
2580                    .filter(|n| !n.is_empty());
2581            }
2582            // Check for messages
2583            if let SessionEntryEnum::Message(m) = e {
2584                if m.message.is_user() {
2585                    message_count += 1;
2586                    let text = m.message.content();
2587                    if !text.is_empty() {
2588                        all_messages.push(text.clone());
2589                        if first_message.is_empty() {
2590                            first_message = text;
2591                        }
2592                    }
2593                }
2594            }
2595        }
2596    }
2597
2598    // Skip sessions with no real messages
2599    if message_count == 0 {
2600        return None;
2601    }
2602
2603    let cwd = header.cwd.clone();
2604    let parent_session_path = header.parent_session.clone();
2605    let created = chrono::DateTime::parse_from_rfc3339(&header.timestamp)
2606        .map(|dt| dt.with_timezone(&Utc))
2607        .unwrap_or_else(|_| Utc::now());
2608    let modified = get_session_modified_date(&entries, &header.timestamp, &stats);
2609
2610    Some(SessionInfo {
2611        path: file_path.to_string(),
2612        id: header.id.clone(),
2613        cwd,
2614        name,
2615        parent_session_path,
2616        created,
2617        modified,
2618        message_count,
2619        first_message: if first_message.is_empty() {
2620            "(no messages)".to_string()
2621        } else {
2622            first_message
2623        },
2624        all_messages_text: all_messages.join(" "),
2625    })
2626}
2627
2628/// Parse session entries from content
2629fn parse_session_entries(content: &str) -> Option<Vec<FileEntry>> {
2630    let mut entries = Vec::new();
2631
2632    for line in content.trim().lines() {
2633        if line.trim().is_empty() {
2634            continue;
2635        }
2636        if let Ok(entry) = serde_json::from_str::<FileEntry>(line) {
2637            entries.push(entry);
2638        }
2639    }
2640
2641    Some(entries)
2642}
2643
2644/// Get session modified date
2645fn get_session_modified_date(
2646    entries: &[FileEntry],
2647    header_timestamp: &str,
2648    stats: &std::fs::Metadata,
2649) -> DateTime<Utc> {
2650    let last_activity_time = get_last_activity_time(entries);
2651    if let Some(t) = last_activity_time {
2652        if t > 0 {
2653            return DateTime::from_timestamp_millis(t).unwrap_or_else(Utc::now);
2654        }
2655    }
2656
2657    let header_time = chrono::DateTime::parse_from_rfc3339(header_timestamp)
2658        .map(|dt| dt.timestamp_millis())
2659        .unwrap_or(-1);
2660
2661    if header_time > 0 {
2662        return DateTime::from_timestamp_millis(header_time).unwrap_or_else(Utc::now);
2663    }
2664
2665    if let Ok(mtime) = stats.modified() {
2666        return DateTime::from(mtime);
2667    }
2668
2669    Utc::now()
2670}
2671
2672/// Get last activity time from entries
2673fn get_last_activity_time(entries: &[FileEntry]) -> Option<i64> {
2674    let mut last_activity: Option<i64> = None;
2675
2676    for entry in entries {
2677        let entry = match entry {
2678            FileEntry::Entry(e) => e,
2679            _ => continue,
2680        };
2681
2682        if let SessionEntryEnum::Message(m) = entry {
2683            if m.message.is_user() || m.message.is_assistant() {
2684                last_activity = Some(std::cmp::max(
2685                    last_activity.unwrap_or(0),
2686                    m.base.timestamp.parse().unwrap_or(0),
2687                ));
2688            }
2689        }
2690    }
2691
2692    last_activity
2693}
2694
2695// ============================================================================
2696// Tests
2697// ============================================================================
2698
2699#[cfg(test)]
2700mod tests {
2701    use super::*;
2702
2703    #[test]
2704    fn test_session_creation() {
2705        let manager = SessionManager::in_memory("/tmp");
2706        assert!(!manager.get_session_id().is_empty());
2707        assert_eq!(manager.get_entries().len(), 0);
2708    }
2709
2710    #[test]
2711    fn test_append_message() {
2712        let mut manager = SessionManager::in_memory("/tmp");
2713        let id = manager.append_message(AgentMessage::User {
2714            content: ContentValue::String("Hello".to_string()),
2715        });
2716        assert!(!id.is_empty());
2717        assert_eq!(manager.get_entries().len(), 1);
2718        assert_eq!(manager.get_leaf_id(), Some(id));
2719    }
2720
2721    #[test]
2722    fn test_tree_traversal() {
2723        let mut manager = SessionManager::in_memory("/tmp");
2724        let id1 = manager.append_message(AgentMessage::User {
2725            content: ContentValue::String("Hello".to_string()),
2726        });
2727        let id2 = manager.append_message(AgentMessage::Assistant {
2728            content: vec![],
2729            provider: None,
2730            model_id: None,
2731            usage: None,
2732            stop_reason: None,
2733        });
2734
2735        // Get branch from root
2736        let branch = manager.get_branch(None);
2737        assert_eq!(branch.len(), 2);
2738
2739        // Get branch from specific entry
2740        let branch = manager.get_branch(Some(&id1));
2741        assert_eq!(branch.len(), 1);
2742
2743        // Get children
2744        let children = manager.get_children(&id1);
2745        assert_eq!(children.len(), 1);
2746
2747        // Get parent
2748        let parent = manager.get_parent(&id2);
2749        assert!(parent.is_some());
2750        assert_eq!(parent.unwrap().id, id1);
2751    }
2752
2753    #[test]
2754    fn test_branching() {
2755        let mut manager = SessionManager::in_memory("/tmp");
2756        let id1 = manager.append_message(AgentMessage::User {
2757            content: ContentValue::String("Hello".to_string()),
2758        });
2759        let _id2 = manager.append_message(AgentMessage::Assistant {
2760            content: vec![],
2761            provider: None,
2762            model_id: None,
2763            usage: None,
2764            stop_reason: None,
2765        });
2766        let _id3 = manager.append_message(AgentMessage::User {
2767            content: ContentValue::String("How are you?".to_string()),
2768        });
2769
2770        // Branch from first message
2771        manager.branch(&id1).unwrap();
2772        assert_eq!(manager.get_leaf_id(), Some(id1.clone()));
2773
2774        // Add new message on branch
2775        let id4 = manager.append_message(AgentMessage::Assistant {
2776            content: vec![],
2777            provider: None,
2778            model_id: None,
2779            usage: None,
2780            stop_reason: None,
2781        });
2782
2783        // Should have 4 entries total (3 original + 1 new branch)
2784        assert_eq!(manager.get_entries().len(), 4);
2785
2786        // Leaf should be the new message
2787        assert_eq!(manager.get_leaf_id(), Some(id4));
2788
2789        // Get tree - 1 root (id1), with 2 children (id2 and id4)
2790        let tree = manager.get_tree(Uuid::nil()).unwrap();
2791        assert_eq!(tree.len(), 1); // One root
2792        assert_eq!(tree[0].children.len(), 2); // id1 has 2 children: id2 and id4
2793    }
2794
2795    #[test]
2796    fn test_session_context() {
2797        let mut manager = SessionManager::in_memory("/tmp");
2798        manager.append_message(AgentMessage::User {
2799            content: ContentValue::String("Hello".to_string()),
2800        });
2801        manager.append_message(AgentMessage::Assistant {
2802            content: vec![AssistantContentBlock::Text {
2803                text: "Hi there!".to_string(),
2804            }],
2805            provider: Some("test".to_string()),
2806            model_id: Some("model".to_string()),
2807            usage: None,
2808            stop_reason: None,
2809        });
2810
2811        let context = manager.build_session_context();
2812        assert_eq!(context.messages.len(), 2);
2813        assert!(context.model.is_some());
2814    }
2815
2816    #[test]
2817    fn test_compaction_entry() {
2818        let mut manager = SessionManager::in_memory("/tmp");
2819        let id1 = manager.append_message(AgentMessage::User {
2820            content: ContentValue::String("First message".to_string()),
2821        });
2822        let _id2 = manager.append_message(AgentMessage::Assistant {
2823            content: vec![],
2824            provider: None,
2825            model_id: None,
2826            usage: None,
2827            stop_reason: None,
2828        });
2829
2830        let id3 = manager.append_compaction("Summarized conversation", &id1, 1000, None, None);
2831        assert!(!id3.is_empty());
2832
2833        let latest = manager.get_latest_compaction_entry();
2834        assert!(latest.is_some());
2835    }
2836
2837    #[test]
2838    fn test_labels() {
2839        let mut manager = SessionManager::in_memory("/tmp");
2840        let id1 = manager.append_message(AgentMessage::User {
2841            content: ContentValue::String("Hello".to_string()),
2842        });
2843
2844        manager.add_label(&id1, "important").unwrap();
2845        assert_eq!(manager.get_label(&id1), Some("important".to_string()));
2846
2847        manager.remove_label(&id1).unwrap();
2848        assert_eq!(manager.get_label(&id1), None);
2849    }
2850
2851    // ========================================================================
2852    // Session tree and branching tests
2853    // ========================================================================
2854
2855    /// Helper: create a user message
2856    fn user_msg(text: &str) -> AgentMessage {
2857        AgentMessage::User {
2858            content: ContentValue::String(text.to_string()),
2859        }
2860    }
2861
2862    /// Helper: create an assistant message
2863    fn assistant_msg(text: &str) -> AgentMessage {
2864        AgentMessage::Assistant {
2865            content: vec![AssistantContentBlock::Text {
2866                text: text.to_string(),
2867            }],
2868            provider: Some("anthropic".to_string()),
2869            model_id: Some("claude-test".to_string()),
2870            usage: None,
2871            stop_reason: None,
2872        }
2873    }
2874
2875    /// Helper: create a bare assistant message (no content/metadata)
2876    fn bare_assistant_msg() -> AgentMessage {
2877        AgentMessage::Assistant {
2878            content: vec![],
2879            provider: None,
2880            model_id: None,
2881            usage: None,
2882            stop_reason: None,
2883        }
2884    }
2885
2886    // ------------------------------------------------------------------------
2887    // append operations integration into tree
2888    // ------------------------------------------------------------------------
2889
2890    #[test]
2891    fn test_append_thinking_level_change_integrates() {
2892        let mut manager = SessionManager::in_memory("/tmp");
2893        let msg_id = manager.append_message(user_msg("hello"));
2894        let thinking_id = manager.append_thinking_level_change("high");
2895        let msg2_id = manager.append_message(assistant_msg("response"));
2896
2897        let entries = manager.get_entries();
2898        assert_eq!(entries.len(), 3);
2899
2900        // Thinking entry should be between the two messages
2901        let thinking_entry = entries.iter().find(|e| e.id == thinking_id).unwrap();
2902        assert_eq!(thinking_entry.parent_id, Some(msg_id));
2903
2904        let msg2 = entries.iter().find(|e| e.id == msg2_id).unwrap();
2905        assert_eq!(msg2.parent_id, Some(thinking_id));
2906    }
2907
2908    #[test]
2909    fn test_append_model_change_integrates() {
2910        let mut manager = SessionManager::in_memory("/tmp");
2911        let msg_id = manager.append_message(user_msg("hello"));
2912        let model_id = manager.append_model_change("openai", "gpt-4");
2913        let msg2_id = manager.append_message(assistant_msg("response"));
2914
2915        let entries = manager.get_entries();
2916        let model_entry = entries.iter().find(|e| e.id == model_id).unwrap();
2917        assert_eq!(model_entry.parent_id, Some(msg_id));
2918
2919        let msg2 = entries.iter().find(|e| e.id == msg2_id).unwrap();
2920        assert_eq!(msg2.parent_id, Some(model_id));
2921    }
2922
2923    #[test]
2924    fn test_append_compaction_integrates_into_tree() {
2925        let mut manager = SessionManager::in_memory("/tmp");
2926        let id1 = manager.append_message(user_msg("1"));
2927        let id2 = manager.append_message(assistant_msg("2"));
2928        let compaction_id = manager.append_compaction("summary", &id1, 1000, None, None);
2929        let id3 = manager.append_message(user_msg("3"));
2930
2931        let entries = manager.get_entries();
2932        let compaction = entries.iter().find(|e| e.id == compaction_id).unwrap();
2933        assert_eq!(compaction.parent_id, Some(id2));
2934
2935        let msg3 = entries.iter().find(|e| e.id == id3).unwrap();
2936        assert_eq!(msg3.parent_id, Some(compaction_id));
2937
2938        // Verify compaction content
2939        if let AgentMessage::CompactionSummary {
2940            summary,
2941            tokens_before,
2942            ..
2943        } = &compaction.message
2944        {
2945            assert_eq!(summary, "summary");
2946            assert_eq!(*tokens_before, 1000);
2947        } else {
2948            panic!("Expected CompactionSummary");
2949        }
2950    }
2951
2952    #[test]
2953    fn test_leaf_pointer_advances() {
2954        let mut manager = SessionManager::in_memory("/tmp");
2955        assert!(manager.get_leaf_id().is_none());
2956
2957        let id1 = manager.append_message(user_msg("1"));
2958        assert_eq!(manager.get_leaf_id(), Some(id1.clone()));
2959
2960        let id2 = manager.append_message(assistant_msg("2"));
2961        assert_eq!(manager.get_leaf_id(), Some(id2.clone()));
2962
2963        let id3 = manager.append_thinking_level_change("high");
2964        assert_eq!(manager.get_leaf_id(), Some(id3));
2965    }
2966
2967    #[test]
2968    fn test_get_entry() {
2969        let mut manager = SessionManager::in_memory("/tmp");
2970        assert!(manager.get_entry("nonexistent").is_none());
2971
2972        let id1 = manager.append_message(user_msg("first"));
2973        let id2 = manager.append_message(assistant_msg("second"));
2974
2975        let entry1 = manager.get_entry(&id1);
2976        assert!(entry1.is_some());
2977        assert!(entry1.unwrap().message.is_user());
2978
2979        let entry2 = manager.get_entry(&id2);
2980        assert!(entry2.is_some());
2981        assert!(entry2.unwrap().message.is_assistant());
2982    }
2983
2984    #[test]
2985    fn test_get_leaf_entry() {
2986        let manager = SessionManager::in_memory("/tmp");
2987        assert!(manager.get_leaf_entry().is_none());
2988
2989        let mut manager = SessionManager::in_memory("/tmp");
2990        manager.append_message(user_msg("1"));
2991        let id2 = manager.append_message(assistant_msg("2"));
2992
2993        let leaf = manager.get_leaf_entry();
2994        assert!(leaf.is_some());
2995        assert_eq!(leaf.unwrap().id, id2);
2996    }
2997
2998    // ------------------------------------------------------------------------
2999    // getBranch / getPath
3000    // ------------------------------------------------------------------------
3001
3002    #[test]
3003    fn test_get_branch_full_path_root_to_leaf() {
3004        let mut manager = SessionManager::in_memory("/tmp");
3005        let id1 = manager.append_message(user_msg("1"));
3006        let id2 = manager.append_message(assistant_msg("2"));
3007        let id3 = manager.append_thinking_level_change("high");
3008        let id4 = manager.append_message(user_msg("3"));
3009
3010        let branch = manager.get_branch(None);
3011        assert_eq!(branch.len(), 4);
3012        assert_eq!(branch[0].id, id1);
3013        assert_eq!(branch[1].id, id2);
3014        assert_eq!(branch[2].id, id3);
3015        assert_eq!(branch[3].id, id4);
3016    }
3017
3018    #[test]
3019    fn test_get_branch_from_specific_entry() {
3020        let mut manager = SessionManager::in_memory("/tmp");
3021        let id1 = manager.append_message(user_msg("1"));
3022        let id2 = manager.append_message(assistant_msg("2"));
3023        manager.append_message(user_msg("3"));
3024        manager.append_message(assistant_msg("4"));
3025
3026        let branch = manager.get_branch(Some(&id2));
3027        assert_eq!(branch.len(), 2);
3028        assert_eq!(branch[0].id, id1);
3029        assert_eq!(branch[1].id, id2);
3030    }
3031
3032    // ------------------------------------------------------------------------
3033    // Multiple branches at same point (3 siblings)
3034    // ------------------------------------------------------------------------
3035
3036    #[test]
3037    fn test_multiple_branches_at_same_point() {
3038        let mut manager = SessionManager::in_memory("/tmp");
3039        manager.append_message(user_msg("root"));
3040        let id2 = manager.append_message(bare_assistant_msg());
3041
3042        // Branch A
3043        manager.branch(&id2).unwrap();
3044        let id_a = manager.append_message(user_msg("branch-A"));
3045
3046        // Branch B
3047        manager.branch(&id2).unwrap();
3048        let id_b = manager.append_message(user_msg("branch-B"));
3049
3050        // Branch C
3051        manager.branch(&id2).unwrap();
3052        let id_c = manager.append_message(user_msg("branch-C"));
3053
3054        let tree = manager.get_tree(Uuid::nil()).unwrap();
3055        let node2 = &tree[0].children[0];
3056        assert_eq!(node2.entry.id, id2);
3057        assert_eq!(node2.children.len(), 3);
3058
3059        let mut branch_ids: Vec<String> =
3060            node2.children.iter().map(|c| c.entry.id.clone()).collect();
3061        branch_ids.sort();
3062        let mut expected = vec![id_a, id_b, id_c];
3063        expected.sort();
3064        assert_eq!(branch_ids, expected);
3065    }
3066
3067    // ------------------------------------------------------------------------
3068    // Deep branching
3069    // ------------------------------------------------------------------------
3070
3071    #[test]
3072    fn test_deep_branching() {
3073        let mut manager = SessionManager::in_memory("/tmp");
3074
3075        // Main path: 1 -> 2 -> 3 -> 4
3076        manager.append_message(user_msg("1"));
3077        let id2 = manager.append_message(bare_assistant_msg());
3078        let id3 = manager.append_message(user_msg("3"));
3079        manager.append_message(bare_assistant_msg());
3080
3081        // Branch from 2: 2 -> 5 -> 6
3082        manager.branch(&id2).unwrap();
3083        let id5 = manager.append_message(user_msg("5"));
3084        manager.append_message(bare_assistant_msg());
3085
3086        // Branch from 5: 5 -> 7
3087        manager.branch(&id5).unwrap();
3088        manager.append_message(user_msg("7"));
3089
3090        let tree = manager.get_tree(Uuid::nil()).unwrap();
3091
3092        // node2 has 2 children: id3 and id5
3093        let node2 = &tree[0].children[0];
3094        assert_eq!(node2.children.len(), 2);
3095
3096        let node5 = node2.children.iter().find(|c| c.entry.id == id5).unwrap();
3097        assert_eq!(node5.children.len(), 2); // id6 and id7
3098
3099        let node3 = node2.children.iter().find(|c| c.entry.id == id3).unwrap();
3100        assert_eq!(node3.children.len(), 1); // id4
3101    }
3102
3103    // ------------------------------------------------------------------------
3104    // branch_with_summary
3105    // ------------------------------------------------------------------------
3106
3107    #[test]
3108    fn test_branch_with_summary_inserts_and_advances() {
3109        let mut manager = SessionManager::in_memory("/tmp");
3110        let id1 = manager.append_message(user_msg("1"));
3111        manager.append_message(bare_assistant_msg());
3112        manager.append_message(user_msg("3"));
3113
3114        let summary_id =
3115            manager.branch_with_summary(Some(&id1), "Summary of abandoned work", None, None);
3116        assert!(!summary_id.is_empty());
3117        assert_eq!(manager.get_leaf_id(), Some(summary_id.clone()));
3118
3119        // Verify branch_summary entry
3120        let entries = manager.get_entries();
3121        let summary_entry = entries.iter().find(|e| e.id == summary_id).unwrap();
3122        assert_eq!(summary_entry.parent_id, Some(id1));
3123
3124        if let AgentMessage::BranchSummary { summary, .. } = &summary_entry.message {
3125            assert_eq!(summary, "Summary of abandoned work");
3126        } else {
3127            panic!("Expected BranchSummary");
3128        }
3129    }
3130
3131    // ------------------------------------------------------------------------
3132    // build_session_context with branches
3133    // ------------------------------------------------------------------------
3134
3135    #[test]
3136    fn test_build_session_context_returns_branch_messages() {
3137        let mut manager = SessionManager::in_memory("/tmp");
3138
3139        // Main: 1 -> 2 -> 3
3140        manager.append_message(user_msg("msg1"));
3141        let id2 = manager.append_message(bare_assistant_msg());
3142        manager.append_message(user_msg("msg3"));
3143
3144        // Branch from 2: 2 -> 4
3145        manager.branch(&id2).unwrap();
3146        manager.append_message(assistant_msg("msg4-branch"));
3147
3148        let ctx = manager.build_session_context();
3149        // Should have msg1, msg2, msg4-branch (NOT msg3)
3150        assert_eq!(ctx.messages.len(), 3);
3151        assert!(ctx.messages[0].is_user());
3152        assert!(ctx.messages[1].is_assistant());
3153        assert!(ctx.messages[2].is_assistant());
3154    }
3155
3156    #[test]
3157    fn test_build_session_context_follows_branch_path() {
3158        // Tree: 1 -> 2 -> 3 (branch A)
3159        //             \-> 4 (branch B)
3160        let mut manager = SessionManager::in_memory("/tmp");
3161        manager.append_message(user_msg("start"));
3162        let id2 = manager.append_message(bare_assistant_msg());
3163        manager.append_message(user_msg("branch A"));
3164
3165        // Switch to branch B
3166        manager.branch(&id2).unwrap();
3167        manager.append_message(user_msg("branch B"));
3168
3169        let ctx = manager.build_session_context();
3170        assert_eq!(ctx.messages.len(), 3);
3171        // Last message should be "branch B"
3172        let last = ctx.messages.last().unwrap();
3173        assert_eq!(last.content(), "branch B");
3174    }
3175
3176    #[test]
3177    fn test_build_session_context_includes_branch_summary() {
3178        let mut manager = SessionManager::in_memory("/tmp");
3179        manager.append_message(user_msg("start"));
3180        let id2 = manager.append_message(bare_assistant_msg());
3181        manager.append_message(user_msg("abandoned path"));
3182
3183        // Branch with summary
3184        manager.branch_with_summary(Some(&id2), "Summary of abandoned work", None, None);
3185        manager.append_message(user_msg("new direction"));
3186
3187        let ctx = manager.build_session_context();
3188        // Should include: start, response, branch_summary, new direction
3189        assert!(ctx.messages.len() >= 3);
3190
3191        // Branch summary should be in messages
3192        let has_summary = ctx.messages.iter().any(|m| {
3193            if let AgentMessage::BranchSummary { summary, .. } = m {
3194                summary == "Summary of abandoned work"
3195            } else {
3196                false
3197            }
3198        });
3199        assert!(has_summary, "Branch summary should be in context messages");
3200    }
3201
3202    #[test]
3203    fn test_build_session_context_with_compaction() {
3204        let mut manager = SessionManager::in_memory("/tmp");
3205
3206        // Build conversation
3207        let id1 = manager.append_message(user_msg("first"));
3208        manager.append_message(assistant_msg("response1"));
3209        manager.append_message(user_msg("second"));
3210        manager.append_message(assistant_msg("response2"));
3211
3212        // Add compaction
3213        manager.append_compaction("Summary of first two turns", &id1, 1000, None, None);
3214
3215        // Continue after compaction
3216        manager.append_message(user_msg("third"));
3217        manager.append_message(assistant_msg("response3"));
3218
3219        let ctx = manager.build_session_context();
3220        // CompactionSummary is NOT included in context messages (only user/assistant/branch_summary)
3221        // but the path from leaf should include all entries
3222        assert!(ctx.messages.len() >= 4); // at minimum: user, assistant, user, assistant from after-compaction path
3223
3224        // Compaction entry should exist in the entries
3225        let compaction_entries = manager.get_compaction_entries();
3226        assert_eq!(compaction_entries.len(), 1);
3227    }
3228
3229    #[test]
3230    fn test_build_session_context_tracks_thinking_level() {
3231        let mut manager = SessionManager::in_memory("/tmp");
3232        manager.append_message(user_msg("hello"));
3233        manager.append_thinking_level_change("high");
3234        manager.append_message(assistant_msg("thinking hard"));
3235
3236        let ctx = manager.build_session_context();
3237        assert_eq!(ctx.thinking_level, "high");
3238    }
3239
3240    // ------------------------------------------------------------------------
3241    // Labels in tree nodes
3242    // ------------------------------------------------------------------------
3243
3244    #[test]
3245    fn test_labels_in_tree_nodes() {
3246        let mut manager = SessionManager::in_memory("/tmp");
3247        let id1 = manager.append_message(user_msg("hello"));
3248        let id2 = manager.append_message(assistant_msg("hi"));
3249
3250        manager.add_label(&id1, "start").unwrap();
3251        manager.add_label(&id2, "response").unwrap();
3252
3253        let tree = manager.get_tree(Uuid::nil()).unwrap();
3254        let node1 = &tree[0];
3255        assert_eq!(node1.label, Some("start".to_string()));
3256
3257        let node2 = &node1.children[0];
3258        assert_eq!(node2.label, Some("response".to_string()));
3259    }
3260
3261    #[test]
3262    fn test_last_label_wins() {
3263        let mut manager = SessionManager::in_memory("/tmp");
3264        let id1 = manager.append_message(user_msg("hello"));
3265
3266        manager.add_label(&id1, "first").unwrap();
3267        manager.add_label(&id1, "second").unwrap();
3268        manager.add_label(&id1, "third").unwrap();
3269
3270        assert_eq!(manager.get_label(&id1), Some("third".to_string()));
3271    }
3272
3273    // ------------------------------------------------------------------------
3274    // branch throws for non-existent
3275    // ------------------------------------------------------------------------
3276
3277    #[test]
3278    fn test_branch_throws_for_nonexistent() {
3279        let mut manager = SessionManager::in_memory("/tmp");
3280        manager.append_message(user_msg("hello"));
3281
3282        let result = manager.branch("nonexistent");
3283        assert!(result.is_err());
3284    }
3285
3286    // ------------------------------------------------------------------------
3287    // Labels not included in buildSessionContext
3288    // ------------------------------------------------------------------------
3289
3290    #[test]
3291    fn test_labels_not_in_session_context() {
3292        let mut manager = SessionManager::in_memory("/tmp");
3293        let msg_id = manager.append_message(user_msg("hello"));
3294        manager.add_label(&msg_id, "checkpoint").unwrap();
3295
3296        let ctx = manager.build_session_context();
3297        // Should only have the user message, not label entries
3298        assert_eq!(ctx.messages.len(), 1);
3299        assert!(ctx.messages[0].is_user());
3300    }
3301
3302    // ------------------------------------------------------------------------
3303    // appendCustomEntry integration
3304    // ------------------------------------------------------------------------
3305
3306    #[test]
3307    fn test_custom_entry_integrates_into_tree() {
3308        let mut manager = SessionManager::in_memory("/tmp");
3309        let msg_id = manager.append_message(user_msg("hello"));
3310        let custom_id =
3311            manager.append_custom_entry("my_data", Some(serde_json::json!({"foo": "bar"})));
3312        let msg2_id = manager.append_message(assistant_msg("response"));
3313
3314        let entries = manager.get_entries();
3315        let custom = entries.iter().find(|e| e.id == custom_id).unwrap();
3316        assert_eq!(custom.parent_id, Some(msg_id));
3317
3318        if let AgentMessage::Custom { custom_type, .. } = &custom.message {
3319            assert_eq!(custom_type, "my_data");
3320        } else {
3321            panic!("Expected Custom message");
3322        }
3323
3324        let msg2 = entries.iter().find(|e| e.id == msg2_id).unwrap();
3325        assert_eq!(msg2.parent_id, Some(custom_id));
3326
3327        // buildSessionContext should work (custom entries skipped in messages)
3328        let ctx = manager.build_session_context();
3329        // Only the 2 real messages; custom entry is not user/assistant/branch_summary
3330        assert_eq!(ctx.messages.len(), 2);
3331    }
3332
3333    // ------------------------------------------------------------------------
3334    // Empty session edge cases
3335    // ------------------------------------------------------------------------
3336
3337    #[test]
3338    fn test_get_branch_empty_session() {
3339        let manager = SessionManager::in_memory("/tmp");
3340        let branch = manager.get_branch(None);
3341        assert!(branch.is_empty());
3342    }
3343
3344    #[test]
3345    fn test_get_tree_empty_session() {
3346        let manager = SessionManager::in_memory("/tmp");
3347        let tree = manager.get_tree(Uuid::nil()).unwrap();
3348        assert!(tree.is_empty());
3349    }
3350
3351    // ------------------------------------------------------------------------
3352    // Complex tree with branches and compaction
3353    // ------------------------------------------------------------------------
3354
3355    #[test]
3356    fn test_complex_tree_with_branches_and_compaction() {
3357        let mut manager = SessionManager::in_memory("/tmp");
3358
3359        // Main path: 1 -> 2 -> 3 -> 4 -> compaction(5) -> 6 -> 7
3360        manager.append_message(user_msg("start"));
3361        manager.append_message(assistant_msg("r1"));
3362        let id3 = manager.append_message(user_msg("q2"));
3363        manager.append_message(assistant_msg("r2"));
3364        manager.append_compaction("Compacted history", &id3, 1000, None, None);
3365        manager.append_message(user_msg("q3"));
3366        manager.append_message(assistant_msg("r3"));
3367
3368        // Abandoned branch from 3
3369        manager.branch(&id3).unwrap();
3370        manager.append_message(user_msg("wrong path"));
3371        manager.append_message(assistant_msg("wrong response"));
3372
3373        // Branch summary resuming from 3
3374        manager.branch_with_summary(Some(&id3), "Tried wrong approach", None, None);
3375        manager.append_message(user_msg("better approach"));
3376
3377        let tree = manager.get_tree(Uuid::nil()).unwrap();
3378        // Root node
3379        assert_eq!(tree.len(), 1);
3380
3381        // Walk tree to verify structure
3382        let root = &tree[0];
3383        assert!(root.entry.message.is_user());
3384    }
3385
3386    // ------------------------------------------------------------------------
3387    // get_latest_compaction_entry returns the most recent
3388    // ------------------------------------------------------------------------
3389
3390    #[test]
3391    fn test_multiple_compactions_returns_latest() {
3392        let mut manager = SessionManager::in_memory("/tmp");
3393        let id1 = manager.append_message(user_msg("a"));
3394        manager.append_message(bare_assistant_msg());
3395        manager.append_compaction("First summary", &id1, 1000, None, None);
3396        manager.append_message(user_msg("c"));
3397        manager.append_message(bare_assistant_msg());
3398        manager.append_compaction("Second summary", &id1, 2000, None, None);
3399
3400        // get_compaction_entries returns all compaction entries
3401        let compactions = manager.get_compaction_entries();
3402        assert_eq!(compactions.len(), 2);
3403
3404        // At least one should exist with the second summary
3405        let latest = manager.get_latest_compaction_entry();
3406        assert!(latest.is_some());
3407    }
3408
3409    // ------------------------------------------------------------------------
3410    // get_compaction_entries returns all
3411    // ------------------------------------------------------------------------
3412
3413    #[test]
3414    fn test_get_all_compaction_entries() {
3415        let mut manager = SessionManager::in_memory("/tmp");
3416        let id1 = manager.append_message(user_msg("a"));
3417        manager.append_message(bare_assistant_msg());
3418        manager.append_compaction("First", &id1, 1000, None, None);
3419        manager.append_message(user_msg("b"));
3420        manager.append_message(bare_assistant_msg());
3421        manager.append_compaction("Second", &id1, 2000, None, None);
3422
3423        let compactions = manager.get_compaction_entries();
3424        assert_eq!(compactions.len(), 2);
3425    }
3426}