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
use crate::db::models::Event;
use crate::error::{IntentError, Result};
use chrono::Utc;
use sqlx::{Row, SqlitePool};
use std::sync::Arc;

pub struct EventManager<'a> {
    pool: &'a SqlitePool,
    notifier: crate::notifications::NotificationSender,
    cli_notifier: Option<crate::dashboard::cli_notifier::CliNotifier>,
    project_path: Option<String>,
}

impl<'a> EventManager<'a> {
    pub fn new(pool: &'a SqlitePool) -> Self {
        Self {
            pool,
            notifier: crate::notifications::NotificationSender::new(None),
            cli_notifier: Some(crate::dashboard::cli_notifier::CliNotifier::new()),
            project_path: None,
        }
    }

    /// Create an EventManager with project path for CLI notifications
    pub fn with_project_path(pool: &'a SqlitePool, project_path: String) -> Self {
        Self {
            pool,
            notifier: crate::notifications::NotificationSender::new(None),
            cli_notifier: Some(crate::dashboard::cli_notifier::CliNotifier::new()),
            project_path: Some(project_path),
        }
    }

    /// Create an EventManager with WebSocket notification support
    pub fn with_websocket(
        pool: &'a SqlitePool,
        ws_state: Arc<crate::dashboard::websocket::WebSocketState>,
        project_path: String,
    ) -> Self {
        Self {
            pool,
            notifier: crate::notifications::NotificationSender::new(Some(ws_state)),
            cli_notifier: None, // Dashboard context doesn't need CLI notifier
            project_path: Some(project_path),
        }
    }

    /// Internal helper: Notify UI about event creation
    async fn notify_event_created(&self, event: &Event) {
        use crate::dashboard::websocket::DatabaseOperationPayload;

        // WebSocket notification (Dashboard context)
        if let Some(project_path) = &self.project_path {
            let event_json = match serde_json::to_value(event) {
                Ok(json) => json,
                Err(e) => {
                    tracing::warn!(error = %e, "Failed to serialize event for notification");
                    return;
                },
            };

            let payload =
                DatabaseOperationPayload::event_created(event.id, event_json, project_path.clone());
            self.notifier.send(payload).await;
        }

        // CLI → Dashboard HTTP notification (CLI context)
        if let Some(cli_notifier) = &self.cli_notifier {
            cli_notifier
                .notify_event_added(event.task_id, event.id, self.project_path.clone())
                .await;
        }
    }

    /// Internal helper: Notify UI about event update
    async fn notify_event_updated(&self, event: &Event) {
        use crate::dashboard::websocket::DatabaseOperationPayload;

        let Some(project_path) = &self.project_path else {
            return;
        };

        let event_json = match serde_json::to_value(event) {
            Ok(json) => json,
            Err(e) => {
                tracing::warn!("Failed to serialize event for notification: {}", e);
                return;
            },
        };

        let payload =
            DatabaseOperationPayload::event_updated(event.id, event_json, project_path.clone());
        self.notifier.send(payload).await;
    }

    /// Internal helper: Notify UI about event deletion
    async fn notify_event_deleted(&self, event_id: i64) {
        use crate::dashboard::websocket::DatabaseOperationPayload;

        let Some(project_path) = &self.project_path else {
            return;
        };

        let payload = DatabaseOperationPayload::event_deleted(event_id, project_path.clone());
        self.notifier.send(payload).await;
    }

    /// Add a new event
    pub async fn add_event(
        &self,
        task_id: i64,
        log_type: String,
        discussion_data: String,
    ) -> Result<Event> {
        // Check if task exists
        let task_exists: bool =
            sqlx::query_scalar::<_, bool>(crate::sql_constants::CHECK_TASK_EXISTS)
                .bind(task_id)
                .fetch_one(self.pool)
                .await?;

        if !task_exists {
            return Err(IntentError::TaskNotFound(task_id));
        }

        let now = Utc::now();

        let result = sqlx::query(
            r#"
            INSERT INTO events (task_id, log_type, discussion_data, timestamp)
            VALUES (?, ?, ?, ?)
            "#,
        )
        .bind(task_id)
        .bind(&log_type)
        .bind(&discussion_data)
        .bind(now)
        .execute(self.pool)
        .await?;

        let id = result.last_insert_rowid();

        let event = Event {
            id,
            task_id,
            timestamp: now,
            log_type,
            discussion_data,
        };

        // Notify WebSocket clients about the new event
        self.notify_event_created(&event).await;

        Ok(event)
    }

