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
use crate::db::models::{DateRange, Event, Report, ReportSummary, StatusBreakdown, Task};
use crate::error::Result;
use chrono::Utc;
use sqlx::SqlitePool;

pub struct ReportManager<'a> {
    pool: &'a SqlitePool,
}

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

    /// Generate a report with optional filters
    pub async fn generate_report(
        &self,
        since: Option<String>,
        status: Option<String>,
        filter_name: Option<String>,
        filter_spec: Option<String>,
        summary_only: bool,
    ) -> Result<Report> {
        // Parse duration if provided
        let since_datetime = since.and_then(|s| crate::time_utils::parse_duration(&s).ok());

        // Build task query
        let mut task_query = String::from("SELECT id FROM tasks WHERE 1=1");
        let mut task_conditions = Vec::new();

        if let Some(ref status) = status {
            task_query.push_str(" AND status = ?");
            task_conditions.push(status.clone());
        }

        if let Some(ref dt) = since_datetime {
            task_query.push_str(" AND first_todo_at >= ?");
            task_conditions.push(dt.to_rfc3339());
        }

        // Add FTS5 filters
        let task_ids = if filter_name.is_some() || filter_spec.is_some() {
            self.filter_tasks_by_fts(&filter_name, &filter_spec).await?
        } else {
            Vec::new()
        };

        // If FTS filters were applied, intersect with other filters
        let tasks = if !task_ids.is_empty() {
            task_query.push_str(&format!(
                " AND id IN ({})",
                task_ids.iter().map(|_| "?").collect::<Vec<_>>().join(", ")
            ));
            let full_query = task_query.replace("SELECT id", "SELECT id, parent_id, name, NULL as spec, status, complexity, priority, first_todo_at, first_doing_at, first_done_at, active_form, owner, metadata");
            let mut q = sqlx::query_as::<_, Task>(&full_query);
            for cond in &task_conditions {
                q = q.bind(cond);
            }
            for id in &task_ids {
                q = q.bind(id);
            }
            q.fetch_all(self.pool).await?
        } else if filter_name.is_none() && filter_spec.is_none() {
            let full_query = task_query.replace("SELECT id", "SELECT id, parent_id, name, NULL as spec, status, complexity, priority, first_todo_at, first_doing_at, first_done_at, active_form, owner, metadata");
            let mut q = sqlx::query_as::<_, Task>(&full_query);
            for cond in &task_conditions {
                q = q.bind(cond);
            }
            q.fetch_all(self.pool).await?
        } else {
            Vec::new()
        };

        // Count tasks by status from filtered results
        let todo_count = tasks.iter().filter(|t| t.status == "todo").count() as i64;
        let doing_count = tasks.iter().filter(|t| t.status == "doing").count() as i64;
        let done_count = tasks.iter().filter(|t| t.status == "done").count() as i64;

        let total_tasks = tasks.len() as i64;

        // Get events
        let events = if !summary_only {
            let mut event_query = String::from(crate::sql_constants::SELECT_EVENT_BASE);
            let mut event_conditions = Vec::new();

            if let Some(ref dt) = since_datetime {
                event_query.push_str(" AND timestamp >= ?");
                event_conditions.push(dt.to_rfc3339());
            }

            event_query.push_str(" ORDER BY timestamp DESC");

            let mut q = sqlx::query_as::<_, Event>(&event_query);
            for cond in &event_conditions {
                q = q.bind(cond);
            }

            Some(q.fetch_all(self.pool).await?)
        } else {
            None
        };

        let total_events = if let Some(ref evts) = events {
            evts.len() as i64
        } else {
            sqlx::query_scalar::<_, i64>(crate::sql_constants::COUNT_EVENTS_TOTAL)
                .fetch_one(self.pool)
                .await?
        };

        let date_range = since_datetime.map(|from| DateRange {
            from,
            to: Utc::now(),
        });

        Ok(Report {
            summary: ReportSummary {
                total_tasks,
                tasks_by_status: StatusBreakdown {
                    todo: todo_count,
                    doing: doing_count,
                    done: done_count,
                },
                total_events,
                date_range,
            },
            tasks: if summary_only { None } else { Some(tasks) },
            events,
        })
    }

    /// Filter tasks using FTS5
    async fn filter_tasks_by_fts(
        &self,
        filter_name: &Option<String>,
        filter_spec: &Option<String>,
    ) -> Result<Vec<i64>> {
        let mut query = String::from("SELECT rowid FROM tasks_fts WHERE ");
        let mut conditions = Vec::new();

        if let Some(name_filter) = filter_name {
            conditions.push(format!(
                "name MATCH '{}'",
                crate::search::escape_fts5(name_filter)
            ));
        }

        if let Some(spec_filter) = filter_spec {
            conditions.push(format!(
                "spec MATCH '{}'",
                crate::search::escape_fts5(spec_filter)
            ));
        }

        if conditions.is_empty() {
            return Ok(Vec::new());
        }

        query.push_str(&conditions.join(" AND "));

        let ids: Vec<i64> = sqlx::query_scalar(&query).fetch_all(self.pool).await?;

        Ok(ids)
    }
}

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

    #[tokio::test]
    async fn test_generate_report_summary_only() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        // Create tasks with different statuses
        task_mgr
            .add_task("Todo task".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        let doing = task_mgr
            .add_task("Doing task".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        task_mgr.start_task(doing.id, false).await.unwrap();
        let done = task_mgr
            .add_task("Done task".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        task_mgr.start_task(done.id, false).await.unwrap();
        task_mgr.done_task(false).await.unwrap();

        let report = report_mgr
            .generate_report(None, None, None, None, true)
            .await
            .unwrap();

        assert_eq!(report.summary.total_tasks, 3);
        assert_eq!(report.summary.tasks_by_status.todo, 1);
        assert_eq!(report.summary.tasks_by_status.doing, 1);
        assert_eq!(report.summary.tasks_by_status.done, 1);
        assert!(report.tasks.is_none());
        assert!(report.events.is_none());
    }

    #[tokio::test]
    async fn test_generate_report_full() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        task_mgr
            .add_task("Task 1".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        task_mgr
            .add_task("Task 2".to_string(), None, None, None, None, None)
            .await
            .unwrap();

        let report = report_mgr
            .generate_report(None, None, None, None, false)
            .await
            .unwrap();

        assert!(report.tasks.is_some());
        assert_eq!(report.tasks.unwrap().len(), 2);
    }

    #[tokio::test]
    async fn test_generate_report_filter_by_status() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        task_mgr
            .add_task("Todo task".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        let doing = task_mgr
            .add_task("Doing task".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        task_mgr.start_task(doing.id, false).await.unwrap();

        let report = report_mgr
            .generate_report(None, Some("doing".to_string()), None, None, false)
            .await
            .unwrap();

        let tasks = report.tasks.unwrap();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].status, "doing");
    }

    #[tokio::test]
    async fn test_generate_report_with_events() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let event_mgr = EventManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        let task = task_mgr
            .add_task("Task 1".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        event_mgr
            .add_event(task.id, "decision".to_string(), "Test event".to_string())
            .await
            .unwrap();

        let report = report_mgr
            .generate_report(None, None, None, None, false)
            .await
            .unwrap();

        assert!(report.events.is_some());
        assert_eq!(report.summary.total_events, 1);
    }

    #[tokio::test]
    async fn test_parse_duration_days() {
        let result = crate::time_utils::parse_duration("7d").ok();
        assert!(result.is_some());
    }

    #[tokio::test]
    async fn test_parse_duration_hours() {
        let result = crate::time_utils::parse_duration("24h").ok();
        assert!(result.is_some());
    }

    #[tokio::test]
    async fn test_parse_duration_invalid() {
        let result = crate::time_utils::parse_duration("invalid").ok();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_filter_tasks_by_fts_name() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        task_mgr
            .add_task(
                "Authentication feature".to_string(),
                None,
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        task_mgr
            .add_task(
                "Database migration".to_string(),
                None,
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();

        let report = report_mgr
            .generate_report(None, None, Some("Authentication".to_string()), None, false)
            .await
            .unwrap();

        let tasks = report.tasks.unwrap();
        assert_eq!(tasks.len(), 1);
        assert!(tasks[0].name.contains("Authentication"));
    }

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

        let report = report_mgr
            .generate_report(None, None, None, None, true)
            .await
            .unwrap();

        assert_eq!(report.summary.total_tasks, 0);
        assert_eq!(report.summary.total_events, 0);
    }

    #[tokio::test]
    async fn test_report_filter_consistency() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        // Create tasks with different statuses
        task_mgr
            .add_task("Task A".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        task_mgr
            .add_task("Task B".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        let doing = task_mgr
            .add_task("Task C".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        task_mgr.start_task(doing.id, false).await.unwrap();

        // Filter with non-existent spec should return consistent summary
        let report = report_mgr
            .generate_report(None, None, None, Some("JWT".to_string()), true)
            .await
            .unwrap();

        // All counts should be 0 since no tasks match the filter
        assert_eq!(report.summary.total_tasks, 0);
        assert_eq!(report.summary.tasks_by_status.todo, 0);
        assert_eq!(report.summary.tasks_by_status.doing, 0);
        assert_eq!(report.summary.tasks_by_status.done, 0);
    }

    #[tokio::test]
    async fn test_generate_report_with_since() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        // Create some tasks
        task_mgr
            .add_task("Old task".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        task_mgr
            .add_task("Recent task".to_string(), None, None, None, None, None)
            .await
            .unwrap();

        // Query with since parameter (should include all tasks created just now)
        let report = report_mgr
            .generate_report(Some("1h".to_string()), None, None, None, true)
            .await
            .unwrap();

        // Should include recent tasks
        assert!(report.summary.total_tasks >= 2);
        assert!(report.summary.date_range.is_some());
    }

    #[tokio::test]
    async fn test_generate_report_filter_by_spec() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        task_mgr
            .add_task(
                "Task 1".to_string(),
                Some("Implement authentication using JWT".to_string()),
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        task_mgr
            .add_task(
                "Task 2".to_string(),
                Some("Setup database migrations".to_string()),
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();

        let report = report_mgr
            .generate_report(None, None, None, Some("authentication".to_string()), false)
            .await
            .unwrap();

        let tasks = report.tasks.unwrap();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].name, "Task 1");
    }

    #[tokio::test]
    async fn test_generate_report_combined_status_and_since() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        task_mgr
            .add_task("Todo task".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        let doing = task_mgr
            .add_task("Doing task".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        task_mgr.start_task(doing.id, false).await.unwrap();

        // Filter by status + since
        let report = report_mgr
            .generate_report(
                Some("1d".to_string()),
                Some("doing".to_string()),
                None,
                None,
                false,
            )
            .await
            .unwrap();

        let tasks = report.tasks.unwrap();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].status, "doing");
    }

    #[tokio::test]
    async fn test_filter_tasks_by_fts_spec() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        task_mgr
            .add_task(
                "Feature A".to_string(),
                Some("Implement JWT authentication".to_string()),
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        task_mgr
            .add_task(
                "Feature B".to_string(),
                Some("Setup OAuth2 integration".to_string()),
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();

        let ids = report_mgr
            .filter_tasks_by_fts(&None, &Some("JWT".to_string()))
            .await
            .unwrap();

        assert_eq!(ids.len(), 1);
    }

    #[tokio::test]
    async fn test_filter_tasks_by_fts_both_name_and_spec() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        task_mgr
            .add_task(
                "Auth feature".to_string(),
                Some("Implement authentication".to_string()),
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        task_mgr
            .add_task(
                "Database setup".to_string(),
                Some("Configure authentication database".to_string()),
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();

        // Both name and spec contain "auth"
        let ids = report_mgr
            .filter_tasks_by_fts(
                &Some("Auth".to_string()),
                &Some("authentication".to_string()),
            )
            .await
            .unwrap();

        assert_eq!(ids.len(), 1);
    }

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

        // Empty filters should return empty vec
        let ids = report_mgr.filter_tasks_by_fts(&None, &None).await.unwrap();

        assert_eq!(ids.len(), 0);
    }

    #[tokio::test]
    async fn test_report_date_range_present() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        task_mgr
            .add_task("Task".to_string(), None, None, None, None, None)
            .await
            .unwrap();

        let report = report_mgr
            .generate_report(Some("7d".to_string()), None, None, None, true)
            .await
            .unwrap();

        // date_range should be present when since is specified
        assert!(report.summary.date_range.is_some());
        let date_range = report.summary.date_range.unwrap();
        assert!(date_range.to > date_range.from);
    }

    #[tokio::test]
    async fn test_report_date_range_absent() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        task_mgr
            .add_task("Task".to_string(), None, None, None, None, None)
            .await
            .unwrap();

        let report = report_mgr
            .generate_report(None, None, None, None, true)
            .await
            .unwrap();

        // date_range should be None when since is not specified
        assert!(report.summary.date_range.is_none());
    }

    #[tokio::test]
    async fn test_report_events_count_consistency() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let event_mgr = EventManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        let task = task_mgr
            .add_task("Task".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        event_mgr
            .add_event(task.id, "decision".to_string(), "Event 1".to_string())
            .await
            .unwrap();
        event_mgr
            .add_event(task.id, "note".to_string(), "Event 2".to_string())
            .await
            .unwrap();

        // summary_only should still count events
        let summary_report = report_mgr
            .generate_report(None, None, None, None, true)
            .await
            .unwrap();
        assert_eq!(summary_report.summary.total_events, 2);
        assert!(summary_report.events.is_none());

        // Full report should include events
        let full_report = report_mgr
            .generate_report(None, None, None, None, false)
            .await
            .unwrap();
        assert_eq!(full_report.summary.total_events, 2);
        assert_eq!(full_report.events.unwrap().len(), 2);
    }

    #[tokio::test]
    async fn test_generate_report_all_filters_combined() {
        let ctx = TestContext::new().await;
        let task_mgr = TaskManager::new(ctx.pool());
        let report_mgr = ReportManager::new(ctx.pool());

        task_mgr
            .add_task(
                "Auth feature".to_string(),
                Some("JWT implementation".to_string()),
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        let doing = task_mgr
            .add_task(
                "Auth testing".to_string(),
                Some("Write JWT tests".to_string()),
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        task_mgr.start_task(doing.id, false).await.unwrap();

        // Combine all filters: since + status + name + spec
        let report = report_mgr
            .generate_report(
                Some("1h".to_string()),
                Some("doing".to_string()),
                Some("Auth".to_string()),
                Some("JWT".to_string()),
                false,
            )
            .await
            .unwrap();

        let tasks = report.tasks.unwrap();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].status, "doing");
        assert!(tasks[0].name.contains("Auth"));
    }
}