intent-engine 0.11.1

A command-line database service for tracking strategic intent, tasks, and events
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
use crate::db::models::{TaskSortBy, WorkspaceStats};
use crate::error::Result;
use crate::events::EventManager;
use crate::tasks::TaskManager;
use crate::workspace::WorkspaceManager;
use serde::{Deserialize, Serialize};
use sqlx::SqlitePool;

/// Session restoration status
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SessionStatus {
    /// Successfully restored focus
    Success,
    /// No active focus (workspace exists but no current task)
    NoFocus,
    /// Error occurred
    Error,
}

/// Error types for session restoration
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorType {
    WorkspaceNotFound,
    DatabaseCorrupted,
    PermissionDenied,
}

/// Simplified task info for session restoration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskInfo {
    pub id: i64,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
}

/// Detailed current task info
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CurrentTaskInfo {
    pub id: i64,
    pub name: String,
    pub status: String,
    /// Full spec
    pub spec: Option<String>,
    /// Truncated spec (first 100 chars)
    pub spec_preview: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub first_doing_at: Option<String>,
}

/// Siblings information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SiblingsInfo {
    pub total: usize,
    pub done: usize,
    pub doing: usize,
    pub todo: usize,
    pub done_list: Vec<TaskInfo>,
}

/// Children information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChildrenInfo {
    pub total: usize,
    pub todo: usize,
    pub list: Vec<TaskInfo>,
}

/// Event information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventInfo {
    #[serde(rename = "type")]
    pub event_type: String,
    pub data: String,
    pub timestamp: String,
}

// WorkspaceStats is imported from crate::db::models

/// Complete session restoration result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionRestoreResult {
    pub status: SessionStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace_path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub current_task: Option<CurrentTaskInfo>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_task: Option<TaskInfo>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub siblings: Option<SiblingsInfo>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub children: Option<ChildrenInfo>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recent_events: Option<Vec<EventInfo>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suggested_commands: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stats: Option<WorkspaceStats>,
    /// Recommended next task (from pick_next) - used when no focus
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recommended_task: Option<TaskInfo>,
    /// Top pending tasks by priority - used when no focus
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_pending_tasks: Option<Vec<TaskInfo>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_type: Option<ErrorType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recovery_suggestion: Option<String>,
}

/// Session restoration manager
pub struct SessionRestoreManager<'a> {
    pool: &'a SqlitePool,
}

impl<'a> SessionRestoreManager<'a> {
    pub fn new(pool: &'a SqlitePool) -> Self {
        Self { pool }
    }

    /// Restore session with full context
    pub async fn restore(&self, include_events: usize) -> Result<SessionRestoreResult> {
        let workspace_mgr = WorkspaceManager::new(self.pool);
        let task_mgr = TaskManager::new(self.pool);
        let event_mgr = EventManager::new(self.pool);

        // Get current workspace path (for display purposes)
        let workspace_path = std::env::current_dir()
            .ok()
            .and_then(|p| p.to_str().map(String::from));

        // Get current task
        let current_task_id = match workspace_mgr.get_current_task(None).await {
            Ok(response) => {
                if let Some(id) = response.current_task_id {
                    id
                } else {
                    // No focus - return stats
                    return self.restore_no_focus(workspace_path).await;
                }
            },
            Err(_) => {
                // Error getting current task
                return Ok(Self::error_result(
                    workspace_path,
                    ErrorType::DatabaseCorrupted,
                    "Unable to query workspace state",
                    "Run 'ie workspace init' or check database integrity",
                ));
            },
        };

        // Get current task details
        let task = match task_mgr.get_task(current_task_id).await {
            Ok(t) => t,
            Err(_) => {
                return Ok(Self::error_result(
                    workspace_path,
                    ErrorType::DatabaseCorrupted,
                    "Current task not found in database",
                    "Run 'ie current --set <task_id>' to set a valid task",
                ));
            },
        };

        let spec_preview = task.spec.as_ref().map(|s| Self::truncate_spec(s, 100));

        let current_task = CurrentTaskInfo {
            id: task.id,
            name: task.name.clone(),
            status: task.status.clone(),
            spec: task.spec.clone(),
            spec_preview,
            created_at: task.first_todo_at.map(|dt| dt.to_rfc3339()),
            first_doing_at: task.first_doing_at.map(|dt| dt.to_rfc3339()),
        };

        // Get parent task
        let parent_task = if let Some(parent_id) = task.parent_id {
            task_mgr.get_task(parent_id).await.ok().map(|p| TaskInfo {
                id: p.id,
                name: p.name,
                status: Some(p.status),
            })
        } else {
            None
        };

        // Get siblings info
        let siblings = if let Some(parent_id) = task.parent_id {
            let result = task_mgr
                .find_tasks(None, Some(Some(parent_id)), None, None, None)
                .await?;
            Self::build_siblings_info(&result.tasks)
        } else {
            None
        };

        // Get children info
        let children = {
            let result = task_mgr
                .find_tasks(None, Some(Some(current_task_id)), None, None, None)
                .await?;
            Self::build_children_info(&result.tasks)
        };

        // Get recent events
        let events = event_mgr
            .list_events(Some(current_task_id), None, None, None)
            .await?;
        let recent_events: Vec<EventInfo> = events
            .into_iter()
            .take(include_events)
            .map(|e| EventInfo {
                event_type: e.log_type,
                data: e.discussion_data,
                timestamp: e.timestamp.to_rfc3339(),
            })
            .collect();

        // Suggest next commands based on context
        let suggested_commands = Self::suggest_commands(&current_task, children.as_ref());

        Ok(SessionRestoreResult {
            status: SessionStatus::Success,
            workspace_path,
            current_task: Some(current_task),
            parent_task,
            siblings,
            children,
            recent_events: Some(recent_events),
            suggested_commands: Some(suggested_commands),
            stats: None,
            recommended_task: None,
            top_pending_tasks: None,
            error_type: None,
            message: None,
            recovery_suggestion: None,
        })
    }

