koda-core 0.2.9

Core engine for the Koda AI coding agent (macOS and Linux only)
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
//! TodoWrite tool — session-scoped task list.
//!
//! The model maintains the full todo list by rewriting it on every call.
//! Items are persisted to session metadata (survives compaction) and injected
//! into the system prompt each turn so the model always has its plan in view.
//!
//! ## Schema (matches Claude Code's TodoWrite)
//!
//! Each item has:
//! - `content`  — what to do (non-empty string)
//! - `status`   — `"pending"` | `"in_progress"` | `"completed"`
//! - `priority` — `"high"` | `"medium"` | `"low"`

use crate::db::Database;
use crate::persistence::Persistence as _;
use crate::providers::ToolDefinition;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

// ── Schema ─────────────────────────────────────────────────────────────────

/// Completion state of a todo item.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TodoStatus {
    /// Not started.
    Pending,
    /// Currently being worked on (at most one task should be in this state).
    InProgress,
    /// Finished.
    Completed,
}

impl TodoStatus {
    fn from_str(s: &str) -> Option<Self> {
        match s {
            "pending" => Some(Self::Pending),
            "in_progress" => Some(Self::InProgress),
            "completed" => Some(Self::Completed),
            _ => None,
        }
    }

    /// Checkbox-style marker — universally understood.
    fn checkbox(&self) -> &'static str {
        match self {
            Self::Pending => "[ ]",
            Self::InProgress => "[→]",
            Self::Completed => "[x]",
        }
    }
}

/// Relative importance of a todo item.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TodoPriority {
    /// Must be done first.
    High,
    /// Normal importance.
    Medium,
    /// Nice-to-have.
    Low,
}

impl TodoPriority {
    fn from_str(s: &str) -> Option<Self> {
        match s {
            "high" => Some(Self::High),
            "medium" => Some(Self::Medium),
            "low" => Some(Self::Low),
            _ => None,
        }
    }

    /// Compact suffix shown after the task content (only for high priority).
    fn suffix(&self) -> &'static str {
        match self {
            Self::High => "",
            Self::Medium | Self::Low => "",
        }
    }
}

/// A single task in the session todo list.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TodoItem {
    /// Human-readable task description.
    pub content: String,
    /// Current completion state.
    pub status: TodoStatus,
    /// Relative importance.
    pub priority: TodoPriority,
}

// ── Tool definition ─────────────────────────────────────────────────────────

/// Return the tool definition for the LLM.
pub fn definitions() -> Vec<ToolDefinition> {
    vec![ToolDefinition {
        name: "TodoWrite".to_string(),
        description: "Create and manage a structured task list for the current session. \
            Rewrite the full list on every call — include all tasks, not just changed ones. \
            Use proactively for: multi-step tasks (3+ steps), complex refactors, or when \
            the user provides a list of things to do. Mark tasks `in_progress` BEFORE \
            starting and `completed` immediately after finishing. Only one task should be \
            `in_progress` at a time."
            .to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "todos": {
                    "type": "array",
                    "description": "The complete todo list (replaces any previous list)",
                    "items": {
                        "type": "object",
                        "properties": {
                            "content": {
                                "type": "string",
                                "description": "Actionable task description in imperative form"
                            },
                            "status": {
                                "type": "string",
                                "enum": ["pending", "in_progress", "completed"],
                                "description": "Current status of the task"
                            },
                            "priority": {
                                "type": "string",
                                "enum": ["high", "medium", "low"],
                                "description": "Task priority"
                            }
                        },
                        "required": ["content", "status", "priority"]
                    }
                }
            },
            "required": ["todos"]
        }),
    }]
}

// ── Handler ─────────────────────────────────────────────────────────────────

