heartbit-core 2026.613.1

The Rust agentic framework — agents, tools, LLM providers, memory, evaluation.
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
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, RwLock};

use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::error::Error;
use crate::llm::types::ToolDefinition;
use crate::tool::{Tool, ToolOutput};

// --- TodoStore ---

/// A single item in the agent's task list.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TodoItem {
    /// The task description.
    pub content: String,
    /// Current status of the task.
    pub status: TodoStatus,
    /// Priority level of the task.
    pub priority: TodoPriority,
    /// Observable done-condition for this item ("done when: …"). The
    /// completion-loop harness uses it as the per-loop acceptance criterion;
    /// recited alongside the content so it stays in recent attention.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub acceptance: Option<String>,
}

/// Status of a to-do item.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TodoStatus {
    /// Task has not been started.
    Pending,
    /// Task is currently being worked on (at most one at a time).
    InProgress,
    /// Task has been successfully completed.
    Completed,
    /// Task was abandoned.
    Cancelled,
    /// Task could not be completed due to an error.
    Failed,
    /// Task is waiting on an external dependency.
    Blocked,
}

impl std::fmt::Display for TodoStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TodoStatus::Pending => write!(f, "pending"),
            TodoStatus::InProgress => write!(f, "in_progress"),
            TodoStatus::Completed => write!(f, "completed"),
            TodoStatus::Cancelled => write!(f, "cancelled"),
            TodoStatus::Failed => write!(f, "failed"),
            TodoStatus::Blocked => write!(f, "blocked"),
        }
    }
}

/// Priority level of a to-do item.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TodoPriority {
    /// Must be done immediately.
    Critical,
    /// Should be done next.
    High,
    /// Normal priority.
    Medium,
    /// Do when convenient.
    Low,
}

impl std::fmt::Display for TodoPriority {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TodoPriority::Critical => write!(f, "critical"),
            TodoPriority::High => write!(f, "high"),
            TodoPriority::Medium => write!(f, "medium"),
            TodoPriority::Low => write!(f, "low"),
        }
    }
}

/// Shared in-process store for agent to-do items.
///
/// Accessed via the `todo_read` and `todo_write` builtin tools.
/// Thread-safe: backed by a `std::sync::RwLock`.
pub struct TodoStore {
    todos: RwLock<Vec<TodoItem>>,
}

impl Default for TodoStore {
    fn default() -> Self {
        Self::new()
    }
}

impl TodoStore {
    /// Create an empty `TodoStore`.
    pub fn new() -> Self {
        Self {
            todos: RwLock::new(Vec::new()),
        }
    }

    fn set(&self, todos: Vec<TodoItem>) -> Result<(), String> {
        // Validate: at most 1 item can be in_progress
        let in_progress_count = todos
            .iter()
            .filter(|t| t.status == TodoStatus::InProgress)
            .count();
        if in_progress_count > 1 {
            return Err(format!(
                "Only 1 item can be in_progress at a time (got {in_progress_count})"
            ));
        }

        let mut guard = self.todos.write().expect("todo store lock poisoned");
        *guard = todos;
        Ok(())
    }

    fn get_all(&self) -> Vec<TodoItem> {
        let guard = self.todos.read().expect("todo store lock poisoned");
        guard.clone()
    }

    /// Open (actionable) items — `Pending` or `InProgress` — in list order.
    ///
    /// Long-horizon planning (recitation): the agent loop reads this each turn
    /// and re-surfaces the live plan at the context tail so it stays in recent
    /// attention. Returns an empty Vec for trivial/chat tasks that never wrote
    /// any todos, so recitation self-gates to zero overhead.
    pub fn open_items(&self) -> Vec<TodoItem> {
        self.todos
            .read()
            .expect("todo store lock poisoned")
            .iter()
            .filter(|t| matches!(t.status, TodoStatus::Pending | TodoStatus::InProgress))
            .cloned()
            .collect()
    }
}

/// Format open todo items as a compact recitation block to append at the
/// context tail. Returns `None` when there are no open items (the caller then
/// appends nothing — trivial tasks pay no cost).
///
/// Long-horizon planning: re-surfacing the *actual* plan (not a re-derived
/// textual summary) every turn counters lost-in-the-middle and means the plan
/// survives compaction automatically (next turn re-recites from the store).
pub(crate) fn recite_open_todos(items: &[TodoItem]) -> Option<String> {
    if items.is_empty() {
        return None;
    }
    let mut s = String::from("[plan — open items, stay on these until done]\n");
    for item in items {
        let mark = if item.status == TodoStatus::InProgress {
            "[>]"
        } else {
            "[ ]"
        };
        s.push_str(mark);
        s.push(' ');
        s.push_str(&item.content);
        if let Some(acceptance) = &item.acceptance {
            s.push_str(" — done when: ");
            s.push_str(acceptance);
        }
        s.push('\n');
    }
    Some(s)
}