    /// Update an existing event
    pub async fn update_event(
        &self,
        event_id: i64,
        log_type: Option<&str>,
        discussion_data: Option<&str>,
    ) -> Result<Event> {
        // First, get the existing event to check if it exists
        let existing_event: Option<Event> =
            sqlx::query_as(crate::sql_constants::SELECT_EVENT_BY_ID)
                .bind(event_id)
                .fetch_optional(self.pool)
                .await?;

        let existing_event = existing_event.ok_or(IntentError::InvalidInput(format!(
            "Event {} not found",
            event_id
        )))?;

        // Update only the fields that are provided
        let new_log_type = log_type.unwrap_or(&existing_event.log_type);
        let new_discussion_data = discussion_data.unwrap_or(&existing_event.discussion_data);

        sqlx::query(
            r#"
            UPDATE events
            SET log_type = ?, discussion_data = ?
            WHERE id = ?
            "#,
        )
        .bind(new_log_type)
        .bind(new_discussion_data)
        .bind(event_id)
        .execute(self.pool)
        .await?;

        let updated_event = Event {
            id: existing_event.id,
            task_id: existing_event.task_id,
            timestamp: existing_event.timestamp,
            log_type: new_log_type.to_string(),
            discussion_data: new_discussion_data.to_string(),
        };

        // Notify WebSocket clients about the update
        self.notify_event_updated(&updated_event).await;

        Ok(updated_event)
    }

    /// Delete an event
    pub async fn delete_event(&self, event_id: i64) -> Result<()> {
        // First, get the event to check if it exists and get task_id for notification
        let event: Option<Event> = sqlx::query_as(crate::sql_constants::SELECT_EVENT_BY_ID)
            .bind(event_id)
            .fetch_optional(self.pool)
            .await?;

        let _event = event.ok_or(IntentError::InvalidInput(format!(
            "Event {} not found",
            event_id
        )))?;

        // Delete from FTS index first (if it exists)
        let _ = sqlx::query("DELETE FROM events_fts WHERE rowid = ?")
            .bind(event_id)
            .execute(self.pool)
            .await;

        // Delete the event
        sqlx::query("DELETE FROM events WHERE id = ?")
            .bind(event_id)
            .execute(self.pool)
            .await?;

        // Notify WebSocket clients about the deletion
        self.notify_event_deleted(event_id).await;

        Ok(())
    }

    /// List events for a task (or globally if task_id is None)
    pub async fn list_events(
        &self,
        task_id: Option<i64>,
        limit: Option<i64>,
        log_type: Option<String>,
        since: Option<String>,
    ) -> Result<Vec<Event>> {
        // Check if task exists (only if task_id provided)
        if let Some(tid) = task_id {
            let task_exists: bool =
                sqlx::query_scalar::<_, bool>(crate::sql_constants::CHECK_TASK_EXISTS)
                    .bind(tid)
                    .fetch_one(self.pool)
                    .await?;

            if !task_exists {
                return Err(IntentError::TaskNotFound(tid));
            }
        }

        let limit = limit.unwrap_or(50);

        // Parse since duration if provided
        let since_timestamp = if let Some(duration_str) = since {
            Some(crate::time_utils::parse_duration(&duration_str)?)
        } else {
            None
        };

        // Build dynamic query based on filters
        let mut query = String::from(crate::sql_constants::SELECT_EVENT_BASE);
        let mut conditions = Vec::new();

        if task_id.is_some() {
            conditions.push("task_id = ?");
        }

        if log_type.is_some() {
            conditions.push("log_type = ?");
        }

        if since_timestamp.is_some() {
            conditions.push("timestamp >= ?");
        }

        if !conditions.is_empty() {
            query.push_str(" AND ");
            query.push_str(&conditions.join(" AND "));
        }

        query.push_str(" ORDER BY timestamp DESC LIMIT ?");

        // Build and execute query
        let mut sql_query = sqlx::query_as::<_, Event>(&query);

        if let Some(tid) = task_id {
            sql_query = sql_query.bind(tid);
        }

        if let Some(ref typ) = log_type {
            sql_query = sql_query.bind(typ);
        }

        if let Some(ts) = since_timestamp {
            sql_query = sql_query.bind(ts);
        }

        sql_query = sql_query.bind(limit);

        let events = sql_query.fetch_all(self.pool).await?;

        Ok(events)
    }

