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
//! Utility functions for CLI handlers
//!
//! Helper functions for reading stdin, formatting status badges, and printing task contexts.

use crate::db::models::{EventsSummary, Task, TaskContext};
use crate::error::{IntentError, Result};
use std::io::{self, Read};

/// Read from stdin with proper encoding handling (especially for Windows PowerShell)
pub fn read_stdin() -> Result<String> {
    #[cfg(windows)]
    {
        use encoding_rs::GBK;

        let mut buffer = Vec::new();
        io::stdin().read_to_end(&mut buffer)?;

        // First try UTF-8
        if let Ok(s) = String::from_utf8(buffer.clone()) {
            return Ok(s.trim().to_string());
        }

        // Fall back to GBK decoding (common in Chinese Windows PowerShell)
        let (decoded, _, had_errors) = GBK.decode(&buffer);
        if !had_errors {
            tracing::debug!(
                "Successfully decoded stdin from GBK encoding (Chinese Windows detected)"
            );
            Ok(decoded.trim().to_string())
        } else {
            // If GBK also fails, return the UTF-8 lossy version
            tracing::warn!(
                "Failed to decode stdin from both UTF-8 and GBK, using lossy UTF-8 conversion"
            );
            Ok(String::from_utf8_lossy(&buffer).trim().to_string())
        }
    }

    #[cfg(not(windows))]
    {
        let mut buffer = String::new();
        io::stdin().read_to_string(&mut buffer)?;
        Ok(buffer.trim().to_string())
    }
}

/// Get a status badge icon for task status (arrow style, used in `ie status`)
pub fn get_status_badge(status: &str) -> &'static str {
    match status {
        "done" => "",
        "doing" => "",
        "todo" => "",
        _ => "?",
    }
}

/// Get a status icon for task status (bullet style, used in tree/list views)
pub fn status_icon(status: &str) -> &'static str {
    match status {
        "todo" => "",
        "doing" => "",
        "done" => "",
        _ => "?",
    }
}

/// Print tasks in a hierarchical tree format
pub fn print_task_tree(tasks: &[crate::db::models::Task]) {
    use std::collections::HashMap;

    // Build parent -> children map
    let mut children_map: HashMap<Option<i64>, Vec<&crate::db::models::Task>> = HashMap::new();
    for task in tasks {
        children_map.entry(task.parent_id).or_default().push(task);
    }

    fn print_subtree(
        children_map: &HashMap<Option<i64>, Vec<&crate::db::models::Task>>,
        parent_id: Option<i64>,
        indent: &str,
    ) {
        if let Some(children) = children_map.get(&parent_id) {
            for (i, task) in children.iter().enumerate() {
                let is_last_child = i == children.len() - 1;
                let connector = if indent.is_empty() {
                    ""
                } else if is_last_child {
                    "└─ "
                } else {
                    "├─ "
                };
                let icon = status_icon(&task.status);
                let priority_info = task
                    .priority
                    .map(|p| format!(" [P{}]", p))
                    .unwrap_or_default();

                println!(
                    "  {}{}{} #{} {}{}",
                    indent, connector, icon, task.id, task.name, priority_info
                );

                let new_indent = if indent.is_empty() {
                    "".to_string()
                } else if is_last_child {
                    format!("{}   ", indent)
                } else {
                    format!("{}", indent)
                };
                print_subtree(children_map, Some(task.id), &new_indent);
            }
        }
    }

    // Start with root-level tasks (parent is None or parent not in our set)
    let task_ids: std::collections::HashSet<i64> = tasks.iter().map(|t| t.id).collect();
    let roots: Vec<&crate::db::models::Task> = tasks
        .iter()
        .filter(|t| t.parent_id.is_none() || !task_ids.contains(&t.parent_id.unwrap_or(-1)))
        .collect();

    for task in &roots {
        let icon = status_icon(&task.status);
        let priority_info = task
            .priority
            .map(|p| format!(" [P{}]", p))
            .unwrap_or_default();
        println!("  {} #{} {}{}", icon, task.id, task.name, priority_info);
        print_subtree(&children_map, Some(task.id), "  ");
    }
}

