minni 0.1.1

Local memory, task, and codebase indexing tool for AI agents
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
use crate::db::Database;
use anyhow::{Context, Result};
use chrono::Utc;
use rusqlite::{params, OptionalExtension};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// Task record.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Task {
    pub id: String,
    pub context_id: String,
    pub seq: i64,
    pub title: String,
    pub description: Option<String>,
    pub status: String,
    pub priority: String,
    pub created_at: String,
    pub updated_at: String,
}

/// Task todo item.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskTodo {
    pub id: String,
    pub task_id: String,
    pub seq: i64,
    pub text: String,
    pub done: bool,
    pub created_at: String,
}

/// Task with todos.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FullTask {
    pub task: Task,
    pub todos: Vec<TaskTodo>,
}

/// Task storage and lookup.
pub struct TaskManager<'a> {
    db: &'a Database,
}

impl<'a> TaskManager<'a> {
    pub fn new(db: &'a Database) -> Self {
        Self { db }
    }

    /// Ensure a context with the given name exists (creates it if absent) and return its id.
    pub fn ensure_context(&self, name: &str) -> Result<String> {
        let project_path = self.db.project_root.to_string_lossy().to_string();
        let now = Utc::now().to_rfc3339();
        let new_id = Uuid::new_v4().to_string();

        // INSERT OR IGNORE so we don't overwrite an existing context
        self.db
            .conn()
            .execute(
                "INSERT OR IGNORE INTO contexts (id, name, description, created_at, updated_at, project_path)
                 VALUES (?1, ?2, NULL, ?3, ?4, ?5)",
                params![new_id, name, now, now, project_path],
            )
            .with_context(|| format!("Failed to ensure context '{name}'"))?;

        let id: String = self
            .db
            .conn()
            .query_row(
                "SELECT id FROM contexts WHERE name = ?1",
                params![name],
                |row| row.get(0),
            )
            .with_context(|| format!("Failed to fetch context id for '{name}'"))?;

        Ok(id)
    }

    /// Look up a context by name; error if it doesn't exist.
    fn lookup_context_id(&self, context_name: &str) -> Result<String> {
        self.db
            .conn()
            .query_row(
                "SELECT id FROM contexts WHERE name = ?1",
                params![context_name],
                |row| row.get(0),
            )
            .optional()
            .with_context(|| format!("Failed to query context '{context_name}'"))?
            .ok_or_else(|| anyhow::anyhow!("context '{}' not found", context_name))
    }

    /// Add a new task to the named context.
    pub fn add_task(
        &self,
        context_name: &str,
        title: &str,
        description: Option<&str>,
        priority: &str,
    ) -> Result<Task> {
        let context_id = self.ensure_context(context_name)?;
        let now = Utc::now().to_rfc3339();
        let id = Uuid::new_v4().to_string();

        // Determine next seq within this context
        let seq: i64 = self
            .db
            .conn()
            .query_row(
                "SELECT COALESCE(MAX(seq), 0) + 1 FROM tasks WHERE context_id = ?1",
                params![context_id],
                |row| row.get(0),
            )
            .with_context(|| {
                format!("Failed to determine next seq for context '{context_name}'")
            })?;

        self.db
            .conn()
            .execute(
                "INSERT INTO tasks (id, context_id, seq, title, description, status, priority, created_at, updated_at)
                 VALUES (?1, ?2, ?3, ?4, ?5, 'pending', ?6, ?7, ?8)",
                params![id, context_id, seq, title, description, priority, now, now],
            )
            .with_context(|| format!("Failed to insert task '{title}'"))?;

        Ok(Task {
            id,
            context_id,
            seq,
            title: title.to_string(),
            description: description.map(str::to_string),
            status: "pending".to_string(),
            priority: priority.to_string(),
            created_at: now.clone(),
            updated_at: now,
        })
    }