    /// Search events using FTS5
    pub async fn search_events_fts5(
        &self,
        query: &str,
        limit: Option<i64>,
    ) -> Result<Vec<EventSearchResult>> {
        let limit = limit.unwrap_or(20);

        // Use FTS5 to search events and get snippets
        let results = sqlx::query(
            r#"
            SELECT
                e.id,
                e.task_id,
                e.timestamp,
                e.log_type,
                e.discussion_data,
                snippet(events_fts, 0, '**', '**', '...', 15) as match_snippet
            FROM events_fts
            INNER JOIN events e ON events_fts.rowid = e.id
            WHERE events_fts MATCH ?
            ORDER BY rank
            LIMIT ?
            "#,
        )
        .bind(query)
        .bind(limit)
        .fetch_all(self.pool)
        .await?;

        let mut search_results = Vec::new();
        for row in results {
            let event = Event {
                id: row.get("id"),
                task_id: row.get("task_id"),
                timestamp: row.get("timestamp"),
                log_type: row.get("log_type"),
                discussion_data: row.get("discussion_data"),
            };
            let match_snippet: String = row.get("match_snippet");

            search_results.push(EventSearchResult {
                event,
                match_snippet,
            });
        }

        Ok(search_results)
    }
}

/// Event search result with match snippet
#[derive(Debug)]
pub struct EventSearchResult {
    pub event: Event,
    pub match_snippet: String,
}

