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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;

/// Custom date serialization module - formats to seconds precision
mod datetime_format {
    use chrono::{DateTime, Utc};
    use serde::{self, Deserialize, Deserializer, Serializer};

    const FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";

    pub fn serialize<S>(date: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let s = date.format(FORMAT).to_string();
        serializer.serialize_str(&s)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        // Try parsing with our format first, then fall back to RFC 3339
        DateTime::parse_from_str(&s, FORMAT)
            .map(|dt| dt.with_timezone(&Utc))
            .or_else(|_| DateTime::parse_from_rfc3339(&s).map(|dt| dt.with_timezone(&Utc)))
            .map_err(serde::de::Error::custom)
    }
}

/// Custom date serialization for `Option<DateTime<Utc>>`
mod option_datetime_format {
    use chrono::{DateTime, Utc};
    use serde::{self, Deserialize, Deserializer, Serializer};

    const FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";

    pub fn serialize<S>(date: &Option<DateTime<Utc>>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match date {
            Some(dt) => {
                let s = dt.format(FORMAT).to_string();
                serializer.serialize_some(&s)
            },
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<DateTime<Utc>>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt: Option<String> = Option::deserialize(deserializer)?;
        match opt {
            Some(s) => DateTime::parse_from_str(&s, FORMAT)
                .map(|dt| Some(dt.with_timezone(&Utc)))
                .or_else(|_| {
                    DateTime::parse_from_rfc3339(&s).map(|dt| Some(dt.with_timezone(&Utc)))
                })
                .map_err(serde::de::Error::custom),
            None => Ok(None),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct Dependency {
    pub id: i64,
    pub blocking_task_id: i64,
    pub blocked_task_id: i64,
    #[serde(with = "datetime_format")]
    pub created_at: DateTime<Utc>,
}

/// Task approval record for human task authorization
/// AI must provide the passphrase to complete a human-owned task
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct TaskApproval {
    pub id: i64,
    pub task_id: i64,
    pub passphrase: String,
    #[serde(with = "datetime_format")]
    pub created_at: DateTime<Utc>,
    #[serde(with = "option_datetime_format")]
    pub expires_at: Option<DateTime<Utc>>,
}

/// Response for creating a task approval
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApprovalResponse {
    pub task_id: i64,
    pub passphrase: String,
    #[serde(
        skip_serializing_if = "Option::is_none",
        with = "option_datetime_format"
    )]
    pub expires_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, FromRow, PartialEq)]
pub struct Task {
    pub id: i64,
    pub parent_id: Option<i64>,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub spec: Option<String>,
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub complexity: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<i32>,
    #[serde(with = "option_datetime_format")]
    pub first_todo_at: Option<DateTime<Utc>>,
    #[serde(with = "option_datetime_format")]
    pub first_doing_at: Option<DateTime<Utc>>,
    #[serde(with = "option_datetime_format")]
    pub first_done_at: Option<DateTime<Utc>>,
    /// Present progressive form for UI display when task is in_progress
    /// Example: "Implementing authentication" vs "Implement authentication"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_form: Option<String>,
    /// Task owner: identifies who created the task (e.g. 'human', 'ai', or any custom string)
    #[serde(default = "default_owner")]
    pub owner: String,
    /// Free-form metadata JSON string for extensibility
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<String>,
}

fn default_owner() -> String {
    "human".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TaskWithEvents {
    #[serde(flatten)]
    pub task: Task,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub events_summary: Option<EventsSummary>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EventsSummary {
    pub total_count: i64,
    pub recent_events: Vec<Event>,
}

#[derive(Debug, Clone, Serialize, Deserialize, FromRow, PartialEq)]
pub struct Event {
    pub id: i64,
    pub task_id: i64,
    #[serde(with = "datetime_format")]
    pub timestamp: DateTime<Utc>,
    pub log_type: String,
    pub discussion_data: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct WorkspaceState {
    pub key: String,
    pub value: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Report {
    pub summary: ReportSummary,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tasks: Option<Vec<Task>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub events: Option<Vec<Event>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReportSummary {
    pub total_tasks: i64,
    pub tasks_by_status: StatusBreakdown,
    pub total_events: i64,
    pub date_range: Option<DateRange>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatusBreakdown {
    pub todo: i64,
    pub doing: i64,
    pub done: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DateRange {
    #[serde(with = "datetime_format")]
    pub from: DateTime<Utc>,
    #[serde(with = "datetime_format")]
    pub to: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DoneTaskResponse {
    pub completed_task: Task,
    pub workspace_status: WorkspaceStatus,
    pub next_step_suggestion: NextStepSuggestion,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceStatus {
    pub current_task_id: Option<i64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum NextStepSuggestion {
    #[serde(rename = "PARENT_IS_READY")]
    ParentIsReady {
        message: String,
        parent_task_id: i64,
        parent_task_name: String,
    },
    #[serde(rename = "SIBLING_TASKS_REMAIN")]
    SiblingTasksRemain {
        message: String,
        parent_task_id: i64,
        parent_task_name: String,
        remaining_siblings_count: i64,
    },
    #[serde(rename = "TOP_LEVEL_TASK_COMPLETED")]
    TopLevelTaskCompleted {
        message: String,
        completed_task_id: i64,
        completed_task_name: String,
    },
    #[serde(rename = "NO_PARENT_CONTEXT")]
    NoParentContext {
        message: String,
        completed_task_id: i64,
        completed_task_name: String,
    },
    #[serde(rename = "WORKSPACE_IS_CLEAR")]
    WorkspaceIsClear {
        message: String,
        completed_task_id: i64,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskSearchResult {
    #[serde(flatten)]
    pub task: Task,
    pub match_snippet: String,
}

/// Unified search result that can represent either a task or event match
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "result_type")]
pub enum SearchResult {
    #[serde(rename = "task")]
    Task {
        #[serde(flatten)]
        task: Task,
        match_snippet: String,
        match_field: String, // "name" or "spec"
    },
    #[serde(rename = "event")]
    Event {
        event: Event,
        task_chain: Vec<Task>, // Ancestry: [immediate task, parent, grandparent, ...]
        match_snippet: String,
    },
}

/// Paginated search results across tasks and events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaginatedSearchResults {
    pub results: Vec<SearchResult>,
    pub total_tasks: i64,
    pub total_events: i64,
    pub has_more: bool,
    pub limit: i64,
    pub offset: i64,
}

/// Response for spawn-subtask command - includes subtask and parent info
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpawnSubtaskResponse {
    pub subtask: SubtaskInfo,
    pub parent_task: ParentTaskInfo,
}

/// Subtask info for spawn response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubtaskInfo {
    pub id: i64,
    pub name: String,
    pub parent_id: i64,
    pub status: String,
}

/// Parent task info for spawn response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParentTaskInfo {
    pub id: i64,
    pub name: String,
}

/// Dependency information for a task
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskDependencies {
    /// Tasks that must be completed before this task can start
    pub blocking_tasks: Vec<Task>,
    /// Tasks that are blocked by this task
    pub blocked_by_tasks: Vec<Task>,
}

/// Response for task_context - provides the complete family tree of a task
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskContext {
    pub task: Task,
    pub ancestors: Vec<Task>,
    pub siblings: Vec<Task>,
    pub children: Vec<Task>,
    pub dependencies: TaskDependencies,
}

/// Sort order for task queries
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskSortBy {
    /// Legacy: ORDER BY id ASC (backward compatible)
    Id,
    /// ORDER BY priority ASC, complexity ASC, id ASC
    Priority,
    /// ORDER BY first_doing_at DESC NULLS LAST, first_todo_at DESC NULLS LAST, id ASC
    Time,
    /// Focus-aware: current focused task → doing tasks → todo tasks
    #[default]
    FocusAware,
}

/// Paginated task query results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaginatedTasks {
    pub tasks: Vec<Task>,
    pub total_count: i64,
    pub has_more: bool,
    pub limit: i64,
    pub offset: i64,
}

/// Workspace statistics (aggregated counts without loading tasks)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceStats {
    pub total_tasks: i64,
    pub todo: i64,
    pub doing: i64,
    pub done: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PickNextResponse {
    pub suggestion_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task: Option<Task>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason_code: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl PickNextResponse {
    /// Create a response for focused subtask suggestion
    pub fn focused_subtask(task: Task) -> Self {
        Self {
            suggestion_type: "FOCUSED_SUB_TASK".to_string(),
            task: Some(task),
            reason_code: None,
            message: None,
        }
    }

    /// Create a response for top-level task suggestion
    pub fn top_level_task(task: Task) -> Self {
        Self {
            suggestion_type: "TOP_LEVEL_TASK".to_string(),
            task: Some(task),
            reason_code: None,
            message: None,
        }
    }

    /// Create a response for no tasks in project
    pub fn no_tasks_in_project() -> Self {
        Self {
            suggestion_type: "NONE".to_string(),
            task: None,
            reason_code: Some("NO_TASKS_IN_PROJECT".to_string()),
            message: Some(
                "No tasks found in this project. Your intent backlog is empty.".to_string(),
            ),
        }
    }

    /// Create a response for all tasks completed
    pub fn all_tasks_completed() -> Self {
        Self {
            suggestion_type: "NONE".to_string(),
            task: None,
            reason_code: Some("ALL_TASKS_COMPLETED".to_string()),
            message: Some("Project Complete! All intents have been realized.".to_string()),
        }
    }

    /// Create a response for no available todos
    pub fn no_available_todos() -> Self {
        Self {
            suggestion_type: "NONE".to_string(),
            task: None,
            reason_code: Some("NO_AVAILABLE_TODOS".to_string()),
            message: Some("No immediate next task found based on the current context.".to_string()),
        }
    }

    /// Format response as human-readable text
    pub fn format_as_text(&self) -> String {
        match self.suggestion_type.as_str() {
            "FOCUSED_SUB_TASK" | "TOP_LEVEL_TASK" => {
                if let Some(task) = &self.task {
                    format!(
                        "Based on your current focus, the recommended next task is:\n\n\
                        [ID: {}] [Priority: {}] [Status: {}]\n\
                        Name: {}\n\n\
                        To start working on it, run:\n  ie task start {}",
                        task.id,
                        task.priority.unwrap_or(0),
                        task.status,
                        task.name,
                        task.id
                    )
                } else {
                    "[ERROR] Invalid response: task is missing".to_string()
                }
            },
            "NONE" => {
                let reason_code = self.reason_code.as_deref().unwrap_or("UNKNOWN");
                let message = self.message.as_deref().unwrap_or("No tasks found");

                match reason_code {
                    "NO_TASKS_IN_PROJECT" => {
                        format!(
                            "[INFO] {}\n\n\
                            To get started, capture your first high-level intent:\n  \
                            ie task add --name \"Setup initial project structure\" --priority 1",
                            message
                        )
                    },
                    "ALL_TASKS_COMPLETED" => {
                        format!(
                            "[SUCCESS] {}\n\n\
                            You can review the accomplishments of the last 30 days with:\n  \
                            ie report --since 30d",
                            message
                        )
                    },
                    "NO_AVAILABLE_TODOS" => {
                        format!(
                            "[INFO] {}\n\n\
                            Possible reasons:\n\
                            - All available 'todo' tasks are part of larger epics that have not been started yet.\n\
                            - You are not currently focused on a task that has 'todo' sub-tasks.\n\n\
                            To see all available top-level tasks you can start, run:\n  \
                            ie task find --parent NULL --status todo",
                            message
                        )
                    },
                    _ => format!("[INFO] {}", message),
                }
            },
            _ => "[ERROR] Unknown suggestion type".to_string(),
        }
    }
}

/// Simplified task info for siblings/descendants in status response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskBrief {
    pub id: i64,
    pub name: String,
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<i64>,
    /// Whether the task has a non-empty spec/description
    #[serde(default)]
    pub has_spec: bool,
}

impl From<&Task> for TaskBrief {
    fn from(task: &Task) -> Self {
        Self {
            id: task.id,
            name: task.name.clone(),
            status: task.status.clone(),
            parent_id: task.parent_id,
            has_spec: task
                .spec
                .as_ref()
                .map(|s| !s.trim().is_empty())
                .unwrap_or(false),
        }
    }
}

/// Response for ie status command - the "spotlight" view of a task
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatusResponse {
    /// The focused task with full details
    pub focused_task: Task,
    /// Ancestor chain from immediate parent to root (full details)
    pub ancestors: Vec<Task>,
    /// Sibling tasks (id + name + status)
    pub siblings: Vec<TaskBrief>,
    /// All descendant tasks recursively (id + name + status + parent_id)
    pub descendants: Vec<TaskBrief>,
    /// Optional event history
    #[serde(skip_serializing_if = "Option::is_none")]
    pub events: Option<Vec<Event>>,
}

/// Response when no task is focused
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NoFocusResponse {
    pub message: String,
    /// Root-level tasks (no parent)
    pub root_tasks: Vec<TaskBrief>,
}

/// LLM-generated suggestion for background analysis
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct Suggestion {
    pub id: i64,
    #[serde(rename = "type")]
    #[sqlx(rename = "type")]
    pub suggestion_type: String,
    pub content: String,
    #[serde(with = "datetime_format")]
    pub created_at: DateTime<Utc>,
    pub dismissed: bool,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_task(id: i64, name: &str, priority: Option<i32>) -> Task {
        Task {
            id,
            parent_id: None,
            name: name.to_string(),
            spec: None,
            status: "todo".to_string(),
            complexity: None,
            priority,
            first_todo_at: None,
            first_doing_at: None,
            first_done_at: None,
            active_form: None,
            owner: "human".to_string(),
            metadata: None,
        }
    }

    #[test]
    fn test_pick_next_response_focused_subtask() {
        let task = create_test_task(1, "Test task", Some(5));
        let response = PickNextResponse::focused_subtask(task.clone());

        assert_eq!(response.suggestion_type, "FOCUSED_SUB_TASK");
        assert!(response.task.is_some());
        assert_eq!(response.task.unwrap().id, 1);
        assert!(response.reason_code.is_none());
        assert!(response.message.is_none());
    }

    #[test]
    fn test_pick_next_response_top_level_task() {
        let task = create_test_task(2, "Top level task", Some(3));
        let response = PickNextResponse::top_level_task(task.clone());

        assert_eq!(response.suggestion_type, "TOP_LEVEL_TASK");
        assert!(response.task.is_some());
        assert_eq!(response.task.unwrap().id, 2);
        assert!(response.reason_code.is_none());
        assert!(response.message.is_none());
    }

    #[test]
    fn test_pick_next_response_no_tasks_in_project() {
        let response = PickNextResponse::no_tasks_in_project();

        assert_eq!(response.suggestion_type, "NONE");
        assert!(response.task.is_none());
        assert_eq!(response.reason_code.as_deref(), Some("NO_TASKS_IN_PROJECT"));
        assert!(response.message.is_some());
        assert!(response.message.unwrap().contains("No tasks found"));
    }

    #[test]
    fn test_pick_next_response_all_tasks_completed() {
        let response = PickNextResponse::all_tasks_completed();

        assert_eq!(response.suggestion_type, "NONE");
        assert!(response.task.is_none());
        assert_eq!(response.reason_code.as_deref(), Some("ALL_TASKS_COMPLETED"));
        assert!(response.message.is_some());
        assert!(response.message.unwrap().contains("Project Complete"));
    }

    #[test]
    fn test_pick_next_response_no_available_todos() {
        let response = PickNextResponse::no_available_todos();

        assert_eq!(response.suggestion_type, "NONE");
        assert!(response.task.is_none());
        assert_eq!(response.reason_code.as_deref(), Some("NO_AVAILABLE_TODOS"));
        assert!(response.message.is_some());
    }

    #[test]
    fn test_format_as_text_focused_subtask() {
        let task = create_test_task(1, "Test task", Some(5));
        let response = PickNextResponse::focused_subtask(task);
        let text = response.format_as_text();

        assert!(text.contains("Based on your current focus"));
        assert!(text.contains("[ID: 1]"));
        assert!(text.contains("[Priority: 5]"));
        assert!(text.contains("Test task"));
        assert!(text.contains("ie task start 1"));
    }

    #[test]
    fn test_format_as_text_top_level_task() {
        let task = create_test_task(2, "Top level task", None);
        let response = PickNextResponse::top_level_task(task);
        let text = response.format_as_text();

        assert!(text.contains("Based on your current focus"));
        assert!(text.contains("[ID: 2]"));
        assert!(text.contains("[Priority: 0]")); // Default priority
        assert!(text.contains("Top level task"));
        assert!(text.contains("ie task start 2"));
    }

    #[test]
    fn test_format_as_text_no_tasks_in_project() {
        let response = PickNextResponse::no_tasks_in_project();
        let text = response.format_as_text();

        assert!(text.contains("[INFO]"));
        assert!(text.contains("No tasks found"));
        assert!(text.contains("ie task add"));
        assert!(text.contains("--priority 1"));
    }

    #[test]
    fn test_format_as_text_all_tasks_completed() {
        let response = PickNextResponse::all_tasks_completed();
        let text = response.format_as_text();

        assert!(text.contains("[SUCCESS]"));
        assert!(text.contains("Project Complete"));
        assert!(text.contains("ie report --since 30d"));
    }

    #[test]
    fn test_format_as_text_no_available_todos() {
        let response = PickNextResponse::no_available_todos();
        let text = response.format_as_text();

        assert!(text.contains("[INFO]"));
        assert!(text.contains("No immediate next task"));
        assert!(text.contains("Possible reasons"));
        assert!(text.contains("ie task find"));
    }

    #[test]
    fn test_error_response_serialization() {
        use crate::error::IntentError;

        let error = IntentError::TaskNotFound(123);
        let response = error.to_error_response();

        assert_eq!(response.code, "TASK_NOT_FOUND");
        assert!(response.error.contains("123"));
    }

    #[test]
    fn test_next_step_suggestion_serialization() {
        let suggestion = NextStepSuggestion::ParentIsReady {
            message: "Test message".to_string(),
            parent_task_id: 1,
            parent_task_name: "Parent".to_string(),
        };

        let json = serde_json::to_string(&suggestion).unwrap();
        assert!(json.contains("\"type\":\"PARENT_IS_READY\""));
        assert!(json.contains("parent_task_id"));
    }

    #[test]
    fn test_task_with_events_serialization() {
        let task = create_test_task(1, "Test", Some(5));
        let task_with_events = TaskWithEvents {
            task,
            events_summary: None,
        };

        let json = serde_json::to_string(&task_with_events).unwrap();
        assert!(json.contains("\"id\":1"));
        assert!(json.contains("\"name\":\"Test\""));
        // events_summary should be skipped when None
        assert!(!json.contains("events_summary"));
    }

    #[test]
    fn test_report_summary_with_date_range() {
        let from = Utc::now() - chrono::Duration::days(7);
        let to = Utc::now();

        let summary = ReportSummary {
            total_tasks: 10,
            tasks_by_status: StatusBreakdown {
                todo: 5,
                doing: 3,
                done: 2,
            },
            total_events: 20,
            date_range: Some(DateRange { from, to }),
        };

        let json = serde_json::to_string(&summary).unwrap();
        assert!(json.contains("\"total_tasks\":10"));
        assert!(json.contains("\"total_events\":20"));
        assert!(json.contains("date_range"));
    }
}