    /// Restore when no focus exists
    ///
    /// Uses efficient SQL aggregation for stats and limited queries for task lists.
    /// Does NOT load all tasks into memory.
    async fn restore_no_focus(
        &self,
        workspace_path: Option<String>,
    ) -> Result<SessionRestoreResult> {
        let task_mgr = TaskManager::new(self.pool);

        // 1. Get stats using SQL aggregation (no data loading)
        let stats = task_mgr.get_stats().await?;

        // 2. Get recommended next task via pick_next
        let recommendation = task_mgr.pick_next().await?;
        let recommended_task = recommendation.task.map(|t| TaskInfo {
            id: t.id,
            name: t.name,
            status: Some(t.status),
        });

        // 3. Get top 5 pending tasks by priority (limited query)
        let top_pending_result = task_mgr
            .find_tasks(
                Some("todo".to_string()),
                None,
                Some(TaskSortBy::Priority),
                Some(5),
                None,
            )
            .await?;
        let top_pending_tasks: Vec<TaskInfo> = top_pending_result
            .tasks
            .into_iter()
            .map(|t| TaskInfo {
                id: t.id,
                name: t.name,
                status: Some(t.status),
            })
            .collect();

        let suggested_commands = vec![
            "ie pick-next".to_string(),
            "ie task list --status todo".to_string(),
        ];

        Ok(SessionRestoreResult {
            status: SessionStatus::NoFocus,
            workspace_path,
            current_task: None,
            parent_task: None,
            siblings: None,
            children: None,
            recent_events: None,
            suggested_commands: Some(suggested_commands),
            stats: Some(stats),
            recommended_task,
            top_pending_tasks: if top_pending_tasks.is_empty() {
                None
            } else {
                Some(top_pending_tasks)
            },
            error_type: None,
            message: None,
            recovery_suggestion: None,
        })
    }

    /// Build siblings information
    fn build_siblings_info(siblings: &[crate::db::models::Task]) -> Option<SiblingsInfo> {
        if siblings.is_empty() {
            return None;
        }

        let done_list: Vec<TaskInfo> = siblings
            .iter()
            .filter(|s| s.status == "done")
            .map(|s| TaskInfo {
                id: s.id,
                name: s.name.clone(),
                status: Some(s.status.clone()),
            })
            .collect();

        Some(SiblingsInfo {
            total: siblings.len(),
            done: siblings.iter().filter(|s| s.status == "done").count(),
            doing: siblings.iter().filter(|s| s.status == "doing").count(),
            todo: siblings.iter().filter(|s| s.status == "todo").count(),
            done_list,
        })
    }

    /// Build children information
    fn build_children_info(children: &[crate::db::models::Task]) -> Option<ChildrenInfo> {
        if children.is_empty() {
            return None;
        }

        let list: Vec<TaskInfo> = children
            .iter()
            .map(|c| TaskInfo {
                id: c.id,
                name: c.name.clone(),
                status: Some(c.status.clone()),
            })
            .collect();

        Some(ChildrenInfo {
            total: children.len(),
            todo: children.iter().filter(|c| c.status == "todo").count(),
            list,
        })
    }