impl crate::backend::EventBackend for EventManager<'_> {
    fn add_event(
        &self,
        task_id: i64,
        log_type: String,
        discussion_data: String,
    ) -> impl std::future::Future<Output = Result<Event>> + Send {
        self.add_event(task_id, log_type, discussion_data)
    }

    fn list_events(
        &self,
        task_id: Option<i64>,
        limit: Option<i64>,
        log_type: Option<String>,
        since: Option<String>,
    ) -> impl std::future::Future<Output = Result<Vec<Event>>> + Send {
        self.list_events(task_id, limit, log_type, since)
    }
}

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

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

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

        assert_eq!(event.task_id, task.id);
        assert_eq!(event.log_type, "decision");
        assert_eq!(event.discussion_data, "Test decision");
    }

    #[tokio::test]
    async fn test_add_event_nonexistent_task() {
        let ctx = TestContext::new().await;
        let event_mgr = EventManager::new(ctx.pool());

        let result = event_mgr
            .add_event(999, "decision".to_string(), "Test".to_string())
            .await;
        assert!(matches!(result, Err(IntentError::TaskNotFound(999))));
    }

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

        let task = task_mgr
            .add_task("Test task".to_string(), None, None, None, None, None)
            .await
            .unwrap();

        // Add multiple events
        event_mgr
            .add_event(task.id, "decision".to_string(), "Decision 1".to_string())
            .await
            .unwrap();
        event_mgr
            .add_event(task.id, "blocker".to_string(), "Blocker 1".to_string())
            .await
            .unwrap();
        event_mgr
            .add_event(task.id, "milestone".to_string(), "Milestone 1".to_string())
            .await
            .unwrap();

        let events = event_mgr
            .list_events(Some(task.id), None, None, None)
            .await
            .unwrap();
        assert_eq!(events.len(), 3);

        // Events should be in reverse chronological order
        assert_eq!(events[0].log_type, "milestone");
        assert_eq!(events[1].log_type, "blocker");
        assert_eq!(events[2].log_type, "decision");
    }

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

        let task = task_mgr
            .add_task("Test task".to_string(), None, None, None, None, None)
            .await
            .unwrap();

        // Add 5 events
        for i in 0..5 {
            event_mgr
                .add_event(task.id, "test".to_string(), format!("Event {}", i))
                .await
                .unwrap();
        }

        let events = event_mgr
            .list_events(Some(task.id), Some(3), None, None)
            .await
            .unwrap();
        assert_eq!(events.len(), 3);
    }

    #[tokio::test]
    async fn test_list_events_nonexistent_task() {
        let ctx = TestContext::new().await;
        let event_mgr = EventManager::new(ctx.pool());

        let result = event_mgr.list_events(Some(999), None, None, None).await;
        assert!(matches!(result, Err(IntentError::TaskNotFound(999))));
    }

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

        let task = task_mgr
            .add_task("Test task".to_string(), None, None, None, None, None)
            .await
            .unwrap();

        let events = event_mgr
            .list_events(Some(task.id), None, None, None)
            .await
            .unwrap();
        assert_eq!(events.len(), 0);
    }

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

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

        // Update event type and data
        let updated = event_mgr
            .update_event(event.id, Some("milestone"), Some("Updated decision"))
            .await
            .unwrap();

        assert_eq!(updated.id, event.id);
        assert_eq!(updated.task_id, task.id);
        assert_eq!(updated.log_type, "milestone");
        assert_eq!(updated.discussion_data, "Updated decision");
    }

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

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

        // Update only discussion_data
        let updated = event_mgr
            .update_event(event.id, None, Some("Updated data only"))
            .await
            .unwrap();

        assert_eq!(updated.log_type, "decision"); // Unchanged
        assert_eq!(updated.discussion_data, "Updated data only");
    }

    #[tokio::test]
    async fn test_update_event_nonexistent() {
        let ctx = TestContext::new().await;
        let event_mgr = EventManager::new(ctx.pool());

        let result = event_mgr
            .update_event(999, Some("decision"), Some("Test"))
            .await;

        assert!(result.is_err());
        assert!(matches!(result, Err(IntentError::InvalidInput(_))));
    }

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

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

        // Delete the event
        event_mgr.delete_event(event.id).await.unwrap();

        // Verify it's deleted
        let events = event_mgr
            .list_events(Some(task.id), None, None, None)
            .await
            .unwrap();
        assert_eq!(events.len(), 0);
    }

    #[tokio::test]
    async fn test_delete_event_nonexistent() {
        let ctx = TestContext::new().await;
        let event_mgr = EventManager::new(ctx.pool());

        let result = event_mgr.delete_event(999).await;
        assert!(result.is_err());
        assert!(matches!(result, Err(IntentError::InvalidInput(_))));
    }

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

        let task = task_mgr
            .add_task("Test task".to_string(), None, None, None, None, None)
            .await
            .unwrap();

        // Add events of different types
        event_mgr
            .add_event(task.id, "decision".to_string(), "Decision 1".to_string())
            .await
            .unwrap();
        event_mgr
            .add_event(task.id, "blocker".to_string(), "Blocker 1".to_string())
            .await
            .unwrap();
        event_mgr
            .add_event(task.id, "decision".to_string(), "Decision 2".to_string())
            .await
            .unwrap();

        // Filter by decision type
        let events = event_mgr
            .list_events(Some(task.id), None, Some("decision".to_string()), None)
            .await
            .unwrap();

        assert_eq!(events.len(), 2);
        assert!(events.iter().all(|e| e.log_type == "decision"));
    }

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

        let task1 = task_mgr
            .add_task("Task 1".to_string(), None, None, None, None, None)
            .await
            .unwrap();
        let task2 = task_mgr
            .add_task("Task 2".to_string(), None, None, None, None, None)
            .await
            .unwrap();

        // Add events to both tasks
        event_mgr
            .add_event(
                task1.id,
                "decision".to_string(),
                "Task 1 Decision".to_string(),
            )
            .await
            .unwrap();
        event_mgr
            .add_event(
                task2.id,
                "decision".to_string(),
                "Task 2 Decision".to_string(),
            )
            .await
            .unwrap();

        // List all events globally (task_id = None)
        let events = event_mgr.list_events(None, None, None, None).await.unwrap();

        assert!(events.len() >= 2); // At least our 2 events
        let task1_events: Vec<_> = events.iter().filter(|e| e.task_id == task1.id).collect();
        let task2_events: Vec<_> = events.iter().filter(|e| e.task_id == task2.id).collect();

        assert_eq!(task1_events.len(), 1);
        assert_eq!(task2_events.len(), 1);
    }
}