/// Print a concise task summary
pub fn print_task_summary(task: &Task) {
    let icon = status_icon(&task.status);
    println!("  {} #{} {}", icon, task.id, task.name);
    println!("  Status: {}", task.status);
    if let Some(pid) = task.parent_id {
        println!("  Parent: #{}", pid);
    }
    if let Some(p) = task.priority {
        println!("  Priority: {}", p);
    }
    if let Some(spec) = &task.spec {
        if !spec.is_empty() {
            println!("  Spec: {}", spec);
        }
    }
    println!("  Owner: {}", task.owner);
    if let Some(af) = &task.active_form {
        println!("  Active form: {}", af);
    }
    if let Some(meta) = &task.metadata {
        println!("  Metadata: {}", meta);
    }
}

/// Print task context in a human-friendly tree format
pub fn print_task_context(ctx: &TaskContext) {
    let icon = status_icon(&ctx.task.status);
    println!("\n{} Task #{}: {}", icon, ctx.task.id, ctx.task.name);
    println!("Status: {}", ctx.task.status);

    if let Some(spec) = &ctx.task.spec {
        println!("\nSpec:");
        for line in spec.lines() {
            println!("  {}", line);
        }
    }

    // Print parent chain
    if !ctx.ancestors.is_empty() {
        println!("\nParent Chain:");
        for (i, ancestor) in ctx.ancestors.iter().enumerate() {
            let indent = "  ".repeat(i + 1);
            println!(
                "{}└─ {} #{}: {}",
                indent,
                status_icon(&ancestor.status),
                ancestor.id,
                ancestor.name
            );
        }
    }

    // Print children
    if !ctx.children.is_empty() {
        println!("\nChildren:");
        for child in &ctx.children {
            println!(
                "  {} #{}: {}",
                status_icon(&child.status),
                child.id,
                child.name
            );
        }
    }

    // Print siblings
    if !ctx.siblings.is_empty() {
        println!("\nSiblings:");
        for sibling in &ctx.siblings {
            println!(
                "  {} #{}: {}",
                status_icon(&sibling.status),
                sibling.id,
                sibling.name
            );
        }
    }

    // Print dependencies (blocking tasks)
    if !ctx.dependencies.blocking_tasks.is_empty() {
        println!("\nDepends on:");
        for dep in &ctx.dependencies.blocking_tasks {
            println!("  {} #{}: {}", status_icon(&dep.status), dep.id, dep.name);
        }
    }

    // Print dependents (blocked by tasks)
    if !ctx.dependencies.blocked_by_tasks.is_empty() {
        println!("\nBlocks:");
        for dep in &ctx.dependencies.blocked_by_tasks {
            println!("  {} #{}: {}", status_icon(&dep.status), dep.id, dep.name);
        }
    }

    println!();
}

/// Print events summary (recent events with count)
pub fn print_events_summary(summary: &EventsSummary) {
    println!("Events ({}):", summary.total_count);
    for event in summary.recent_events.iter().take(10) {
        println!(
            "  [{}] {}{}",
            event.log_type,
            event.timestamp.format("%Y-%m-%d %H:%M:%S"),
            event.discussion_data
        );
    }
}

/// Check if query is a `#ID` format (e.g., `"#123"`, `"#1"`).
/// Returns `Some(id)` if it is a task ID query, `None` otherwise.
pub fn parse_task_id_query(query: &str) -> Option<i64> {
    let query = query.trim();
    if !query.starts_with('#') || query.len() < 2 {
        return None;
    }
    query[1..].parse::<i64>().ok()
}

/// Check if query is a status keyword combination (`todo`, `doing`, `done`).
/// Returns `Some(statuses)` if all words are valid status keywords, `None` otherwise.
pub fn parse_status_keywords(query: &str) -> Option<Vec<String>> {
    let query_lower = query.to_lowercase();
    let words: Vec<&str> = query_lower.split_whitespace().collect();

    if words.is_empty() {
        return None;
    }

    let valid_statuses = ["todo", "doing", "done"];
    let mut statuses: Vec<String> = Vec::new();

    for word in words {
        if valid_statuses.contains(&word) {
            if !statuses.iter().any(|s| s == word) {
                statuses.push(word.to_string());
            }
        } else {
            return None;
        }
    }

    Some(statuses)
}