    /// Update non-None fields of a task identified by (context_name, seq).
    pub fn update_task(
        &self,
        context_name: &str,
        seq: i64,
        title: Option<&str>,
        description: Option<&str>,
        status: Option<&str>,
        priority: Option<&str>,
    ) -> Result<Task> {
        let task = self.get_task(context_name, seq)?;
        let now = Utc::now().to_rfc3339();

        let new_title = title.unwrap_or(&task.title);
        // description: if caller passes Some("") we treat it as explicit clear;
        // None means "leave unchanged"
        let new_description: Option<&str> = match description {
            Some(d) => Some(d),
            None => task.description.as_deref(),
        };
        let new_status = status.unwrap_or(&task.status);
        let new_priority = priority.unwrap_or(&task.priority);

        self.db
            .conn()
            .execute(
                "UPDATE tasks SET title = ?1, description = ?2, status = ?3, priority = ?4, updated_at = ?5
                 WHERE id = ?6",
                params![new_title, new_description, new_status, new_priority, now, task.id],
            )
            .with_context(|| format!("Failed to update task {seq} in context '{context_name}'"))?;

        Ok(Task {
            id: task.id,
            context_id: task.context_id,
            seq: task.seq,
            title: new_title.to_string(),
            description: new_description.map(str::to_string),
            status: new_status.to_string(),
            priority: new_priority.to_string(),
            created_at: task.created_at,
            updated_at: now,
        })
    }

    /// Retrieve a task by (context_name, seq).
    pub fn get_task(&self, context_name: &str, seq: i64) -> Result<Task> {
        let context_id = self.lookup_context_id(context_name)?;

        let task = self
            .db
            .conn()
            .query_row(
                "SELECT id, context_id, seq, title, description,
                        status, priority, created_at, updated_at
                 FROM tasks
                 WHERE context_id = ?1 AND seq = ?2",
                params![context_id, seq],
                |row| {
                    Ok(Task {
                        id: row.get(0)?,
                        context_id: row.get(1)?,
                        seq: row.get(2)?,
                        title: row.get(3)?,
                        description: row.get(4)?,
                        status: row.get(5)?,
                        priority: row.get(6)?,
                        created_at: row.get(7)?,
                        updated_at: row.get(8)?,
                    })
                },
            )
            .optional()
            .with_context(|| format!("Failed to query task {seq} in context '{context_name}'"))?
            .ok_or_else(|| {
                anyhow::anyhow!("task {} not found in context '{}'", seq, context_name)
            })?;

        Ok(task)
    }

    /// Retrieve a task together with all its todos.
    pub fn get_full_task(&self, context_name: &str, seq: i64) -> Result<FullTask> {
        let task = self.get_task(context_name, seq)?;
        let todos = self.get_todos(&task.id)?;
        Ok(FullTask { task, todos })
    }

