1use crate::db::models::{TaskSortBy, WorkspaceStats};
2use crate::error::Result;
3use crate::events::EventManager;
4use crate::tasks::TaskManager;
5use crate::workspace::WorkspaceManager;
6use serde::{Deserialize, Serialize};
7use sqlx::SqlitePool;
8
9#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11#[serde(rename_all = "lowercase")]
12pub enum SessionStatus {
13 Success,
15 NoFocus,
17 Error,
19}
20
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum ErrorType {
25 WorkspaceNotFound,
26 DatabaseCorrupted,
27 PermissionDenied,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct TaskInfo {
33 pub id: i64,
34 pub name: String,
35 #[serde(skip_serializing_if = "Option::is_none")]
36 pub status: Option<String>,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct CurrentTaskInfo {
42 pub id: i64,
43 pub name: String,
44 pub status: String,
45 pub spec: Option<String>,
47 pub spec_preview: Option<String>,
49 #[serde(skip_serializing_if = "Option::is_none")]
50 pub created_at: Option<String>,
51 #[serde(skip_serializing_if = "Option::is_none")]
52 pub first_doing_at: Option<String>,
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct SiblingsInfo {
58 pub total: usize,
59 pub done: usize,
60 pub doing: usize,
61 pub todo: usize,
62 pub done_list: Vec<TaskInfo>,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct ChildrenInfo {
68 pub total: usize,
69 pub todo: usize,
70 pub list: Vec<TaskInfo>,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct EventInfo {
76 #[serde(rename = "type")]
77 pub event_type: String,
78 pub data: String,
79 pub timestamp: String,
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct SessionRestoreResult {
87 pub status: SessionStatus,
88 #[serde(skip_serializing_if = "Option::is_none")]
89 pub workspace_path: Option<String>,
90 #[serde(skip_serializing_if = "Option::is_none")]
91 pub current_task: Option<CurrentTaskInfo>,
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub parent_task: Option<TaskInfo>,
94 #[serde(skip_serializing_if = "Option::is_none")]
95 pub siblings: Option<SiblingsInfo>,
96 #[serde(skip_serializing_if = "Option::is_none")]
97 pub children: Option<ChildrenInfo>,
98 #[serde(skip_serializing_if = "Option::is_none")]
99 pub recent_events: Option<Vec<EventInfo>>,
100 #[serde(skip_serializing_if = "Option::is_none")]
101 pub suggested_commands: Option<Vec<String>>,
102 #[serde(skip_serializing_if = "Option::is_none")]
103 pub stats: Option<WorkspaceStats>,
104 #[serde(skip_serializing_if = "Option::is_none")]
106 pub recommended_task: Option<TaskInfo>,
107 #[serde(skip_serializing_if = "Option::is_none")]
109 pub top_pending_tasks: Option<Vec<TaskInfo>>,
110 #[serde(skip_serializing_if = "Option::is_none")]
111 pub error_type: Option<ErrorType>,
112 #[serde(skip_serializing_if = "Option::is_none")]
113 pub message: Option<String>,
114 #[serde(skip_serializing_if = "Option::is_none")]
115 pub recovery_suggestion: Option<String>,
116}
117
118pub struct SessionRestoreManager<'a> {
120 pool: &'a SqlitePool,
121}
122
123impl<'a> SessionRestoreManager<'a> {
124 pub fn new(pool: &'a SqlitePool) -> Self {
125 Self { pool }
126 }
127
128 pub async fn restore(&self, include_events: usize) -> Result<SessionRestoreResult> {
130 let workspace_mgr = WorkspaceManager::new(self.pool);
131 let task_mgr = TaskManager::new(self.pool);
132 let event_mgr = EventManager::new(self.pool);
133
134 let workspace_path = std::env::current_dir()
136 .ok()
137 .and_then(|p| p.to_str().map(String::from));
138
139 let current_task_id = match workspace_mgr.get_current_task().await {
141 Ok(response) => {
142 if let Some(id) = response.current_task_id {
143 id
144 } else {
145 return self.restore_no_focus(workspace_path).await;
147 }
148 },
149 Err(_) => {
150 return Ok(Self::error_result(
152 workspace_path,
153 ErrorType::DatabaseCorrupted,
154 "Unable to query workspace state",
155 "Run 'ie workspace init' or check database integrity",
156 ));
157 },
158 };
159
160 let task = match task_mgr.get_task(current_task_id).await {
162 Ok(t) => t,
163 Err(_) => {
164 return Ok(Self::error_result(
165 workspace_path,
166 ErrorType::DatabaseCorrupted,
167 "Current task not found in database",
168 "Run 'ie current --set <task_id>' to set a valid task",
169 ));
170 },
171 };
172
173 let spec_preview = task.spec.as_ref().map(|s| Self::truncate_spec(s, 100));
174
175 let current_task = CurrentTaskInfo {
176 id: task.id,
177 name: task.name.clone(),
178 status: task.status.clone(),
179 spec: task.spec.clone(),
180 spec_preview,
181 created_at: task.first_todo_at.map(|dt| dt.to_rfc3339()),
182 first_doing_at: task.first_doing_at.map(|dt| dt.to_rfc3339()),
183 };
184
185 let parent_task = if let Some(parent_id) = task.parent_id {
187 task_mgr.get_task(parent_id).await.ok().map(|p| TaskInfo {
188 id: p.id,
189 name: p.name,
190 status: Some(p.status),
191 })
192 } else {
193 None
194 };
195
196 let siblings = if let Some(parent_id) = task.parent_id {
198 let result = task_mgr
199 .find_tasks(None, Some(Some(parent_id)), None, None, None)
200 .await?;
201 Self::build_siblings_info(&result.tasks)
202 } else {
203 None
204 };
205
206 let children = {
208 let result = task_mgr
209 .find_tasks(None, Some(Some(current_task_id)), None, None, None)
210 .await?;
211 Self::build_children_info(&result.tasks)
212 };
213
214 let events = event_mgr
216 .list_events(Some(current_task_id), None, None, None)
217 .await?;
218 let recent_events: Vec<EventInfo> = events
219 .into_iter()
220 .take(include_events)
221 .map(|e| EventInfo {
222 event_type: e.log_type,
223 data: e.discussion_data,
224 timestamp: e.timestamp.to_rfc3339(),
225 })
226 .collect();
227
228 let suggested_commands = Self::suggest_commands(¤t_task, children.as_ref());
230
231 Ok(SessionRestoreResult {
232 status: SessionStatus::Success,
233 workspace_path,
234 current_task: Some(current_task),
235 parent_task,
236 siblings,
237 children,
238 recent_events: Some(recent_events),
239 suggested_commands: Some(suggested_commands),
240 stats: None,
241 recommended_task: None,
242 top_pending_tasks: None,
243 error_type: None,
244 message: None,
245 recovery_suggestion: None,
246 })
247 }
248
249 async fn restore_no_focus(
254 &self,
255 workspace_path: Option<String>,
256 ) -> Result<SessionRestoreResult> {
257 let task_mgr = TaskManager::new(self.pool);
258
259 let stats = task_mgr.get_stats().await?;
261
262 let recommendation = task_mgr.pick_next().await?;
264 let recommended_task = recommendation.task.map(|t| TaskInfo {
265 id: t.id,
266 name: t.name,
267 status: Some(t.status),
268 });
269
270 let top_pending_result = task_mgr
272 .find_tasks(
273 Some("todo"),
274 None,
275 Some(TaskSortBy::Priority),
276 Some(5),
277 None,
278 )
279 .await?;
280 let top_pending_tasks: Vec<TaskInfo> = top_pending_result
281 .tasks
282 .into_iter()
283 .map(|t| TaskInfo {
284 id: t.id,
285 name: t.name,
286 status: Some(t.status),
287 })
288 .collect();
289
290 let suggested_commands = vec![
291 "ie pick-next".to_string(),
292 "ie task list --status todo".to_string(),
293 ];
294
295 Ok(SessionRestoreResult {
296 status: SessionStatus::NoFocus,
297 workspace_path,
298 current_task: None,
299 parent_task: None,
300 siblings: None,
301 children: None,
302 recent_events: None,
303 suggested_commands: Some(suggested_commands),
304 stats: Some(stats),
305 recommended_task,
306 top_pending_tasks: if top_pending_tasks.is_empty() {
307 None
308 } else {
309 Some(top_pending_tasks)
310 },
311 error_type: None,
312 message: None,
313 recovery_suggestion: None,
314 })
315 }
316
317 fn build_siblings_info(siblings: &[crate::db::models::Task]) -> Option<SiblingsInfo> {
319 if siblings.is_empty() {
320 return None;
321 }
322
323 let done_list: Vec<TaskInfo> = siblings
324 .iter()
325 .filter(|s| s.status == "done")
326 .map(|s| TaskInfo {
327 id: s.id,
328 name: s.name.clone(),
329 status: Some(s.status.clone()),
330 })
331 .collect();
332
333 Some(SiblingsInfo {
334 total: siblings.len(),
335 done: siblings.iter().filter(|s| s.status == "done").count(),
336 doing: siblings.iter().filter(|s| s.status == "doing").count(),
337 todo: siblings.iter().filter(|s| s.status == "todo").count(),
338 done_list,
339 })
340 }
341
342 fn build_children_info(children: &[crate::db::models::Task]) -> Option<ChildrenInfo> {
344 if children.is_empty() {
345 return None;
346 }
347
348 let list: Vec<TaskInfo> = children
349 .iter()
350 .map(|c| TaskInfo {
351 id: c.id,
352 name: c.name.clone(),
353 status: Some(c.status.clone()),
354 })
355 .collect();
356
357 Some(ChildrenInfo {
358 total: children.len(),
359 todo: children.iter().filter(|c| c.status == "todo").count(),
360 list,
361 })
362 }
363
364 fn suggest_commands(
366 _current_task: &CurrentTaskInfo,
367 children: Option<&ChildrenInfo>,
368 ) -> Vec<String> {
369 let mut commands = vec![];
370
371 commands.push("ie event list --type blocker".to_string());
373
374 if let Some(children) = children {
376 if children.todo > 0 {
377 commands.push("ie task done".to_string());
378 }
379 } else {
380 commands.push("ie task done".to_string());
381 }
382
383 commands.push("ie task spawn-subtask".to_string());
384
385 commands
386 }
387
388 fn truncate_spec(spec: &str, max_len: usize) -> String {
390 if spec.len() <= max_len {
391 spec.to_string()
392 } else {
393 format!("{}...", &spec[..max_len])
394 }
395 }
396
397 fn error_result(
399 workspace_path: Option<String>,
400 error_type: ErrorType,
401 message: &str,
402 recovery: &str,
403 ) -> SessionRestoreResult {
404 let suggested_commands = match error_type {
405 ErrorType::WorkspaceNotFound => {
406 vec!["ie workspace init".to_string(), "ie help".to_string()]
407 },
408 ErrorType::DatabaseCorrupted => {
409 vec!["ie workspace init".to_string(), "ie doctor".to_string()]
410 },
411 ErrorType::PermissionDenied => {
412 vec!["chmod 644 .intent-engine/workspace.db".to_string()]
413 },
414 };
415
416 SessionRestoreResult {
417 status: SessionStatus::Error,
418 workspace_path,
419 current_task: None,
420 parent_task: None,
421 siblings: None,
422 children: None,
423 recent_events: None,
424 suggested_commands: Some(suggested_commands),
425 stats: None,
426 recommended_task: None,
427 top_pending_tasks: None,
428 error_type: Some(error_type),
429 message: Some(message.to_string()),
430 recovery_suggestion: Some(recovery.to_string()),
431 }
432 }
433}
434
435#[cfg(test)]
436mod tests {
437 use super::*;
438 use crate::events::EventManager;
439 use crate::tasks::TaskManager;
440 use crate::test_utils::test_helpers::TestContext;
441 use crate::workspace::WorkspaceManager;
442
443 #[test]
444 fn test_truncate_spec() {
445 let spec = "a".repeat(200);
446 let truncated = SessionRestoreManager::truncate_spec(&spec, 100);
447 assert_eq!(truncated.len(), 103); assert!(truncated.ends_with("..."));
449 }
450
451 #[test]
452 fn test_truncate_spec_short() {
453 let spec = "Short spec";
454 let truncated = SessionRestoreManager::truncate_spec(spec, 100);
455 assert_eq!(truncated, spec);
456 assert!(!truncated.ends_with("..."));
457 }
458
459 #[tokio::test]
460 async fn test_restore_with_focus_minimal() {
461 let ctx = TestContext::new().await;
462 let pool = ctx.pool();
463
464 let task_mgr = TaskManager::new(pool);
466 let task = task_mgr.add_task("Test task", None, None).await.unwrap();
467
468 let workspace_mgr = WorkspaceManager::new(pool);
469 workspace_mgr.set_current_task(task.id).await.unwrap();
470
471 let restore_mgr = SessionRestoreManager::new(pool);
473 let result = restore_mgr.restore(3).await.unwrap();
474
475 assert_eq!(result.status, SessionStatus::Success);
477 assert!(result.current_task.is_some());
478 let current_task = result.current_task.unwrap();
479 assert_eq!(current_task.id, task.id);
480 assert_eq!(current_task.name, "Test task");
481 }
482
483 #[tokio::test]
484 async fn test_restore_with_focus_rich_context() {
485 let ctx = TestContext::new().await;
486 let pool = ctx.pool();
487
488 let task_mgr = TaskManager::new(pool);
489 let event_mgr = EventManager::new(pool);
490 let workspace_mgr = WorkspaceManager::new(pool);
491
492 let parent = task_mgr
494 .add_task("Parent task", Some("Parent spec"), None)
495 .await
496 .unwrap();
497
498 let sibling1 = task_mgr
500 .add_task("Sibling 1", None, Some(parent.id))
501 .await
502 .unwrap();
503 task_mgr
504 .update_task(sibling1.id, None, None, None, Some("done"), None, None)
505 .await
506 .unwrap();
507
508 let current = task_mgr
509 .add_task("Current task", Some("Current spec"), Some(parent.id))
510 .await
511 .unwrap();
512 task_mgr
513 .update_task(current.id, None, None, None, Some("doing"), None, None)
514 .await
515 .unwrap();
516 workspace_mgr.set_current_task(current.id).await.unwrap();
517
518 let _sibling3 = task_mgr
519 .add_task("Sibling 3", None, Some(parent.id))
520 .await
521 .unwrap();
522
523 let _child1 = task_mgr
525 .add_task("Child 1", None, Some(current.id))
526 .await
527 .unwrap();
528 let _child2 = task_mgr
529 .add_task("Child 2", None, Some(current.id))
530 .await
531 .unwrap();
532
533 event_mgr
535 .add_event(current.id, "decision", "Decision 1")
536 .await
537 .unwrap();
538 event_mgr
539 .add_event(current.id, "blocker", "Blocker 1")
540 .await
541 .unwrap();
542 event_mgr
543 .add_event(current.id, "note", "Note 1")
544 .await
545 .unwrap();
546
547 let restore_mgr = SessionRestoreManager::new(pool);
549 let result = restore_mgr.restore(3).await.unwrap();
550
551 assert_eq!(result.status, SessionStatus::Success);
553
554 let task = result.current_task.unwrap();
555 assert_eq!(task.id, current.id);
556 assert_eq!(task.spec, Some("Current spec".to_string()));
557
558 assert!(result.parent_task.is_some());
560 let parent_info = result.parent_task.unwrap();
561 assert_eq!(parent_info.id, parent.id);
562
563 assert!(result.siblings.is_some());
565 let siblings = result.siblings.unwrap();
566 assert_eq!(siblings.total, 3);
567 assert_eq!(siblings.done, 1);
568 assert_eq!(siblings.doing, 1);
569 assert_eq!(siblings.todo, 1);
570 assert_eq!(siblings.done_list.len(), 1);
571
572 assert!(result.children.is_some());
574 let children = result.children.unwrap();
575 assert_eq!(children.total, 2);
576 assert_eq!(children.todo, 2);
577
578 assert!(result.recent_events.is_some());
580 let events = result.recent_events.unwrap();
581 assert_eq!(events.len(), 3);
582
583 let event_types: Vec<&str> = events.iter().map(|e| e.event_type.as_str()).collect();
585 assert!(event_types.contains(&"decision"));
586 assert!(event_types.contains(&"blocker"));
587 assert!(event_types.contains(&"note"));
588 }
589
590 #[tokio::test]
591 async fn test_restore_with_spec_preview() {
592 let ctx = TestContext::new().await;
593 let pool = ctx.pool();
594
595 let task_mgr = TaskManager::new(pool);
596 let workspace_mgr = WorkspaceManager::new(pool);
597
598 let long_spec = "a".repeat(200);
600 let task = task_mgr
601 .add_task("Test task", Some(&long_spec), None)
602 .await
603 .unwrap();
604 workspace_mgr.set_current_task(task.id).await.unwrap();
605
606 let restore_mgr = SessionRestoreManager::new(pool);
608 let result = restore_mgr.restore(3).await.unwrap();
609
610 let current_task = result.current_task.unwrap();
612 assert_eq!(current_task.spec, Some(long_spec));
613 assert!(current_task.spec_preview.is_some());
614 let preview = current_task.spec_preview.unwrap();
615 assert_eq!(preview.len(), 103); assert!(preview.ends_with("..."));
617 }
618
619 #[tokio::test]
620 async fn test_restore_no_focus() {
621 let ctx = TestContext::new().await;
622 let pool = ctx.pool();
623
624 let task_mgr = TaskManager::new(pool);
625
626 task_mgr.add_task("Task 1", None, None).await.unwrap();
628 task_mgr.add_task("Task 2", None, None).await.unwrap();
629
630 let restore_mgr = SessionRestoreManager::new(pool);
632 let result = restore_mgr.restore(3).await.unwrap();
633
634 assert_eq!(result.status, SessionStatus::NoFocus);
636 assert!(result.current_task.is_none());
637 assert!(result.stats.is_some());
638
639 let stats = result.stats.unwrap();
640 assert_eq!(stats.total_tasks, 2);
641 assert_eq!(stats.todo, 2);
642
643 assert!(result.recommended_task.is_some());
646
647 assert!(result.top_pending_tasks.is_some());
649 let top_pending = result.top_pending_tasks.unwrap();
650 assert_eq!(top_pending.len(), 2);
651 }
652
653 #[tokio::test]
654 async fn test_restore_recent_events_limit() {
655 let ctx = TestContext::new().await;
656 let pool = ctx.pool();
657
658 let task_mgr = TaskManager::new(pool);
659 let event_mgr = EventManager::new(pool);
660 let workspace_mgr = WorkspaceManager::new(pool);
661
662 let task = task_mgr.add_task("Test task", None, None).await.unwrap();
664 workspace_mgr.set_current_task(task.id).await.unwrap();
665
666 for i in 0..10 {
668 event_mgr
669 .add_event(task.id, "note", &format!("Event {}", i))
670 .await
671 .unwrap();
672 }
673
674 let restore_mgr = SessionRestoreManager::new(pool);
676 let result = restore_mgr.restore(3).await.unwrap();
677
678 let events = result.recent_events.unwrap();
680 assert_eq!(events.len(), 3);
681 }
682
683 #[tokio::test]
684 async fn test_restore_custom_events_limit() {
685 let ctx = TestContext::new().await;
686 let pool = ctx.pool();
687
688 let task_mgr = TaskManager::new(pool);
689 let event_mgr = EventManager::new(pool);
690 let workspace_mgr = WorkspaceManager::new(pool);
691
692 let task = task_mgr.add_task("Test task", None, None).await.unwrap();
694 workspace_mgr.set_current_task(task.id).await.unwrap();
695
696 for i in 0..10 {
698 event_mgr
699 .add_event(task.id, "note", &format!("Event {}", i))
700 .await
701 .unwrap();
702 }
703
704 let restore_mgr = SessionRestoreManager::new(pool);
706 let result = restore_mgr.restore(5).await.unwrap();
707
708 let events = result.recent_events.unwrap();
710 assert_eq!(events.len(), 5);
711 }
712
713 #[test]
714 fn test_suggest_commands_with_children() {
715 let current_task = CurrentTaskInfo {
716 id: 1,
717 name: "Test".to_string(),
718 status: "doing".to_string(),
719 spec: None,
720 spec_preview: None,
721 created_at: None,
722 first_doing_at: None,
723 };
724
725 let children = Some(ChildrenInfo {
726 total: 2,
727 todo: 1,
728 list: vec![],
729 });
730
731 let commands = SessionRestoreManager::suggest_commands(¤t_task, children.as_ref());
732
733 assert!(!commands.is_empty());
734 assert!(commands.iter().any(|c| c.contains("blocker")));
735 }
736
737 #[test]
738 fn test_error_result_workspace_not_found() {
739 let result = SessionRestoreManager::error_result(
740 Some("/test/path".to_string()),
741 ErrorType::WorkspaceNotFound,
742 "Test message",
743 "Test recovery",
744 );
745
746 assert_eq!(result.status, SessionStatus::Error);
747 assert_eq!(result.error_type, Some(ErrorType::WorkspaceNotFound));
748 assert_eq!(result.message, Some("Test message".to_string()));
749 assert_eq!(
750 result.recovery_suggestion,
751 Some("Test recovery".to_string())
752 );
753 assert!(result.suggested_commands.is_some());
754
755 let commands = result.suggested_commands.unwrap();
756 assert!(commands.iter().any(|c| c.contains("init")));
757 }
758
759 #[test]
760 fn test_build_siblings_info_empty() {
761 let siblings: Vec<crate::db::models::Task> = vec![];
762 let result = SessionRestoreManager::build_siblings_info(&siblings);
763 assert!(result.is_none());
764 }
765
766 #[test]
767 fn test_build_children_info_empty() {
768 let children: Vec<crate::db::models::Task> = vec![];
769 let result = SessionRestoreManager::build_children_info(&children);
770 assert!(result.is_none());
771 }
772}