/// Parse metadata key=value strings into a JSON object.
/// "key=value" sets a key, "key=" deletes a key.
pub fn parse_metadata(pairs: &[String]) -> Result<serde_json::Value> {
    let mut map = serde_json::Map::new();
    for pair in pairs {
        if let Some(eq_pos) = pair.find('=') {
            let key = pair[..eq_pos].trim().to_string();
            let value = pair[eq_pos + 1..].trim().to_string();
            if key.is_empty() {
                return Err(IntentError::InvalidInput(format!(
                    "Invalid metadata: empty key in '{}'",
                    pair
                )));
            }
            if value.is_empty() {
                // "key=" means delete
                map.insert(key, serde_json::Value::Null);
            } else {
                map.insert(key, serde_json::Value::String(value));
            }
        } else {
            return Err(IntentError::InvalidInput(format!(
                "Invalid metadata format: '{}'. Expected 'key=value'",
                pair
            )));
        }
    }
    Ok(serde_json::Value::Object(map))
}

/// Merge new metadata into existing metadata JSON string.
/// Null values in new_meta mean "delete this key".
pub fn merge_metadata(existing: Option<&str>, new_meta: &serde_json::Value) -> Option<String> {
    let mut base: serde_json::Map<String, serde_json::Value> = existing
        .and_then(|s| serde_json::from_str(s).ok())
        .unwrap_or_default();

    if let serde_json::Value::Object(new_map) = new_meta {
        for (key, value) in new_map {
            if value.is_null() {
                base.remove(key);
            } else {
                base.insert(key.clone(), value.clone());
            }
        }
    }

    if base.is_empty() {
        None
    } else {
        Some(serde_json::to_string(&base).unwrap_or_default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::models::{Task, TaskContext, TaskDependencies};

    // Helper function to create a test task with minimal boilerplate
    fn create_test_task(id: i64, name: &str, status: &str, parent_id: Option<i64>) -> Task {
        Task {
            id,
            name: name.to_string(),
            status: status.to_string(),
            spec: None,
            parent_id,
            priority: Some(5),
            complexity: None,
            first_todo_at: None,
            first_doing_at: None,
            first_done_at: None,
            active_form: None,
            owner: "human".to_string(),
            metadata: None,
        }
    }

    #[test]
    fn test_get_status_badge_done() {
        assert_eq!(get_status_badge("done"), "");
    }

    #[test]
    fn test_get_status_badge_doing() {
        assert_eq!(get_status_badge("doing"), "");
    }

    #[test]
    fn test_get_status_badge_todo() {
        assert_eq!(get_status_badge("todo"), "");
    }

    #[test]
    fn test_get_status_badge_unknown() {
        assert_eq!(get_status_badge("unknown"), "?");
        assert_eq!(get_status_badge(""), "?");
        assert_eq!(get_status_badge("invalid"), "?");
    }

    #[test]
    fn test_status_icon() {
        assert_eq!(status_icon("todo"), "");
        assert_eq!(status_icon("doing"), "");
        assert_eq!(status_icon("done"), "");
        assert_eq!(status_icon("unknown"), "?");
    }

    #[test]
    fn test_print_task_context_basic() {
        let task = create_test_task(1, "Test Task", "todo", None);

        let ctx = TaskContext {
            task,
            ancestors: vec![],
            children: vec![],
            siblings: vec![],
            dependencies: TaskDependencies {
                blocking_tasks: vec![],
                blocked_by_tasks: vec![],
            },
        };

        // Should not panic and should execute all branches
        print_task_context(&ctx); // should not panic
    }

    #[test]
    fn test_print_task_context_with_spec() {
        let mut task = create_test_task(2, "Task with Spec", "doing", None);
        task.spec = Some("This is a\nmulti-line\nspecification".to_string());

        let ctx = TaskContext {
            task,
            ancestors: vec![],
            children: vec![],
            siblings: vec![],
            dependencies: TaskDependencies {
                blocking_tasks: vec![],
                blocked_by_tasks: vec![],
            },
        };

        print_task_context(&ctx); // should not panic
    }

    #[test]
    fn test_print_task_context_with_children() {
        let task = create_test_task(3, "Parent Task", "doing", None);
        let child1 = create_test_task(4, "Child Task 1", "todo", Some(3));
        let child2 = create_test_task(5, "Child Task 2", "done", Some(3));

        let ctx = TaskContext {
            task,
            ancestors: vec![],
            children: vec![child1, child2],
            siblings: vec![],
            dependencies: TaskDependencies {
                blocking_tasks: vec![],
                blocked_by_tasks: vec![],
            },
        };

        print_task_context(&ctx); // should not panic
    }

    #[test]
    fn test_print_task_context_with_ancestors() {
        let task = create_test_task(6, "Nested Task", "doing", Some(7));
        let parent = create_test_task(7, "Parent Task", "doing", None);

        let ctx = TaskContext {
            task,
            ancestors: vec![parent],
            children: vec![],
            siblings: vec![],
            dependencies: TaskDependencies {
                blocking_tasks: vec![],
                blocked_by_tasks: vec![],
            },
        };

        print_task_context(&ctx); // should not panic
    }

    #[test]
    fn test_print_task_context_with_dependencies() {
        let task = create_test_task(8, "Task with Dependencies", "todo", None);
        let blocker = create_test_task(9, "Blocking Task", "doing", None);
        let blocked = create_test_task(10, "Blocked Task", "todo", None);

        let ctx = TaskContext {
            task,
            ancestors: vec![],
            children: vec![],
            siblings: vec![],
            dependencies: TaskDependencies {
                blocking_tasks: vec![blocker],
                blocked_by_tasks: vec![blocked],
            },
        };

        print_task_context(&ctx); // should not panic
    }

    #[test]
    fn test_print_task_context_with_siblings() {
        let task = create_test_task(11, "Task with Siblings", "doing", Some(12));
        let sibling = create_test_task(13, "Sibling Task", "todo", Some(12));

        let ctx = TaskContext {
            task,
            ancestors: vec![],
            children: vec![],
            siblings: vec![sibling],
            dependencies: TaskDependencies {
                blocking_tasks: vec![],
                blocked_by_tasks: vec![],
            },
        };

        print_task_context(&ctx); // should not panic
    }

    // ============================================================================
    // parse_task_id_query tests
    // ============================================================================

    #[test]
    fn test_parse_task_id_query_valid() {
        assert_eq!(parse_task_id_query("#1"), Some(1));
        assert_eq!(parse_task_id_query("#123"), Some(123));
        assert_eq!(parse_task_id_query("#999999"), Some(999999));
    }

    #[test]
    fn test_parse_task_id_query_with_whitespace() {
        assert_eq!(parse_task_id_query("  #1  "), Some(1));
        assert_eq!(parse_task_id_query("\t#42\n"), Some(42));
    }

    #[test]
    fn test_parse_task_id_query_invalid() {
        assert_eq!(parse_task_id_query("123"), None);
        assert_eq!(parse_task_id_query("task"), None);
        assert_eq!(parse_task_id_query("#"), None);
        assert_eq!(parse_task_id_query("#abc"), None);
        assert_eq!(parse_task_id_query("#1a"), None);
        assert_eq!(parse_task_id_query("#a1"), None);
        assert_eq!(parse_task_id_query("#123 task"), None);
        assert_eq!(parse_task_id_query("task #123"), None);
        assert_eq!(parse_task_id_query("#-1"), Some(-1));
        assert_eq!(parse_task_id_query(""), None);
    }

    // ============================================================================
    // parse_status_keywords tests
    // ============================================================================

    #[test]
    fn test_parse_status_keywords_valid() {
        assert_eq!(
            parse_status_keywords("todo"),
            Some(vec!["todo".to_string()])
        );
        assert_eq!(
            parse_status_keywords("doing"),
            Some(vec!["doing".to_string()])
        );
        assert_eq!(
            parse_status_keywords("done"),
            Some(vec!["done".to_string()])
        );
    }

    #[test]
    fn test_parse_status_keywords_multiple() {
        let result = parse_status_keywords("todo doing");
        assert!(result.is_some());
        let statuses = result.unwrap();
        assert!(statuses.contains(&"todo".to_string()));
        assert!(statuses.contains(&"doing".to_string()));
    }

    #[test]
    fn test_parse_status_keywords_case_insensitive() {
        assert_eq!(
            parse_status_keywords("TODO"),
            Some(vec!["todo".to_string()])
        );
        assert_eq!(
            parse_status_keywords("DoInG"),
            Some(vec!["doing".to_string()])
        );
    }

    #[test]
    fn test_parse_status_keywords_invalid() {
        assert_eq!(parse_status_keywords("todo task"), None);
        assert_eq!(parse_status_keywords("search term"), None);
        assert_eq!(parse_status_keywords(""), None);
        assert_eq!(parse_status_keywords("   "), None);
    }

    #[test]
    fn test_parse_status_keywords_dedup() {
        let result = parse_status_keywords("todo todo todo");
        assert!(result.is_some());
        let statuses = result.unwrap();
        assert_eq!(statuses.len(), 1);
        assert_eq!(statuses[0], "todo");
    }
}