    /// List all tasks in a context ordered by seq.
    pub fn list_tasks(&self, context_name: &str) -> Result<Vec<Task>> {
        let context_id = self.lookup_context_id(context_name)?;

        let mut stmt = self
            .db
            .conn()
            .prepare(
                "SELECT id, context_id, seq, title, description,
                        status, priority, created_at, updated_at
                 FROM tasks
                 WHERE context_id = ?1
                 ORDER BY seq",
            )
            .context("Failed to prepare list_tasks statement")?;

        let tasks = stmt
            .query_map(params![context_id], |row| {
                Ok(Task {
                    id: row.get(0)?,
                    context_id: row.get(1)?,
                    seq: row.get(2)?,
                    title: row.get(3)?,
                    description: row.get(4)?,
                    status: row.get(5)?,
                    priority: row.get(6)?,
                    created_at: row.get(7)?,
                    updated_at: row.get(8)?,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(tasks)
    }

    /// Add a todo item to a task identified by (context_name, task_seq).
    pub fn add_todo(&self, context_name: &str, task_seq: i64, text: &str) -> Result<TaskTodo> {
        let task = self.get_task(context_name, task_seq)?;
        let now = Utc::now().to_rfc3339();
        let id = Uuid::new_v4().to_string();

        let seq: i64 = self
            .db
            .conn()
            .query_row(
                "SELECT COALESCE(MAX(seq), 0) + 1 FROM task_todos WHERE task_id = ?1",
                params![task.id],
                |row| row.get(0),
            )
            .with_context(|| format!("Failed to determine next todo seq for task {task_seq}"))?;

        self.db
            .conn()
            .execute(
                "INSERT INTO task_todos (id, task_id, seq, text, done, created_at)
                 VALUES (?1, ?2, ?3, ?4, 0, ?5)",
                params![id, task.id, seq, text, now],
            )
            .with_context(|| format!("Failed to insert todo for task {task_seq}"))?;

        Ok(TaskTodo {
            id,
            task_id: task.id,
            seq,
            text: text.to_string(),
            done: false,
            created_at: now,
        })
    }

    /// Mark a todo item as done.
    pub fn mark_todo_done(&self, context_name: &str, task_seq: i64, todo_seq: i64) -> Result<()> {
        let task = self.get_task(context_name, task_seq)?;

        let rows = self
            .db
            .conn()
            .execute(
                "UPDATE task_todos SET done = 1 WHERE task_id = ?1 AND seq = ?2",
                params![task.id, todo_seq],
            )
            .with_context(|| {
                format!("Failed to mark todo {todo_seq} done on task {task_seq} in context '{context_name}'")
            })?;

        if rows == 0 {
            anyhow::bail!(
                "todo {todo_seq} not found on task {task_seq} in context '{context_name}'"
            );
        }

        Ok(())
    }

    /// Retrieve all todos for a task by its id, ordered by seq.
    pub fn get_todos(&self, task_id: &str) -> Result<Vec<TaskTodo>> {
        let mut stmt = self
            .db
            .conn()
            .prepare(
                "SELECT id, task_id, seq, text, done, created_at
                 FROM task_todos
                 WHERE task_id = ?1
                 ORDER BY seq",
            )
            .context("Failed to prepare get_todos statement")?;

        let todos = stmt
            .query_map(params![task_id], |row| {
                let done_int: i64 = row.get(4)?;
                Ok(TaskTodo {
                    id: row.get(0)?,
                    task_id: row.get(1)?,
                    seq: row.get(2)?,
                    text: row.get(3)?,
                    done: done_int != 0,
                    created_at: row.get(5)?,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(todos)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::SCHEMA;
    use rusqlite::Connection;

    fn in_memory_db() -> Database {
        let conn = Connection::open_in_memory().expect("in-memory DB");
        conn.execute_batch(SCHEMA).expect("schema");
        Database::from_parts(conn, std::path::PathBuf::from("/tmp/test"))
    }

    #[test]
    fn test_add_task_seq_increments() {
        let db = in_memory_db();
        let tm = TaskManager::new(&db);

        let t1 = tm
            .add_task("my-context", "First task", None, "medium")
            .unwrap();
        assert_eq!(t1.seq, 1);

        let t2 = tm
            .add_task("my-context", "Second task", None, "high")
            .unwrap();
        assert_eq!(t2.seq, 2);
    }

    #[test]
    fn test_add_task_separate_contexts_have_independent_seqs() {
        let db = in_memory_db();
        let tm = TaskManager::new(&db);

        let t1 = tm.add_task("ctx-a", "Task A1", None, "low").unwrap();
        assert_eq!(t1.seq, 1);

        let t2 = tm.add_task("ctx-b", "Task B1", None, "low").unwrap();
        assert_eq!(t2.seq, 1);

        let t3 = tm.add_task("ctx-a", "Task A2", None, "low").unwrap();
        assert_eq!(t3.seq, 2);
    }

    #[test]
    fn test_update_task_mutates_only_provided_fields() {
        let db = in_memory_db();
        let tm = TaskManager::new(&db);

        tm.add_task("ctx", "Original title", Some("Original desc"), "medium")
            .unwrap();

        // Update only status
        let updated = tm
            .update_task("ctx", 1, None, None, Some("in_progress"), None)
            .unwrap();

        assert_eq!(updated.title, "Original title");
        assert_eq!(updated.description.as_deref(), Some("Original desc"));
        assert_eq!(updated.status, "in_progress");
        assert_eq!(updated.priority, "medium");
    }

    #[test]

    fn test_update_task_not_found_returns_error() {
        let db = in_memory_db();
        let tm = TaskManager::new(&db);

        // Ensure the context exists so we exercise the "task not found" path
        tm.add_task("ctx", "A task", None, "medium").unwrap();

        let result = tm.update_task("ctx", 99, None, None, None, None);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("task") && msg.contains("not found"),
            "error should mention task not found: {msg}"
        );
    }

    #[test]
    fn test_add_todo_increments_seq() {
        let db = in_memory_db();
        let tm = TaskManager::new(&db);

        tm.add_task("ctx", "A task", None, "medium").unwrap();

        let td1 = tm.add_todo("ctx", 1, "First step").unwrap();
        assert_eq!(td1.seq, 1);

        let td2 = tm.add_todo("ctx", 1, "Second step").unwrap();
        assert_eq!(td2.seq, 2);
    }

    #[test]
    fn test_mark_todo_done_flips_done() {
        let db = in_memory_db();
        let tm = TaskManager::new(&db);

        tm.add_task("ctx", "A task", None, "medium").unwrap();
        tm.add_todo("ctx", 1, "Do something").unwrap();

        // Before marking done
        let full = tm.get_full_task("ctx", 1).unwrap();
        assert!(!full.todos[0].done);

        tm.mark_todo_done("ctx", 1, 1).unwrap();

        let full = tm.get_full_task("ctx", 1).unwrap();
        assert!(full.todos[0].done);
    }

    #[test]
    fn test_mark_todo_done_nonexistent_returns_error() {
        let db = in_memory_db();
        let tm = TaskManager::new(&db);

        tm.add_task("ctx", "A task", None, "medium").unwrap();

        let result = tm.mark_todo_done("ctx", 1, 99);
        assert!(result.is_err());
    }

    #[test]
    fn test_list_tasks_ordered_by_seq() {
        let db = in_memory_db();
        let tm = TaskManager::new(&db);

        tm.add_task("ctx", "C", None, "low").unwrap();
        tm.add_task("ctx", "A", None, "low").unwrap();
        tm.add_task("ctx", "B", None, "low").unwrap();

        let tasks = tm.list_tasks("ctx").unwrap();
        assert_eq!(tasks.len(), 3);
        assert_eq!(tasks[0].seq, 1);
        assert_eq!(tasks[1].seq, 2);
        assert_eq!(tasks[2].seq, 3);
    }

    #[test]
    fn test_get_full_task_includes_todos() {
        let db = in_memory_db();
        let tm = TaskManager::new(&db);

        tm.add_task("ctx", "My task", Some("Details"), "high")
            .unwrap();
        tm.add_todo("ctx", 1, "Step one").unwrap();
        tm.add_todo("ctx", 1, "Step two").unwrap();

        let full = tm.get_full_task("ctx", 1).unwrap();
        assert_eq!(full.task.title, "My task");
        assert_eq!(full.todos.len(), 2);
        assert_eq!(full.todos[0].text, "Step one");
        assert_eq!(full.todos[1].text, "Step two");
    }

    #[test]
    fn test_get_task_nonexistent_context_reports_context_not_found() {
        let db = in_memory_db();
        let tm = TaskManager::new(&db);

        let result = tm.get_task("no-such-context", 1);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("context") && msg.contains("not found"),
            "error should mention context not found: {msg}"
        );
    }

    #[test]
    fn test_get_task_nonexistent_seq_reports_task_not_found() {
        let db = in_memory_db();
        let tm = TaskManager::new(&db);

        // Create the context via add_task, then query a seq that doesn't exist
        tm.add_task("ctx", "A task", None, "medium").unwrap();

        let result = tm.get_task("ctx", 99);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("task") && msg.contains("not found"),
            "error should mention task not found: {msg}"
        );
    }

    #[test]
    fn test_list_tasks_nonexistent_context_reports_context_not_found() {
        let db = in_memory_db();
        let tm = TaskManager::new(&db);

        let result = tm.list_tasks("ghost-context");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("context") && msg.contains("not found"),
            "error should mention context not found: {msg}"
        );
    }
}