// --- Tools ---

/// Create the `todo_read` and `todo_write` tool pair sharing a single store.
pub fn todo_tools(store: Arc<TodoStore>) -> Vec<Arc<dyn Tool>> {
    vec![
        Arc::new(TodoWriteTool {
            store: store.clone(),
        }),
        Arc::new(TodoReadTool { store }),
    ]
}

struct TodoWriteTool {
    store: Arc<TodoStore>,
}

impl Tool for TodoWriteTool {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition {
            name: "todowrite".into(),
            description:
                "Write/replace the full todo list. Only 1 item can be in_progress at a time. \
                          This replaces the entire list (not append)."
                    .into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "todos": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "content": {"type": "string"},
                                "status": {
                                    "type": "string",
                                    "enum": ["pending", "in_progress", "completed", "cancelled", "failed", "blocked"]
                                },
                                "priority": {
                                    "type": "string",
                                    "enum": ["critical", "high", "medium", "low"]
                                },
                                "acceptance": {
                                    "type": "string",
                                    "description": "Observable done-condition for this item (e.g. 'cargo test green', 'GET /health returns 200'). Recommended for feature work."
                                }
                            },
                            "required": ["content", "status", "priority"]
                        }
                    }
                },
                "required": ["todos"]
            }),
        }
    }

    fn execute(
        &self,
        _ctx: &crate::ExecutionContext,
        input: serde_json::Value,
    ) -> Pin<Box<dyn Future<Output = Result<ToolOutput, Error>> + Send + '_>> {
        Box::pin(async move {
            let todos_value = input
                .get("todos")
                .ok_or_else(|| Error::Agent("todos is required".into()))?;

            let todos: Vec<TodoItem> = serde_json::from_value(todos_value.clone())
                .map_err(|e| Error::Agent(format!("Invalid todo list: {e}")))?;

            if let Err(msg) = self.store.set(todos) {
                return Ok(ToolOutput::error(msg));
            }

            let all = self.store.get_all();
            Ok(ToolOutput::success(format!(
                "Todo list updated ({} items)",
                all.len()
            )))
        })
    }
}

struct TodoReadTool {
    store: Arc<TodoStore>,
}