    /// Suggest next commands based on context
    fn suggest_commands(
        _current_task: &CurrentTaskInfo,
        children: Option<&ChildrenInfo>,
    ) -> Vec<String> {
        let mut commands = vec![];

        // If there are blockers, suggest viewing them
        commands.push("ie event list --type blocker".to_string());

        // Suggest completion or spawning subtasks
        if let Some(children) = children {
            if children.todo > 0 {
                commands.push("ie task done".to_string());
            }
        } else {
            commands.push("ie task done".to_string());
        }

        commands.push("ie task spawn-subtask".to_string());

        commands
    }

    /// Truncate spec to specified length
    fn truncate_spec(spec: &str, max_len: usize) -> String {
        if spec.len() <= max_len {
            spec.to_string()
        } else {
            format!("{}...", &spec[..max_len])
        }
    }

    /// Create error result
    fn error_result(
        workspace_path: Option<String>,
        error_type: ErrorType,
        message: &str,
        recovery: &str,
    ) -> SessionRestoreResult {
        let suggested_commands = match error_type {
            ErrorType::WorkspaceNotFound => {
                vec!["ie workspace init".to_string(), "ie help".to_string()]
            },
            ErrorType::DatabaseCorrupted => {
                vec!["ie workspace init".to_string(), "ie doctor".to_string()]
            },
            ErrorType::PermissionDenied => {
                vec!["chmod 644 .intent-engine/workspace.db".to_string()]
            },
        };

        SessionRestoreResult {
            status: SessionStatus::Error,
            workspace_path,
            current_task: None,
            parent_task: None,
            siblings: None,
            children: None,
            recent_events: None,
            suggested_commands: Some(suggested_commands),
            stats: None,
            recommended_task: None,
            top_pending_tasks: None,
            error_type: Some(error_type),
            message: Some(message.to_string()),
            recovery_suggestion: Some(recovery.to_string()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::events::EventManager;
    use crate::tasks::{TaskManager, TaskUpdate};
    use crate::test_utils::test_helpers::TestContext;
    use crate::workspace::WorkspaceManager;

    #[test]
    fn test_truncate_spec() {
        let spec = "a".repeat(200);
        let truncated = SessionRestoreManager::truncate_spec(&spec, 100);
        assert_eq!(truncated.len(), 103); // 100 + "..."
        assert!(truncated.ends_with("..."));
    }

    #[test]
    fn test_truncate_spec_short() {
        let spec = "Short spec";
        let truncated = SessionRestoreManager::truncate_spec(spec, 100);
        assert_eq!(truncated, spec);
        assert!(!truncated.ends_with("..."));
    }

    #[tokio::test]
    async fn test_restore_with_focus_minimal() {
        let ctx = TestContext::new().await;
        let pool = ctx.pool();

        // Create a task and set it as current
        let task_mgr = TaskManager::new(pool);
        let task = task_mgr
            .add_task("Test task".to_string(), None, None, None, None, None)
            .await
            .unwrap();

        let workspace_mgr = WorkspaceManager::new(pool);
        workspace_mgr.set_current_task(task.id, None).await.unwrap();

        // Restore session
        let restore_mgr = SessionRestoreManager::new(pool);
        let result = restore_mgr.restore(3).await.unwrap();

        // Verify
        assert_eq!(result.status, SessionStatus::Success);
        assert!(result.current_task.is_some());
        let current_task = result.current_task.unwrap();
        assert_eq!(current_task.id, task.id);
        assert_eq!(current_task.name, "Test task");
    }

    #[tokio::test]
    async fn test_restore_with_focus_rich_context() {
        let ctx = TestContext::new().await;
        let pool = ctx.pool();

        let task_mgr = TaskManager::new(pool);
        let event_mgr = EventManager::new(pool);
        let workspace_mgr = WorkspaceManager::new(pool);

        // Create parent task
        let parent = task_mgr
            .add_task(
                "Parent task".to_string(),
                Some("Parent spec".to_string()),
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();

        // Create 3 siblings (1 done, 1 doing, 1 todo)
        let sibling1 = task_mgr
            .add_task(
                "Sibling 1".to_string(),
                None,
                Some(parent.id),
                None,
                None,
                None,
            )
            .await
            .unwrap();
        task_mgr
            .update_task(
                sibling1.id,
                TaskUpdate {
                    status: Some("done"),
                    ..Default::default()
                },
            )
            .await
            .unwrap();

        let current = task_mgr
            .add_task(
                "Current task".to_string(),
                Some("Current spec".to_string()),
                Some(parent.id),
                None,
                None,
                None,
            )
            .await
            .unwrap();
        task_mgr
            .update_task(
                current.id,
                TaskUpdate {
                    status: Some("doing"),
                    ..Default::default()
                },
            )
            .await
            .unwrap();
        workspace_mgr
            .set_current_task(current.id, None)
            .await
            .unwrap();

        let _sibling3 = task_mgr
            .add_task(
                "Sibling 3".to_string(),
                None,
                Some(parent.id),
                None,
                None,
                None,
            )
            .await
            .unwrap();

        // Add children to current task
        let _child1 = task_mgr
            .add_task(
                "Child 1".to_string(),
                None,
                Some(current.id),
                None,
                None,
                None,
            )
            .await
            .unwrap();
        let _child2 = task_mgr
            .add_task(
                "Child 2".to_string(),
                None,
                Some(current.id),
                None,
                None,
                None,
            )
            .await
            .unwrap();

        // Add events
        event_mgr
            .add_event(current.id, "decision".to_string(), "Decision 1".to_string())
            .await
            .unwrap();
        event_mgr
            .add_event(current.id, "blocker".to_string(), "Blocker 1".to_string())
            .await
            .unwrap();
        event_mgr
            .add_event(current.id, "note".to_string(), "Note 1".to_string())
            .await
            .unwrap();

        // Restore session
        let restore_mgr = SessionRestoreManager::new(pool);
        let result = restore_mgr.restore(3).await.unwrap();

        // Verify complete context
        assert_eq!(result.status, SessionStatus::Success);

        let task = result.current_task.unwrap();
        assert_eq!(task.id, current.id);
        assert_eq!(task.spec, Some("Current spec".to_string()));

        // Verify parent
        assert!(result.parent_task.is_some());
        let parent_info = result.parent_task.unwrap();
        assert_eq!(parent_info.id, parent.id);

        // Verify siblings
        assert!(result.siblings.is_some());
        let siblings = result.siblings.unwrap();
        assert_eq!(siblings.total, 3);
        assert_eq!(siblings.done, 1);
        assert_eq!(siblings.doing, 1);
        assert_eq!(siblings.todo, 1);
        assert_eq!(siblings.done_list.len(), 1);

        // Verify children
        assert!(result.children.is_some());
        let children = result.children.unwrap();
        assert_eq!(children.total, 2);
        assert_eq!(children.todo, 2);

        // Verify events
        assert!(result.recent_events.is_some());
        let events = result.recent_events.unwrap();
        assert_eq!(events.len(), 3);

        // Check event types
        let event_types: Vec<&str> = events.iter().map(|e| e.event_type.as_str()).collect();
        assert!(event_types.contains(&"decision"));
        assert!(event_types.contains(&"blocker"));
        assert!(event_types.contains(&"note"));
    }

    #[tokio::test]
    async fn test_restore_with_spec_preview() {
        let ctx = TestContext::new().await;
        let pool = ctx.pool();

        let task_mgr = TaskManager::new(pool);
        let workspace_mgr = WorkspaceManager::new(pool);

        // Create task with long spec
        let long_spec = "a".repeat(200);
        let task = task_mgr
            .add_task(
                "Test task".to_string(),
                Some(long_spec.to_string()),
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        workspace_mgr.set_current_task(task.id, None).await.unwrap();

        // Restore
        let restore_mgr = SessionRestoreManager::new(pool);
        let result = restore_mgr.restore(3).await.unwrap();

        // Verify spec preview is truncated
        let current_task = result.current_task.unwrap();
        assert_eq!(current_task.spec, Some(long_spec));
        assert!(current_task.spec_preview.is_some());
        let preview = current_task.spec_preview.unwrap();
        assert_eq!(preview.len(), 103); // 100 + "..."
        assert!(preview.ends_with("..."));
    }

    #[tokio::test]
    async fn test_restore_no_focus() {
        let ctx = TestContext::new().await;
        let pool = ctx.pool();

        let task_mgr = TaskManager::new(pool);

        // Create some tasks but no current task
        task_mgr
            .add_task("Task 1".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        task_mgr
            .add_task("Task 2".to_string(), None, None, None, None, None)
            .await
            .unwrap();

        // Restore
        let restore_mgr = SessionRestoreManager::new(pool);
        let result = restore_mgr.restore(3).await.unwrap();

        // Verify no focus status
        assert_eq!(result.status, SessionStatus::NoFocus);
        assert!(result.current_task.is_none());
        assert!(result.stats.is_some());

        let stats = result.stats.unwrap();
        assert_eq!(stats.total_tasks, 2);
        assert_eq!(stats.todo, 2);

        // Verify new fields: recommended_task and top_pending_tasks
        // pick_next should recommend one of the tasks
        assert!(result.recommended_task.is_some());

        // top_pending_tasks should contain the 2 todo tasks
        assert!(result.top_pending_tasks.is_some());
        let top_pending = result.top_pending_tasks.unwrap();
        assert_eq!(top_pending.len(), 2);
    }

    #[tokio::test]
    async fn test_restore_recent_events_limit() {
        let ctx = TestContext::new().await;
        let pool = ctx.pool();

        let task_mgr = TaskManager::new(pool);
        let event_mgr = EventManager::new(pool);
        let workspace_mgr = WorkspaceManager::new(pool);

        // Create task
        let task = task_mgr
            .add_task("Test task".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        workspace_mgr.set_current_task(task.id, None).await.unwrap();

        // Add 10 events
        for i in 0..10 {
            event_mgr
                .add_event(task.id, "note".to_string(), format!("Event {}", i))
                .await
                .unwrap();
        }

        // Restore with default limit (3)
        let restore_mgr = SessionRestoreManager::new(pool);
        let result = restore_mgr.restore(3).await.unwrap();

        // Should only return 3 events (most recent)
        let events = result.recent_events.unwrap();
        assert_eq!(events.len(), 3);
    }

    #[tokio::test]
    async fn test_restore_custom_events_limit() {
        let ctx = TestContext::new().await;
        let pool = ctx.pool();

        let task_mgr = TaskManager::new(pool);
        let event_mgr = EventManager::new(pool);
        let workspace_mgr = WorkspaceManager::new(pool);

        // Create task
        let task = task_mgr
            .add_task("Test task".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        workspace_mgr.set_current_task(task.id, None).await.unwrap();

        // Add 10 events
        for i in 0..10 {
            event_mgr
                .add_event(task.id, "note".to_string(), format!("Event {}", i))
                .await
                .unwrap();
        }

        // Restore with custom limit (5)
        let restore_mgr = SessionRestoreManager::new(pool);
        let result = restore_mgr.restore(5).await.unwrap();

        // Should return 5 events
        let events = result.recent_events.unwrap();
        assert_eq!(events.len(), 5);
    }

    #[test]
    fn test_suggest_commands_with_children() {
        let current_task = CurrentTaskInfo {
            id: 1,
            name: "Test".to_string(),
            status: "doing".to_string(),
            spec: None,
            spec_preview: None,
            created_at: None,
            first_doing_at: None,
        };

        let children = Some(ChildrenInfo {
            total: 2,
            todo: 1,
            list: vec![],
        });

        let commands = SessionRestoreManager::suggest_commands(&current_task, children.as_ref());

        assert!(!commands.is_empty());
        assert!(commands.iter().any(|c| c.contains("blocker")));
    }

    #[test]
    fn test_error_result_workspace_not_found() {
        let result = SessionRestoreManager::error_result(
            Some("/test/path".to_string()),
            ErrorType::WorkspaceNotFound,
            "Test message",
            "Test recovery",
        );

        assert_eq!(result.status, SessionStatus::Error);
        assert_eq!(result.error_type, Some(ErrorType::WorkspaceNotFound));
        assert_eq!(result.message, Some("Test message".to_string()));
        assert_eq!(
            result.recovery_suggestion,
            Some("Test recovery".to_string())
        );
        assert!(result.suggested_commands.is_some());

        let commands = result.suggested_commands.unwrap();
        assert!(commands.iter().any(|c| c.contains("init")));
    }

    #[test]
    fn test_build_siblings_info_empty() {
        let siblings: Vec<crate::db::models::Task> = vec![];
        let result = SessionRestoreManager::build_siblings_info(&siblings);
        assert!(result.is_none());
    }

    #[test]
    fn test_build_children_info_empty() {
        let children: Vec<crate::db::models::Task> = vec![];
        let result = SessionRestoreManager::build_children_info(&children);
        assert!(result.is_none());
    }
}