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