impl Tool for TodoReadTool {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition {
            name: "todoread".into(),
            description: "Read the current todo list.".into(),
            input_schema: json!({"type": "object"}),
        }
    }

    fn execute(
        &self,
        _ctx: &crate::ExecutionContext,
        _input: serde_json::Value,
    ) -> Pin<Box<dyn Future<Output = Result<ToolOutput, Error>> + Send + '_>> {
        Box::pin(async move {
            let todos = self.store.get_all();

            if todos.is_empty() {
                return Ok(ToolOutput::success("No todos."));
            }

            let mut output = String::new();
            for (i, todo) in todos.iter().enumerate() {
                let status_icon = match todo.status {
                    TodoStatus::Pending => "[ ]",
                    TodoStatus::InProgress => "[>]",
                    TodoStatus::Completed => "[x]",
                    TodoStatus::Cancelled => "[-]",
                    TodoStatus::Failed => "[!]",
                    TodoStatus::Blocked => "[B]",
                };
                let priority_tag = match todo.priority {
                    TodoPriority::Critical => " [CRITICAL]",
                    TodoPriority::High => " [HIGH]",
                    TodoPriority::Medium => "",
                    TodoPriority::Low => " [low]",
                };
                output.push_str(&format!(
                    "{}. {} {}{}\n",
                    i + 1,
                    status_icon,
                    todo.content,
                    priority_tag
                ));
            }

            Ok(ToolOutput::success(output))
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn item(content: &str, status: TodoStatus) -> TodoItem {
        TodoItem {
            content: content.into(),
            status,
            priority: TodoPriority::Medium,
            acceptance: None,
        }
    }

    #[test]
    fn open_items_filters_done_and_keeps_order() {
        let store = TodoStore::new();
        store
            .set(vec![
                item("a", TodoStatus::Pending),
                item("b", TodoStatus::Completed),
                item("c", TodoStatus::InProgress),
                item("d", TodoStatus::Cancelled),
            ])
            .unwrap();
        let open = store.open_items();
        let contents: Vec<&str> = open.iter().map(|i| i.content.as_str()).collect();
        assert_eq!(
            contents,
            vec!["a", "c"],
            "only Pending/InProgress, in order"
        );
    }

    #[test]
    fn recite_empty_is_none() {
        assert!(recite_open_todos(&[]).is_none());
    }

    #[test]
    fn recite_formats_open_items_with_marks() {
        let block = recite_open_todos(&[
            item("write tests", TodoStatus::InProgress),
            item("ship it", TodoStatus::Pending),
        ])
        .expect("non-empty");
        assert!(
            block.contains("[>] write tests"),
            "in-progress marker: {block}"
        );
        assert!(block.contains("[ ] ship it"), "pending marker: {block}");
        // in_progress comes before pending in the input order
        assert!(block.find("write tests").unwrap() < block.find("ship it").unwrap());
    }

    #[test]
    fn todo_item_carries_acceptance_condition() {
        // Per-loop done-condition (completion-loop harness P1): a todowrite
        // payload may attach an observable acceptance criterion to each item.
        let item: TodoItem = serde_json::from_value(json!({
            "content": "add /health endpoint",
            "status": "in_progress",
            "priority": "high",
            "acceptance": "GET /health returns 200 and cargo test is green"
        }))
        .expect("acceptance field deserializes");
        assert_eq!(
            item.acceptance.as_deref(),
            Some("GET /health returns 200 and cargo test is green")
        );
        // Round-trips through serialization.
        let back: TodoItem =
            serde_json::from_value(serde_json::to_value(&item).expect("ser")).expect("de");
        assert_eq!(back.acceptance, item.acceptance);
        // Back-compat: payloads WITHOUT the field still deserialize.
        let legacy: TodoItem = serde_json::from_value(json!({
            "content": "x", "status": "pending", "priority": "low"
        }))
        .expect("legacy payload still valid");
        assert!(legacy.acceptance.is_none());
        // Recitation surfaces the done-condition for open items.
        let block = recite_open_todos(&[item]).expect("non-empty");
        assert!(
            block.contains("done when: GET /health returns 200"),
            "acceptance line missing from recitation: {block}"
        );
    }

    #[test]
    fn definition_names() {
        let store = Arc::new(TodoStore::new());
        let tools = todo_tools(store);
        let names: Vec<String> = tools.iter().map(|t| t.definition().name).collect();
        assert!(names.contains(&"todowrite".to_string()));
        assert!(names.contains(&"todoread".to_string()));
    }

    #[tokio::test]
    async fn todowrite_and_read() {
        let store = Arc::new(TodoStore::new());
        let tools = todo_tools(store);
        let write_tool = &tools[0];
        let read_tool = &tools[1];

        // Write some todos
        let result = write_tool
            .execute(
                &crate::ExecutionContext::default(),
                json!({
                    "todos": [
                        {"content": "Fix bug", "status": "in_progress", "priority": "high"},
                        {"content": "Write tests", "status": "pending", "priority": "medium"}
                    ]
                }),
            )
            .await
            .unwrap();
        assert!(!result.is_error, "got error: {}", result.content);
        assert!(result.content.contains("2 items"));

        // Read them back
        let result = read_tool
            .execute(&crate::ExecutionContext::default(), json!({}))
            .await
            .unwrap();
        assert!(!result.is_error);
        assert!(result.content.contains("Fix bug"));
        assert!(result.content.contains("[HIGH]"));
        assert!(result.content.contains("Write tests"));
        assert!(result.content.contains("[>]")); // in_progress
    }

    #[tokio::test]
    async fn todowrite_rejects_multiple_in_progress() {
        let store = Arc::new(TodoStore::new());
        let tools = todo_tools(store);
        let write_tool = &tools[0];

        let result = write_tool
            .execute(
                &crate::ExecutionContext::default(),
                json!({
                    "todos": [
                        {"content": "Task 1", "status": "in_progress", "priority": "high"},
                        {"content": "Task 2", "status": "in_progress", "priority": "high"}
                    ]
                }),
            )
            .await
            .unwrap();
        assert!(result.is_error);
        assert!(result.content.contains("Only 1 item"));
    }

    #[tokio::test]
    async fn todoread_empty() {
        let store = Arc::new(TodoStore::new());
        let tools = todo_tools(store);
        let read_tool = &tools[1];

        let result = read_tool
            .execute(&crate::ExecutionContext::default(), json!({}))
            .await
            .unwrap();
        assert!(!result.is_error);
        assert!(result.content.contains("No todos"));
    }

    #[tokio::test]
    async fn todowrite_replaces_full_list() {
        let store = Arc::new(TodoStore::new());
        let tools = todo_tools(store);
        let write_tool = &tools[0];
        let read_tool = &tools[1];

        // First write
        write_tool
            .execute(
                &crate::ExecutionContext::default(),
                json!({"todos": [{"content": "Old", "status": "pending", "priority": "low"}]}),
            )
            .await
            .unwrap();

        // Second write replaces
        write_tool
            .execute(
                &crate::ExecutionContext::default(),
                json!({"todos": [{"content": "New", "status": "completed", "priority": "high"}]}),
            )
            .await
            .unwrap();

        let result = read_tool
            .execute(&crate::ExecutionContext::default(), json!({}))
            .await
            .unwrap();
        assert!(result.content.contains("New"));
        assert!(!result.content.contains("Old"));
    }
}