scud/models/
task.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
4#[serde(rename_all = "kebab-case")]
5pub enum TaskStatus {
6    #[default]
7    Pending,
8    InProgress,
9    Done,
10    Review,
11    Blocked,
12    Deferred,
13    Cancelled,
14    Expanded, // Task has been broken into subtasks
15}
16
17impl TaskStatus {
18    pub fn as_str(&self) -> &'static str {
19        match self {
20            TaskStatus::Pending => "pending",
21            TaskStatus::InProgress => "in-progress",
22            TaskStatus::Done => "done",
23            TaskStatus::Review => "review",
24            TaskStatus::Blocked => "blocked",
25            TaskStatus::Deferred => "deferred",
26            TaskStatus::Cancelled => "cancelled",
27            TaskStatus::Expanded => "expanded",
28        }
29    }
30
31    #[allow(clippy::should_implement_trait)]
32    pub fn from_str(s: &str) -> Option<Self> {
33        match s {
34            "pending" => Some(TaskStatus::Pending),
35            "in-progress" => Some(TaskStatus::InProgress),
36            "done" => Some(TaskStatus::Done),
37            "review" => Some(TaskStatus::Review),
38            "blocked" => Some(TaskStatus::Blocked),
39            "deferred" => Some(TaskStatus::Deferred),
40            "cancelled" => Some(TaskStatus::Cancelled),
41            "expanded" => Some(TaskStatus::Expanded),
42            _ => None,
43        }
44    }
45
46    pub fn all() -> Vec<&'static str> {
47        vec![
48            "pending",
49            "in-progress",
50            "done",
51            "review",
52            "blocked",
53            "deferred",
54            "cancelled",
55            "expanded",
56        ]
57    }
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
61#[serde(rename_all = "lowercase")]
62pub enum Priority {
63    Critical,
64    High,
65    #[default]
66    Medium,
67    Low,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct Task {
72    pub id: String,
73    pub title: String,
74    pub description: String,
75
76    #[serde(default)]
77    pub status: TaskStatus,
78
79    #[serde(default)]
80    pub complexity: u32,
81
82    #[serde(default)]
83    pub priority: Priority,
84
85    #[serde(default)]
86    pub dependencies: Vec<String>,
87
88    // Parent-child relationship for expanded tasks
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub parent_id: Option<String>,
91
92    #[serde(default, skip_serializing_if = "Vec::is_empty")]
93    pub subtasks: Vec<String>,
94
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub details: Option<String>,
97
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub test_strategy: Option<String>,
100
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub created_at: Option<String>,
103
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub updated_at: Option<String>,
106
107    // Assignment tracking (informational only, no locking)
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub assigned_to: Option<String>,
110}
111
112impl Task {
113    // Validation constants
114    const MAX_TITLE_LENGTH: usize = 200;
115    const MAX_DESCRIPTION_LENGTH: usize = 5000;
116    const VALID_FIBONACCI_NUMBERS: &'static [u32] = &[0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89];
117
118    /// ID separator for namespaced IDs (epic:local_id)
119    pub const ID_SEPARATOR: char = ':';
120
121    pub fn new(id: String, title: String, description: String) -> Self {
122        let now = chrono::Utc::now().to_rfc3339();
123        Task {
124            id,
125            title,
126            description,
127            status: TaskStatus::Pending,
128            complexity: 0,
129            priority: Priority::Medium,
130            dependencies: Vec::new(),
131            parent_id: None,
132            subtasks: Vec::new(),
133            details: None,
134            test_strategy: None,
135            created_at: Some(now.clone()),
136            updated_at: Some(now),
137            assigned_to: None,
138        }
139    }
140
141    /// Parse a task ID into (epic_tag, local_id) parts
142    /// e.g., "phase1:10.1" -> Some(("phase1", "10.1"))
143    /// e.g., "10.1" -> None (legacy format)
144    pub fn parse_id(id: &str) -> Option<(&str, &str)> {
145        id.split_once(Self::ID_SEPARATOR)
146    }
147
148    /// Create a namespaced task ID
149    pub fn make_id(epic_tag: &str, local_id: &str) -> String {
150        format!("{}{}{}", epic_tag, Self::ID_SEPARATOR, local_id)
151    }
152
153    /// Get the local ID part (without epic prefix)
154    pub fn local_id(&self) -> &str {
155        Self::parse_id(&self.id)
156            .map(|(_, local)| local)
157            .unwrap_or(&self.id)
158    }
159
160    /// Get the epic tag from a namespaced ID
161    pub fn epic_tag(&self) -> Option<&str> {
162        Self::parse_id(&self.id).map(|(tag, _)| tag)
163    }
164
165    /// Check if this is a subtask (has parent)
166    pub fn is_subtask(&self) -> bool {
167        self.parent_id.is_some()
168    }
169
170    /// Check if this task has been expanded into subtasks
171    pub fn is_expanded(&self) -> bool {
172        self.status == TaskStatus::Expanded || !self.subtasks.is_empty()
173    }
174
175    /// Validate task ID - must contain only alphanumeric characters, hyphens, underscores,
176    /// colons (for namespacing), and dots (for subtask IDs)
177    pub fn validate_id(id: &str) -> Result<(), String> {
178        if id.is_empty() {
179            return Err("Task ID cannot be empty".to_string());
180        }
181
182        if id.len() > 100 {
183            return Err("Task ID too long (max 100 characters)".to_string());
184        }
185
186        // Allow alphanumeric, hyphen, underscore, colon (namespacing), and dot (subtask IDs)
187        let valid_chars = id
188            .chars()
189            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == ':' || c == '.');
190
191        if !valid_chars {
192            return Err(
193                "Task ID can only contain alphanumeric characters, hyphens, underscores, colons, and dots"
194                    .to_string(),
195            );
196        }
197
198        Ok(())
199    }
200
201    /// Validate title - must not be empty and within length limit
202    pub fn validate_title(title: &str) -> Result<(), String> {
203        if title.trim().is_empty() {
204            return Err("Task title cannot be empty".to_string());
205        }
206
207        if title.len() > Self::MAX_TITLE_LENGTH {
208            return Err(format!(
209                "Task title too long (max {} characters)",
210                Self::MAX_TITLE_LENGTH
211            ));
212        }
213
214        Ok(())
215    }
216
217    /// Validate description - within length limit
218    pub fn validate_description(description: &str) -> Result<(), String> {
219        if description.len() > Self::MAX_DESCRIPTION_LENGTH {
220            return Err(format!(
221                "Task description too long (max {} characters)",
222                Self::MAX_DESCRIPTION_LENGTH
223            ));
224        }
225
226        Ok(())
227    }
228
229    /// Validate complexity - must be a Fibonacci number
230    pub fn validate_complexity(complexity: u32) -> Result<(), String> {
231        if !Self::VALID_FIBONACCI_NUMBERS.contains(&complexity) {
232            return Err(format!(
233                "Complexity must be a Fibonacci number: {:?}",
234                Self::VALID_FIBONACCI_NUMBERS
235            ));
236        }
237
238        Ok(())
239    }
240
241    /// Sanitize text by removing potentially dangerous HTML/script tags
242    pub fn sanitize_text(text: &str) -> String {
243        text.replace('<', "&lt;")
244            .replace('>', "&gt;")
245            .replace('"', "&quot;")
246            .replace('\'', "&#x27;")
247    }
248
249    /// Comprehensive validation of all task fields
250    pub fn validate(&self) -> Result<(), Vec<String>> {
251        let mut errors = Vec::new();
252
253        if let Err(e) = Self::validate_id(&self.id) {
254            errors.push(e);
255        }
256
257        if let Err(e) = Self::validate_title(&self.title) {
258            errors.push(e);
259        }
260
261        if let Err(e) = Self::validate_description(&self.description) {
262            errors.push(e);
263        }
264
265        if self.complexity > 0 {
266            if let Err(e) = Self::validate_complexity(self.complexity) {
267                errors.push(e);
268            }
269        }
270
271        if errors.is_empty() {
272            Ok(())
273        } else {
274            Err(errors)
275        }
276    }
277
278    pub fn set_status(&mut self, status: TaskStatus) {
279        self.status = status;
280        self.updated_at = Some(chrono::Utc::now().to_rfc3339());
281    }
282
283    pub fn update(&mut self) {
284        self.updated_at = Some(chrono::Utc::now().to_rfc3339());
285    }
286
287    pub fn has_dependencies_met(&self, all_tasks: &[Task]) -> bool {
288        self.dependencies.iter().all(|dep_id| {
289            all_tasks
290                .iter()
291                .find(|t| &t.id == dep_id)
292                .map(|t| t.status == TaskStatus::Done)
293                .unwrap_or(false)
294        })
295    }
296
297    /// Check if all dependencies are met, searching across provided task references
298    /// Supports cross-tag dependencies when passed tasks from all phases
299    pub fn has_dependencies_met_refs(&self, all_tasks: &[&Task]) -> bool {
300        self.dependencies.iter().all(|dep_id| {
301            all_tasks
302                .iter()
303                .find(|t| &t.id == dep_id)
304                .map(|t| t.status == TaskStatus::Done)
305                .unwrap_or(false)
306        })
307    }
308
309    /// Returns whether this task should be expanded into subtasks
310    /// Only tasks with complexity >= 5 benefit from expansion
311    /// Subtasks and already-expanded tasks don't need expansion
312    pub fn needs_expansion(&self) -> bool {
313        self.complexity >= 5 && !self.is_expanded() && !self.is_subtask()
314    }
315
316    /// Returns the recommended number of subtasks based on complexity
317    /// Complexity 0-3: 0 subtasks (trivial/simple, no expansion needed)
318    /// Complexity 5-8: 2 broad, multi-step subtasks
319    /// Complexity 13+: 3 broad, multi-step subtasks
320    pub fn recommended_subtasks(&self) -> usize {
321        Self::recommended_subtasks_for_complexity(self.complexity)
322    }
323
324    /// Static version for use when we only have complexity value
325    pub fn recommended_subtasks_for_complexity(complexity: u32) -> usize {
326        match complexity {
327            0..=3 => 0, // Trivial/simple tasks: no expansion needed
328            5 => 2,     // Moderate tasks: 2 broad subtasks
329            8 => 2,     // Complex tasks: 2 broad subtasks
330            13 => 3,    // Very complex: 3 broad subtasks
331            _ => 3,     // Extremely complex (21+): 3 broad subtasks max
332        }
333    }
334
335    // Assignment methods (informational only, no locking)
336    pub fn assign(&mut self, assignee: &str) {
337        self.assigned_to = Some(assignee.to_string());
338        self.update();
339    }
340
341    pub fn is_assigned_to(&self, assignee: &str) -> bool {
342        self.assigned_to
343            .as_ref()
344            .map(|s| s == assignee)
345            .unwrap_or(false)
346    }
347
348    /// Check if adding a dependency would create a circular reference
349    /// Returns Err with the cycle path if circular dependency detected
350    pub fn would_create_cycle(&self, new_dep_id: &str, all_tasks: &[Task]) -> Result<(), String> {
351        if self.id == new_dep_id {
352            return Err(format!("Self-reference: {} -> {}", self.id, new_dep_id));
353        }
354
355        let mut visited = std::collections::HashSet::new();
356        let mut path = Vec::new();
357
358        Self::detect_cycle_recursive(new_dep_id, &self.id, all_tasks, &mut visited, &mut path)
359    }
360
361    fn detect_cycle_recursive(
362        current_id: &str,
363        target_id: &str,
364        all_tasks: &[Task],
365        visited: &mut std::collections::HashSet<String>,
366        path: &mut Vec<String>,
367    ) -> Result<(), String> {
368        if current_id == target_id {
369            path.push(current_id.to_string());
370            return Err(format!("Circular dependency: {}", path.join(" -> ")));
371        }
372
373        if visited.contains(current_id) {
374            return Ok(());
375        }
376
377        visited.insert(current_id.to_string());
378        path.push(current_id.to_string());
379
380        if let Some(task) = all_tasks.iter().find(|t| t.id == current_id) {
381            for dep_id in &task.dependencies {
382                Self::detect_cycle_recursive(dep_id, target_id, all_tasks, visited, path)?;
383            }
384        }
385
386        path.pop();
387        Ok(())
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394
395    #[test]
396    fn test_task_creation() {
397        let task = Task::new(
398            "TASK-1".to_string(),
399            "Test Task".to_string(),
400            "Description".to_string(),
401        );
402
403        assert_eq!(task.id, "TASK-1");
404        assert_eq!(task.title, "Test Task");
405        assert_eq!(task.description, "Description");
406        assert_eq!(task.status, TaskStatus::Pending);
407        assert_eq!(task.complexity, 0);
408        assert_eq!(task.priority, Priority::Medium);
409        assert!(task.dependencies.is_empty());
410        assert!(task.created_at.is_some());
411        assert!(task.updated_at.is_some());
412        assert!(task.assigned_to.is_none());
413    }
414
415    #[test]
416    fn test_status_conversion() {
417        assert_eq!(TaskStatus::Pending.as_str(), "pending");
418        assert_eq!(TaskStatus::InProgress.as_str(), "in-progress");
419        assert_eq!(TaskStatus::Done.as_str(), "done");
420        assert_eq!(TaskStatus::Review.as_str(), "review");
421        assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
422        assert_eq!(TaskStatus::Deferred.as_str(), "deferred");
423        assert_eq!(TaskStatus::Cancelled.as_str(), "cancelled");
424    }
425
426    #[test]
427    fn test_status_from_string() {
428        assert_eq!(TaskStatus::from_str("pending"), Some(TaskStatus::Pending));
429        assert_eq!(
430            TaskStatus::from_str("in-progress"),
431            Some(TaskStatus::InProgress)
432        );
433        assert_eq!(TaskStatus::from_str("done"), Some(TaskStatus::Done));
434        assert_eq!(TaskStatus::from_str("invalid"), None);
435    }
436
437    #[test]
438    fn test_set_status_updates_timestamp() {
439        let mut task = Task::new("TASK-1".to_string(), "Test".to_string(), "Desc".to_string());
440        let initial_updated = task.updated_at.clone();
441
442        std::thread::sleep(std::time::Duration::from_millis(10));
443        task.set_status(TaskStatus::InProgress);
444
445        assert_eq!(task.status, TaskStatus::InProgress);
446        assert!(task.updated_at > initial_updated);
447    }
448
449    #[test]
450    fn test_task_assignment() {
451        let mut task = Task::new("TASK-1".to_string(), "Test".to_string(), "Desc".to_string());
452
453        task.assign("alice");
454        assert_eq!(task.assigned_to, Some("alice".to_string()));
455        assert!(task.is_assigned_to("alice"));
456        assert!(!task.is_assigned_to("bob"));
457    }
458
459    #[test]
460    fn test_has_dependencies_met_all_done() {
461        let mut task = Task::new("TASK-3".to_string(), "Test".to_string(), "Desc".to_string());
462        task.dependencies = vec!["TASK-1".to_string(), "TASK-2".to_string()];
463
464        let mut task1 = Task::new(
465            "TASK-1".to_string(),
466            "Dep 1".to_string(),
467            "Desc".to_string(),
468        );
469        task1.set_status(TaskStatus::Done);
470
471        let mut task2 = Task::new(
472            "TASK-2".to_string(),
473            "Dep 2".to_string(),
474            "Desc".to_string(),
475        );
476        task2.set_status(TaskStatus::Done);
477
478        let all_tasks = vec![task1, task2];
479        assert!(task.has_dependencies_met(&all_tasks));
480    }
481
482    #[test]
483    fn test_has_dependencies_met_some_pending() {
484        let mut task = Task::new("TASK-3".to_string(), "Test".to_string(), "Desc".to_string());
485        task.dependencies = vec!["TASK-1".to_string(), "TASK-2".to_string()];
486
487        let mut task1 = Task::new(
488            "TASK-1".to_string(),
489            "Dep 1".to_string(),
490            "Desc".to_string(),
491        );
492        task1.set_status(TaskStatus::Done);
493
494        let task2 = Task::new(
495            "TASK-2".to_string(),
496            "Dep 2".to_string(),
497            "Desc".to_string(),
498        );
499        // task2 is pending
500
501        let all_tasks = vec![task1, task2];
502        assert!(!task.has_dependencies_met(&all_tasks));
503    }
504
505    #[test]
506    fn test_has_dependencies_met_missing_dependency() {
507        let mut task = Task::new("TASK-3".to_string(), "Test".to_string(), "Desc".to_string());
508        task.dependencies = vec!["TASK-1".to_string(), "TASK-MISSING".to_string()];
509
510        let mut task1 = Task::new(
511            "TASK-1".to_string(),
512            "Dep 1".to_string(),
513            "Desc".to_string(),
514        );
515        task1.set_status(TaskStatus::Done);
516
517        let all_tasks = vec![task1];
518        assert!(!task.has_dependencies_met(&all_tasks));
519    }
520
521    #[test]
522    fn test_needs_expansion() {
523        let mut task = Task::new("TASK-1".to_string(), "Test".to_string(), "Desc".to_string());
524
525        // Complexity < 5 should not need expansion
526        task.complexity = 1;
527        assert!(!task.needs_expansion());
528
529        task.complexity = 2;
530        assert!(!task.needs_expansion());
531
532        task.complexity = 3;
533        assert!(!task.needs_expansion());
534
535        // Complexity >= 5 should need expansion
536        task.complexity = 5;
537        assert!(task.needs_expansion());
538
539        task.complexity = 8;
540        assert!(task.needs_expansion());
541
542        task.complexity = 13;
543        assert!(task.needs_expansion());
544
545        task.complexity = 21;
546        assert!(task.needs_expansion());
547
548        // Already expanded tasks (with Expanded status) should not need expansion
549        task.status = TaskStatus::Expanded;
550        assert!(!task.needs_expansion());
551
552        // Reset status and test subtask case
553        task.status = TaskStatus::Pending;
554        task.parent_id = Some("parent:1".to_string());
555        assert!(!task.needs_expansion()); // Subtasks don't need expansion
556
557        // Reset and test tasks with subtasks
558        task.parent_id = None;
559        task.subtasks = vec!["TASK-1.1".to_string()];
560        assert!(!task.needs_expansion()); // Already has subtasks
561    }
562
563    #[test]
564    fn test_task_serialization() {
565        let task = Task::new(
566            "TASK-1".to_string(),
567            "Test Task".to_string(),
568            "Description".to_string(),
569        );
570
571        let json = serde_json::to_string(&task).unwrap();
572        let deserialized: Task = serde_json::from_str(&json).unwrap();
573
574        assert_eq!(task.id, deserialized.id);
575        assert_eq!(task.title, deserialized.title);
576        assert_eq!(task.description, deserialized.description);
577    }
578
579    #[test]
580    fn test_task_serialization_with_optional_fields() {
581        let mut task = Task::new("TASK-1".to_string(), "Test".to_string(), "Desc".to_string());
582        task.details = Some("Detailed info".to_string());
583        task.test_strategy = Some("Test plan".to_string());
584        task.assign("alice");
585
586        let json = serde_json::to_string(&task).unwrap();
587        let deserialized: Task = serde_json::from_str(&json).unwrap();
588
589        assert_eq!(task.details, deserialized.details);
590        assert_eq!(task.test_strategy, deserialized.test_strategy);
591        assert_eq!(task.assigned_to, deserialized.assigned_to);
592    }
593
594    #[test]
595    fn test_priority_default() {
596        let default_priority = Priority::default();
597        assert_eq!(default_priority, Priority::Medium);
598    }
599
600    #[test]
601    fn test_status_all() {
602        let all_statuses = TaskStatus::all();
603        assert_eq!(all_statuses.len(), 8);
604        assert!(all_statuses.contains(&"pending"));
605        assert!(all_statuses.contains(&"in-progress"));
606        assert!(all_statuses.contains(&"done"));
607        assert!(all_statuses.contains(&"review"));
608        assert!(all_statuses.contains(&"blocked"));
609        assert!(all_statuses.contains(&"deferred"));
610        assert!(all_statuses.contains(&"cancelled"));
611        assert!(all_statuses.contains(&"expanded"));
612    }
613
614    #[test]
615    fn test_circular_dependency_self_reference() {
616        let task = Task::new("TASK-1".to_string(), "Test".to_string(), "Desc".to_string());
617        let all_tasks = vec![task.clone()];
618
619        let result = task.would_create_cycle("TASK-1", &all_tasks);
620        assert!(result.is_err());
621        assert!(result.unwrap_err().contains("Self-reference"));
622    }
623
624    #[test]
625    fn test_circular_dependency_direct_cycle() {
626        let mut task1 = Task::new(
627            "TASK-1".to_string(),
628            "Task 1".to_string(),
629            "Desc".to_string(),
630        );
631        task1.dependencies = vec!["TASK-2".to_string()];
632
633        let task2 = Task::new(
634            "TASK-2".to_string(),
635            "Task 2".to_string(),
636            "Desc".to_string(),
637        );
638
639        let all_tasks = vec![task1.clone(), task2.clone()];
640
641        // Trying to add TASK-1 as dependency of TASK-2 would create cycle: TASK-2 -> TASK-1 -> TASK-2
642        let result = task2.would_create_cycle("TASK-1", &all_tasks);
643        assert!(result.is_err());
644        assert!(result.unwrap_err().contains("Circular dependency"));
645    }
646
647    #[test]
648    fn test_circular_dependency_indirect_cycle() {
649        let mut task1 = Task::new(
650            "TASK-1".to_string(),
651            "Task 1".to_string(),
652            "Desc".to_string(),
653        );
654        task1.dependencies = vec!["TASK-2".to_string()];
655
656        let mut task2 = Task::new(
657            "TASK-2".to_string(),
658            "Task 2".to_string(),
659            "Desc".to_string(),
660        );
661        task2.dependencies = vec!["TASK-3".to_string()];
662
663        let task3 = Task::new(
664            "TASK-3".to_string(),
665            "Task 3".to_string(),
666            "Desc".to_string(),
667        );
668
669        let all_tasks = vec![task1.clone(), task2, task3.clone()];
670
671        // Trying to add TASK-1 as dependency of TASK-3 would create cycle:
672        // TASK-3 -> TASK-1 -> TASK-2 -> TASK-3
673        let result = task3.would_create_cycle("TASK-1", &all_tasks);
674        assert!(result.is_err());
675        assert!(result.unwrap_err().contains("Circular dependency"));
676    }
677
678    #[test]
679    fn test_circular_dependency_no_cycle() {
680        let mut task1 = Task::new(
681            "TASK-1".to_string(),
682            "Task 1".to_string(),
683            "Desc".to_string(),
684        );
685        task1.dependencies = vec!["TASK-3".to_string()];
686
687        let task2 = Task::new(
688            "TASK-2".to_string(),
689            "Task 2".to_string(),
690            "Desc".to_string(),
691        );
692
693        let task3 = Task::new(
694            "TASK-3".to_string(),
695            "Task 3".to_string(),
696            "Desc".to_string(),
697        );
698
699        let all_tasks = vec![task1.clone(), task2.clone(), task3];
700
701        // Adding TASK-2 as dependency of TASK-1 is fine (no cycle)
702        let result = task1.would_create_cycle("TASK-2", &all_tasks);
703        assert!(result.is_ok());
704    }
705
706    #[test]
707    fn test_circular_dependency_complex_graph() {
708        let mut task1 = Task::new(
709            "TASK-1".to_string(),
710            "Task 1".to_string(),
711            "Desc".to_string(),
712        );
713        task1.dependencies = vec!["TASK-2".to_string(), "TASK-3".to_string()];
714
715        let mut task2 = Task::new(
716            "TASK-2".to_string(),
717            "Task 2".to_string(),
718            "Desc".to_string(),
719        );
720        task2.dependencies = vec!["TASK-4".to_string()];
721
722        let mut task3 = Task::new(
723            "TASK-3".to_string(),
724            "Task 3".to_string(),
725            "Desc".to_string(),
726        );
727        task3.dependencies = vec!["TASK-4".to_string()];
728
729        let task4 = Task::new(
730            "TASK-4".to_string(),
731            "Task 4".to_string(),
732            "Desc".to_string(),
733        );
734
735        let all_tasks = vec![task1.clone(), task2, task3, task4.clone()];
736
737        // Adding TASK-1 as dependency of TASK-4 would create a cycle
738        let result = task4.would_create_cycle("TASK-1", &all_tasks);
739        assert!(result.is_err());
740        assert!(result.unwrap_err().contains("Circular dependency"));
741    }
742
743    // Validation tests
744    #[test]
745    fn test_validate_id_success() {
746        assert!(Task::validate_id("TASK-123").is_ok());
747        assert!(Task::validate_id("task_456").is_ok());
748        assert!(Task::validate_id("Feature-789").is_ok());
749        // Namespaced IDs
750        assert!(Task::validate_id("phase1:10").is_ok());
751        assert!(Task::validate_id("phase1:10.1").is_ok());
752        assert!(Task::validate_id("my-epic:subtask-1.2.3").is_ok());
753    }
754
755    #[test]
756    fn test_validate_id_empty() {
757        let result = Task::validate_id("");
758        assert!(result.is_err());
759        assert_eq!(result.unwrap_err(), "Task ID cannot be empty");
760    }
761
762    #[test]
763    fn test_validate_id_too_long() {
764        let long_id = "A".repeat(101);
765        let result = Task::validate_id(&long_id);
766        assert!(result.is_err());
767        assert!(result.unwrap_err().contains("too long"));
768    }
769
770    #[test]
771    fn test_validate_id_invalid_characters() {
772        assert!(Task::validate_id("TASK@123").is_err());
773        assert!(Task::validate_id("TASK 123").is_err());
774        assert!(Task::validate_id("TASK#123").is_err());
775        // Note: dot and colon are now valid for namespaced IDs
776        assert!(Task::validate_id("TASK.123").is_ok()); // Valid for subtask IDs like "10.1"
777        assert!(Task::validate_id("epic:TASK-1").is_ok()); // Valid namespaced ID
778    }
779
780    #[test]
781    fn test_validate_title_success() {
782        assert!(Task::validate_title("Valid title").is_ok());
783        assert!(Task::validate_title("A").is_ok());
784    }
785
786    #[test]
787    fn test_validate_title_empty() {
788        let result = Task::validate_title("");
789        assert!(result.is_err());
790        assert_eq!(result.unwrap_err(), "Task title cannot be empty");
791
792        let result = Task::validate_title("   ");
793        assert!(result.is_err());
794        assert_eq!(result.unwrap_err(), "Task title cannot be empty");
795    }
796
797    #[test]
798    fn test_validate_title_too_long() {
799        let long_title = "A".repeat(201);
800        let result = Task::validate_title(&long_title);
801        assert!(result.is_err());
802        assert!(result.unwrap_err().contains("too long"));
803    }
804
805    #[test]
806    fn test_validate_description_success() {
807        assert!(Task::validate_description("Valid description").is_ok());
808        assert!(Task::validate_description("").is_ok());
809    }
810
811    #[test]
812    fn test_validate_description_too_long() {
813        let long_desc = "A".repeat(5001);
814        let result = Task::validate_description(&long_desc);
815        assert!(result.is_err());
816        assert!(result.unwrap_err().contains("too long"));
817    }
818
819    #[test]
820    fn test_validate_complexity_success() {
821        assert!(Task::validate_complexity(0).is_ok());
822        assert!(Task::validate_complexity(1).is_ok());
823        assert!(Task::validate_complexity(2).is_ok());
824        assert!(Task::validate_complexity(3).is_ok());
825        assert!(Task::validate_complexity(5).is_ok());
826        assert!(Task::validate_complexity(8).is_ok());
827        assert!(Task::validate_complexity(13).is_ok());
828        assert!(Task::validate_complexity(21).is_ok());
829    }
830
831    #[test]
832    fn test_validate_complexity_invalid() {
833        assert!(Task::validate_complexity(4).is_err());
834        assert!(Task::validate_complexity(6).is_err());
835        assert!(Task::validate_complexity(7).is_err());
836        assert!(Task::validate_complexity(100).is_err());
837    }
838
839    #[test]
840    fn test_sanitize_text() {
841        assert_eq!(
842            Task::sanitize_text("<script>alert('xss')</script>"),
843            "&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;"
844        );
845        assert_eq!(Task::sanitize_text("Normal text"), "Normal text");
846        assert_eq!(
847            Task::sanitize_text("<div>Content</div>"),
848            "&lt;div&gt;Content&lt;/div&gt;"
849        );
850    }
851
852    #[test]
853    fn test_validate_success() {
854        let task = Task::new(
855            "TASK-1".to_string(),
856            "Valid title".to_string(),
857            "Valid description".to_string(),
858        );
859        assert!(task.validate().is_ok());
860    }
861
862    #[test]
863    fn test_validate_multiple_errors() {
864        let mut task = Task::new("TASK@INVALID".to_string(), "".to_string(), "A".repeat(5001));
865        task.complexity = 100; // Invalid Fibonacci number
866
867        let result = task.validate();
868        assert!(result.is_err());
869        let errors = result.unwrap_err();
870        assert_eq!(errors.len(), 4);
871        assert!(errors.iter().any(|e| e.contains("ID")));
872        assert!(errors.iter().any(|e| e.contains("title")));
873        assert!(errors.iter().any(|e| e.contains("description")));
874        assert!(errors.iter().any(|e| e.contains("Complexity")));
875    }
876
877    // Cross-tag dependency tests
878    #[test]
879    fn test_cross_tag_dependency_met() {
880        let mut task_a = Task::new(
881            "auth:1".to_string(),
882            "Auth task".to_string(),
883            "Desc".to_string(),
884        );
885        task_a.set_status(TaskStatus::Done);
886
887        let mut task_b = Task::new(
888            "api:1".to_string(),
889            "API task".to_string(),
890            "Desc".to_string(),
891        );
892        task_b.dependencies = vec!["auth:1".to_string()];
893
894        let all_tasks = vec![&task_a, &task_b];
895        assert!(task_b.has_dependencies_met_refs(&all_tasks));
896    }
897
898    #[test]
899    fn test_cross_tag_dependency_not_met() {
900        let task_a = Task::new(
901            "auth:1".to_string(),
902            "Auth task".to_string(),
903            "Desc".to_string(),
904        );
905        // task_a still pending
906
907        let mut task_b = Task::new(
908            "api:1".to_string(),
909            "API task".to_string(),
910            "Desc".to_string(),
911        );
912        task_b.dependencies = vec!["auth:1".to_string()];
913
914        let all_tasks = vec![&task_a, &task_b];
915        assert!(!task_b.has_dependencies_met_refs(&all_tasks));
916    }
917
918    #[test]
919    fn test_local_dependency_still_works_with_refs() {
920        let mut task_a = Task::new("1".to_string(), "First".to_string(), "Desc".to_string());
921        task_a.set_status(TaskStatus::Done);
922
923        let mut task_b = Task::new("2".to_string(), "Second".to_string(), "Desc".to_string());
924        task_b.dependencies = vec!["1".to_string()];
925
926        let all_tasks = vec![&task_a, &task_b];
927        assert!(task_b.has_dependencies_met_refs(&all_tasks));
928    }
929
930    #[test]
931    fn test_has_dependencies_met_refs_missing_dependency() {
932        let mut task = Task::new("api:1".to_string(), "Test".to_string(), "Desc".to_string());
933        task.dependencies = vec!["auth:1".to_string(), "auth:MISSING".to_string()];
934
935        let mut dep1 = Task::new(
936            "auth:1".to_string(),
937            "Dep 1".to_string(),
938            "Desc".to_string(),
939        );
940        dep1.set_status(TaskStatus::Done);
941
942        let all_tasks = vec![&dep1];
943        assert!(!task.has_dependencies_met_refs(&all_tasks));
944    }
945}