/// Write the full todo list for this session.
///
/// **Content-aware dedup**: if the incoming list is identical to what's
/// already stored, we skip the write and return a short "unchanged"
/// message. This prevents the model from burning tool calls (and
/// triggering loop detection) by re-emitting the same plan.
pub async fn todo_write(db: &Database, session_id: &str, args: &Value) -> Result<String> {
    let raw = args
        .get("todos")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow::anyhow!("Missing 'todos' array"))?;

    let mut todos: Vec<TodoItem> = Vec::with_capacity(raw.len());
    for (i, item) in raw.iter().enumerate() {
        let content = item
            .get("content")
            .and_then(|v| v.as_str())
            .filter(|s| !s.trim().is_empty())
            .ok_or_else(|| anyhow::anyhow!("todos[{i}]: 'content' must be a non-empty string"))?
            .to_string();

        let status_str = item
            .get("status")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("todos[{i}]: missing 'status'"))?;
        let status = TodoStatus::from_str(status_str).ok_or_else(|| {
            anyhow::anyhow!(
                "todos[{i}]: invalid status '{status_str}' — use pending/in_progress/completed"
            )
        })?;

        let priority_str = item
            .get("priority")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("todos[{i}]: missing 'priority'"))?;
        let priority = TodoPriority::from_str(priority_str).ok_or_else(|| {
            anyhow::anyhow!("todos[{i}]: invalid priority '{priority_str}' — use high/medium/low")
        })?;

        todos.push(TodoItem {
            content,
            status,
            priority,
        });
    }

    // ── Content-aware dedup ──────────────────────────────────────────
    // Compare with what's already stored. If identical, skip the write
    // and tell the model explicitly so it stops re-emitting the same plan.
    if let Ok(Some(existing_json)) = db.get_todo(session_id).await
        && let Ok(existing) = serde_json::from_str::<Vec<TodoItem>>(&existing_json)
        && existing == todos
    {
        return Ok(format!(
            "Todo list unchanged ({} task{}). \
             Do not call TodoWrite again unless you are changing a task's status or content.",
            todos.len(),
            if todos.len() == 1 { "" } else { "s" }
        ));
    }

    let json = serde_json::to_string(&todos)?;
    db.set_todo(session_id, &json).await?;

    Ok(format_todo_list(&todos))
}

/// Load the todo section for injection into the system prompt.
///
/// Returns an empty string when no todos are stored (zero cost).
pub async fn get_todo_section(db: &Database, session_id: &str) -> String {
    let Ok(Some(raw)) = db.get_todo(session_id).await else {
        return String::new();
    };
    let Ok(todos) = serde_json::from_str::<Vec<TodoItem>>(&raw) else {
        return String::new();
    };
    if todos.is_empty() {
        return String::new();
    }

    // Only surface non-completed tasks in the prompt (completed ones are noise).
    let active: Vec<&TodoItem> = todos
        .iter()
        .filter(|t| t.status != TodoStatus::Completed)
        .collect();

    if active.is_empty() {
        return String::new();
    }

    let mut out = "\n## Current Tasks\n".to_string();
    for t in &active {
        out.push_str(&format!("{}{}\n", format_item(t), t.priority.suffix(),));
    }
    out
}

// ── Formatting ──────────────────────────────────────────────────────────────

/// Format a single todo item: `[x] Task description`
fn format_item(t: &TodoItem) -> String {
    format!("{} {}", t.status.checkbox(), t.content)
}

fn format_todo_list(todos: &[TodoItem]) -> String {
    if todos.is_empty() {
        return "Todo list cleared.".to_string();
    }

    let completed = todos
        .iter()
        .filter(|t| t.status == TodoStatus::Completed)
        .count();

    let mut out = format!("Todo list updated ({}/{} done):\n", completed, todos.len(),);
    for t in todos {
        out.push_str(&format!("  {}{}\n", format_item(t), t.priority.suffix()));
    }
    out
}

// ── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use tempfile::TempDir;

    async fn test_db() -> (Database, TempDir, String) {
        let dir = TempDir::new().unwrap();
        let db = Database::open(&dir.path().join("test.db")).await.unwrap();
        use crate::persistence::Persistence;
        let sid = db.create_session("koda", dir.path()).await.unwrap();
        (db, dir, sid)
    }

    #[tokio::test]
    async fn write_and_read_back() {
        let (db, _dir, sid) = test_db().await;
        let args = json!({
            "todos": [
                {"content": "Add tests", "status": "pending", "priority": "high"},
                {"content": "Write docs", "status": "in_progress", "priority": "medium"},
            ]
        });
        let out = todo_write(&db, &sid, &args).await.unwrap();
        assert!(out.contains("0/2 done"));
        assert!(out.contains("[ ] Add tests"));
        assert!(out.contains("[→] Write docs"));

        let section = get_todo_section(&db, &sid).await;
        assert!(section.contains("Add tests"));
        assert!(section.contains("Write docs"));
    }

    #[tokio::test]
    async fn completed_tasks_hidden_from_section() {
        let (db, _dir, sid) = test_db().await;
        let args = json!({
            "todos": [
                {"content": "Done task", "status": "completed", "priority": "low"},
                {"content": "Active task", "status": "pending", "priority": "high"},
            ]
        });
        todo_write(&db, &sid, &args).await.unwrap();
        let section = get_todo_section(&db, &sid).await;
        assert!(
            !section.contains("Done task"),
            "completed tasks should be hidden"
        );
        assert!(section.contains("Active task"));
    }

    #[tokio::test]
    async fn all_completed_returns_empty_section() {
        let (db, _dir, sid) = test_db().await;
        let args = json!({
            "todos": [
                {"content": "Done", "status": "completed", "priority": "medium"}
            ]
        });
        todo_write(&db, &sid, &args).await.unwrap();
        assert!(get_todo_section(&db, &sid).await.is_empty());
    }

    #[tokio::test]
    async fn empty_list_clears_todos() {
        let (db, _dir, sid) = test_db().await;
        // First write something
        let args = json!({ "todos": [
            {"content": "Task", "status": "pending", "priority": "low"}
        ]});
        todo_write(&db, &sid, &args).await.unwrap();
        // Then clear it
        let clear = json!({ "todos": [] });
        let out = todo_write(&db, &sid, &clear).await.unwrap();
        assert!(out.contains("cleared"));
        assert!(get_todo_section(&db, &sid).await.is_empty());
    }

    #[tokio::test]
    async fn invalid_status_returns_error() {
        let (db, _dir, sid) = test_db().await;
        let args = json!({
            "todos": [{"content": "Task", "status": "doing", "priority": "high"}]
        });
        let err = todo_write(&db, &sid, &args).await.unwrap_err();
        assert!(err.to_string().contains("invalid status"));
    }

    #[tokio::test]
    async fn invalid_priority_returns_error() {
        let (db, _dir, sid) = test_db().await;
        let args = json!({
            "todos": [{"content": "Task", "status": "pending", "priority": "urgent"}]
        });
        let err = todo_write(&db, &sid, &args).await.unwrap_err();
        assert!(err.to_string().contains("invalid priority"));
    }

    #[tokio::test]
    async fn empty_content_returns_error() {
        let (db, _dir, sid) = test_db().await;
        let args = json!({
            "todos": [{"content": "  ", "status": "pending", "priority": "low"}]
        });
        let err = todo_write(&db, &sid, &args).await.unwrap_err();
        assert!(err.to_string().contains("non-empty"));
    }

    #[tokio::test]
    async fn missing_todos_field_returns_error() {
        let (db, _dir, sid) = test_db().await;
        let err = todo_write(&db, &sid, &json!({})).await.unwrap_err();
        assert!(err.to_string().contains("todos"));
    }

    #[test]
    fn format_single_task() {
        let todos = vec![TodoItem {
            content: "Ship it".into(),
            status: TodoStatus::InProgress,
            priority: TodoPriority::High,
        }];
        let out = format_todo_list(&todos);
        assert!(out.contains("0/1 done"));
        assert!(out.contains("[→] Ship it"));
        // High priority gets a suffix
        assert!(out.contains(""));
    }

    #[test]
    fn format_completed_task() {
        let todos = vec![
            TodoItem {
                content: "Done thing".into(),
                status: TodoStatus::Completed,
                priority: TodoPriority::Medium,
            },
            TodoItem {
                content: "Todo thing".into(),
                status: TodoStatus::Pending,
                priority: TodoPriority::Low,
            },
        ];
        let out = format_todo_list(&todos);
        assert!(out.contains("1/2 done"));
        assert!(out.contains("[x] Done thing"));
        assert!(out.contains("[ ] Todo thing"));
        // Medium/Low priority: no suffix
        assert!(!out.contains("") || !out.contains("Done thing ⚡"));
    }

    #[test]
    fn status_checkbox_coverage() {
        assert_eq!(TodoStatus::Pending.checkbox(), "[ ]");
        assert_eq!(TodoStatus::InProgress.checkbox(), "[→]");
        assert_eq!(TodoStatus::Completed.checkbox(), "[x]");
    }

    #[tokio::test]
    async fn dedup_skips_identical_write() {
        let (db, _dir, sid) = test_db().await;
        let args = json!({
            "todos": [
                {"content": "Task A", "status": "pending", "priority": "high"},
                {"content": "Task B", "status": "in_progress", "priority": "medium"},
            ]
        });
        // First write — should persist and return full list
        let out1 = todo_write(&db, &sid, &args).await.unwrap();
        assert!(out1.contains("0/2 done"));

        // Second write with identical content — should short-circuit
        let out2 = todo_write(&db, &sid, &args).await.unwrap();
        assert!(
            out2.contains("unchanged"),
            "identical call should return 'unchanged', got: {out2}"
        );
        assert!(
            out2.contains("Do not call TodoWrite again"),
            "should tell model to stop calling"
        );
    }

    #[tokio::test]
    async fn dedup_allows_status_change() {
        let (db, _dir, sid) = test_db().await;
        let args1 = json!({
            "todos": [
                {"content": "Task A", "status": "pending", "priority": "high"},
            ]
        });
        todo_write(&db, &sid, &args1).await.unwrap();

        // Same content but status changed — should NOT short-circuit
        let args2 = json!({
            "todos": [
                {"content": "Task A", "status": "completed", "priority": "high"},
            ]
        });
        let out = todo_write(&db, &sid, &args2).await.unwrap();
        assert!(
            out.contains("1/1 done"),
            "status change should write normally, got: {out}"
        );
        assert!(out.contains("[x] Task A"));
    }
}