agent: per-session todo queue (todo tool, pinned TODO section, GUI panel)

Persistent task list (pending/doing/done) with never-reused seq from a per-session high-water mark; open items injected as a dynamic TODO section with pre-warm-on-change; read-only GUI panel + i18n; TOOL_USE manual extended. Docs updated; agent-feedback memory Q&A exchange and AGENT_RULES seed rules included. Verified: 245 passed / 6 ignored, clippy+fmt clean; dogfooded live.
This commit is contained in:
adm committed 2026-11-30 12:10:45 +01:00
1 parent f74d53e446
commit 9b05592efb
16 files changed
+1067 -21

No files matched your search

+6 -2
View File
@@ -13,6 +13,7 @@ pub mod memory;
pub mod notepad;
pub mod share;
pub mod shell;
pub mod todo;
use std::future::Future;
use std::sync::Arc;
@@ -35,12 +36,14 @@ pub const MAX_ITERS: usize = 24;
pub const REPEAT_LIMIT: usize = 3;
/// The tools offered to the agent: the universal `shell_exec` (action), the
/// `notepad` (per-session context management) and `share_file` (hand the user a
/// download link for a file the agent has on disk).
/// `notepad` (per-session context management), `todo` (the per-session task
/// queue) and `share_file` (hand the user a download link for a file the agent
/// has on disk).
pub fn agent_tools() -> Json {
json!([
shell::shell_exec_declaration(),
notepad::notepad_declaration(),
todo::todo_declaration(),
share::share_file_declaration()
])
}
@@ -108,6 +111,7 @@ async fn execute_tool(
}
}
"notepad" => notepad::execute(store, session_id, &args).await,
"todo" => todo::execute(store, session_id, &args).await,
"share_file" => share::execute(session_id, &args, default_cwd, workspace_root).await,
"remember" | "recall" | "forget" => match memory {
Some(m) => memory::execute(m, session_id, &tc.function.name, &args).await,
+319
View File
@@ -0,0 +1,319 @@
//! The agent's todo tool: a persistent, per-session task list (the operational
//! work queue) that survives restarts and the sliding context window.
//!
//! One action-based tool (`add`/`update`/`remove`/`clear_done`); items are
//! addressed by a stable numeric `seq` (never reused or renumbered). Open items
//! (pending/doing) are injected as the pinned `<TODO>` section above DIALOG;
//! done items stay in history until pruned. Bounded by an open-item cap and a
//! per-item char cap — nothing is evicted automatically. Distinct from the
//! notepad: the notepad curates durable knowledge, the todo tracks work.
use std::sync::Arc;
use anyhow::Result;
use serde_json::{json, Value as Json};
use crate::store::Store;
/// Per-item char cap (unicode-aware). Over-long items are refused, not
/// silently truncated: a task is a short actionable step, not a document.
const MAX_ITEM_CHARS: usize = 512;
/// Max OPEN items (pending + doing). Over it, an `add` is refused and the agent
/// is asked to finish or remove stale tasks itself.
const MAX_OPEN_ITEMS: usize = 30;
/// The OpenAI function declaration offered to the model for the agent.
pub fn todo_declaration() -> Json {
json!({
"type": "function",
"function": {
"name": "todo",
"description": "Manage your persistent per-session task list, always visible above \
the dialog. Use it for multi-step operational work: plan the steps with add, \
mark doing what you are working on and done as soon as it is finished — it is \
your resume point across restarts and wake-ups. The notepad holds durable \
knowledge (goals, decisions, constraints); the todo holds the work queue. Items \
are addressed by a stable numeric seq (never renumbered). Only open items \
(pending/doing) are shown in your context; done items stay in history until \
clear_done. Bounded: at most 30 open items — finish or remove stale ones. Keep \
each task short and actionable.",
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["add", "update", "remove", "clear_done"],
"description": "add appends a pending task; update changes status/content of task `seq`; remove deletes task `seq`; clear_done prunes all completed tasks."
},
"seq": {
"type": "integer",
"description": "Stable id of the task (required for update/remove), as shown in the TODO block."
},
"status": {
"type": "string",
"enum": ["pending", "doing", "done"],
"description": "New status (update only)."
},
"content": {
"type": "string",
"description": "Short task text (required for add, optional for update, max 512 chars)."
}
},
"required": ["action"]
}
}
})
}
/// Execute a todo tool call against the store, returning the text the model
/// reads as the tool result. Store work runs off the async runtime.
pub async fn execute(store: &Arc<dyn Store>, session_id: &str, args: &Json) -> String {
let action = args
.get("action")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let seq = args.get("seq").and_then(|v| v.as_i64());
let status = args
.get("status")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let content = args
.get("content")
.and_then(|v| v.as_str())
.map(|s| s.trim().replace("\r\n", "\n").replace('\r', "\n"));
let store = store.clone();
let sid = session_id.to_string();
let res = tokio::task::spawn_blocking(move || -> Result<String> {
match action.as_str() {
"add" => {
let Some(content) = content.filter(|c| !c.is_empty()) else {
return Ok("error: todo add requires non-empty 'content'".into());
};
let nlen = content.chars().count();
if nlen > MAX_ITEM_CHARS {
return Ok(format!(
"error: task too long ({nlen} > {MAX_ITEM_CHARS} chars); shorten it"
));
}
let open = store
.todos(&sid)?
.iter()
.filter(|i| i.status != "done")
.count();
if open >= MAX_OPEN_ITEMS {
return Ok(format!(
"error: todo full ({open} open items, max {MAX_OPEN_ITEMS}). Finish \
(update status=done) or remove stale tasks, then retry. Nothing is \
evicted automatically."
));
}
let item = store.add_todo(&sid, &content)?;
Ok(format!(
"Task {} added (pending). Open items: {}/{MAX_OPEN_ITEMS}.",
item.seq,
open + 1
))
}
"update" => {
let Some(seq) = seq else {
return Ok("error: todo update requires 'seq'".into());
};
if status.is_none() && content.is_none() {
return Ok("error: todo update requires 'status' and/or 'content'".into());
}
if let Some(s) = &status {
if !matches!(s.as_str(), "pending" | "doing" | "done") {
return Ok(format!(
"error: unknown status '{s}' (use pending|doing|done)"
));
}
}
if let Some(c) = &content {
if c.is_empty() {
return Ok("error: 'content' must not be empty".into());
}
let nlen = c.chars().count();
if nlen > MAX_ITEM_CHARS {
return Ok(format!(
"error: task too long ({nlen} > {MAX_ITEM_CHARS} chars); shorten it"
));
}
}
let existed =
store.update_todo(&sid, seq, status.as_deref(), content.as_deref())?;
if existed {
let item = store
.todos(&sid)?
.into_iter()
.find(|i| i.seq == seq)
.expect("just updated");
Ok(format!("Task {} updated ({}).", seq, item.status))
} else {
Ok(format!("No task {seq} (nothing updated)."))
}
}
"remove" => {
let Some(seq) = seq else {
return Ok("error: todo remove requires 'seq'".into());
};
let existed = store.remove_todo(&sid, seq)?;
if existed {
Ok(format!("Task {seq} removed."))
} else {
Ok(format!("No task {seq} (nothing removed)."))
}
}
"clear_done" => {
let n = store.clear_done_todos(&sid)?;
Ok(format!("Removed {n} completed tasks."))
}
other => Ok(format!(
"error: unknown todo action '{other}' (use add|update|remove|clear_done)"
)),
}
})
.await;
match res {
Ok(Ok(msg)) => msg,
Ok(Err(e)) => format!("error: {e}"),
Err(e) => format!("error: todo task failed: {e}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::store::{SessionSettings, SqliteStore};
fn setup() -> (Arc<dyn Store>, String) {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
let sess = store
.create_session("Chat", "m", &SessionSettings::default())
.unwrap();
(store, sess.id)
}
#[tokio::test]
async fn add_update_remove_clear_done() {
let (store, sid) = setup();
let out = execute(&store, &sid, &json!({"action":"add","content":"step one"})).await;
assert!(out.contains("Task 1 added"), "{out}");
execute(&store, &sid, &json!({"action":"add","content":"step two"})).await;
// Status transition.
let out = execute(
&store,
&sid,
&json!({"action":"update","seq":1,"status":"doing"}),
)
.await;
assert!(out.contains("doing"), "{out}");
assert_eq!(store.todos(&sid).unwrap()[0].status, "doing");
// Content edit keeps the status.
execute(
&store,
&sid,
&json!({"action":"update","seq":1,"content":"step one (revised)"}),
)
.await;
let items = store.todos(&sid).unwrap();
assert_eq!(items[0].content, "step one (revised)");
assert_eq!(items[0].status, "doing");
// Done + clear_done prunes only completed items.
execute(
&store,
&sid,
&json!({"action":"update","seq":1,"status":"done"}),
)
.await;
let out = execute(&store, &sid, &json!({"action":"clear_done"})).await;
assert!(out.contains("Removed 1"), "{out}");
let items = store.todos(&sid).unwrap();
assert_eq!(items.len(), 1);
assert_eq!(items[0].seq, 2, "seq is never renumbered");
// Remove.
let out = execute(&store, &sid, &json!({"action":"remove","seq":2})).await;
assert!(out.contains("removed"), "{out}");
assert!(store.todos(&sid).unwrap().is_empty());
// Removing an absent id is a no-op.
let out = execute(&store, &sid, &json!({"action":"remove","seq":99})).await;
assert!(out.contains("No task 99"), "{out}");
}
#[tokio::test]
async fn seq_is_never_reused_after_remove() {
let (store, sid) = setup();
execute(&store, &sid, &json!({"action":"add","content":"a"})).await;
execute(&store, &sid, &json!({"action":"add","content":"b"})).await;
execute(&store, &sid, &json!({"action":"remove","seq":2})).await;
let out = execute(&store, &sid, &json!({"action":"add","content":"c"})).await;
assert!(out.contains("Task 3"), "{out}");
}
#[tokio::test]
async fn validation_and_open_cap() {
let (store, sid) = setup();
assert!(execute(&store, &sid, &json!({"action":"add"}))
.await
.contains("content"));
assert!(execute(&store, &sid, &json!({"action":"update","seq":1}))
.await
.contains("status"));
assert!(
execute(&store, &sid, &json!({"action":"update","status":"done"}))
.await
.contains("seq")
);
assert!(execute(
&store,
&sid,
&json!({"action":"update","seq":1,"status":"bogus"})
)
.await
.contains("unknown status"));
assert!(execute(&store, &sid, &json!({"action":"bogus"}))
.await
.contains("unknown"));
// Over-long item is refused (not truncated).
let long = "a".repeat(MAX_ITEM_CHARS + 1);
assert!(
execute(&store, &sid, &json!({"action":"add","content":long}))
.await
.contains("too long")
);
// Open cap: 30 pending items fit, the 31st is refused.
for i in 0..MAX_OPEN_ITEMS {
let out = execute(
&store,
&sid,
&json!({"action":"add","content":format!("task {i}")}),
)
.await;
assert!(out.contains("added"), "{out}");
}
let out = execute(
&store,
&sid,
&json!({"action":"add","content":"one too many"}),
)
.await;
assert!(out.contains("full"), "{out}");
// Finishing one frees a slot (done items do not count as open).
execute(
&store,
&sid,
&json!({"action":"update","seq":1,"status":"done"}),
)
.await;
let out = execute(&store, &sid, &json!({"action":"add","content":"fits now"})).await;
assert!(out.contains("added"), "{out}");
}
#[test]
fn declaration_shape() {
let d = todo_declaration();
assert_eq!(d["type"], "function");
assert_eq!(d["function"]["name"], "todo");
assert_eq!(d["function"]["parameters"]["required"][0], "action");
}
}
+1
View File
@@ -83,6 +83,7 @@ fn build_router(state: AppState, auth: AuthConfig) -> Router {
)
.route("/api/sessions/{id}/messages", get(sessions::get_messages))
.route("/api/sessions/{id}/notepad", get(sessions::get_notepad))
.route("/api/sessions/{id}/todos", get(sessions::get_todos))
.route("/api/sessions/{id}/chat", post(sessions::session_chat))
.route("/api/sessions/{id}/download", get(files::download))
.route(
+46 -9
View File
@@ -30,7 +30,7 @@ use crate::name;
use crate::render;
use crate::store::{
ContextSection, McpConnector, NewMessage, NotepadEntry, Session, SessionSettings, Stats, Store,
StoredMessage,
StoredMessage, TodoItem,
};
use crate::window;
use tokio_stream::wrappers::UnboundedReceiverStream;
@@ -277,6 +277,15 @@ pub(crate) async fn get_notepad(
Ok(Json(with_store(&st, move |s| s.notepad(&id)).await?))
}
/// `GET /api/sessions/{id}/todos` — the session's task list (read-only
/// observability; the agent writes it via the todo tool).
pub(crate) async fn get_todos(
State(st): State<AppState>,
Path(id): Path<String>,
) -> Result<Json<Vec<TodoItem>>, Error> {
Ok(Json(with_store(&st, move |s| s.todos(&id)).await?))
}
/// The stats dashboard payload: persistent history aggregates (from the store)
/// plus a live engine status and the since-startup performance gauge, in one
/// JSON object so the GUI renders the whole view from a single poll.
@@ -563,6 +572,19 @@ pub(crate) async fn session_chat(
Ok(v) => v,
Err(e) => return e.into_response(),
};
// The session's task queue: open items become the dynamic <TODO> pinned
// section (same seam as the MCP surface), so the prompt and the pre-warm
// share a byte-identical prefix.
let todos = match with_store(&st, {
let id = id.clone();
move |s| s.todos(&id)
})
.await
{
Ok(v) => v,
Err(e) => return e.into_response(),
};
all_sections.extend(context::todo_section(&todos));
// Sliding DIALOG window: retain the most recent messages by COUNT (main area
// + buffer headroom), with stepped eviction so the prefix stays byte-stable
// for KV-cache reuse. Full history stays in SQLite; the agent pins what
@@ -572,6 +594,8 @@ pub(crate) async fn session_chat(
// trigger compares it against the notepad at turn end to detect a header change
// (pre-warm-on-change, chosen over freezing the header).
let notepad_fp = context::notepad_fingerprint(&notepad);
// Same pre-warm-on-change discipline for the todo header.
let todo_fp = context::todo_fingerprint(&todos);
let sel = window::select(&history, window_start);
if sel.start_id != window_start {
let start_id = sel.start_id;
@@ -640,6 +664,7 @@ pub(crate) async fn session_chat(
let svc_pw = st.service.clone();
let store_pw = store.clone();
let notepad_fp_pw = notepad_fp.clone();
let todo_fp_pw = todo_fp.clone();
tokio::spawn(async move {
// Streaming model step: emit Delta events while generating (so the GUI
// shows thinking + final answer live), then return the accumulated
@@ -729,6 +754,7 @@ pub(crate) async fn session_chat(
sid.clone(),
true,
notepad_fp_pw,
todo_fp_pw,
memory_available,
);
});
@@ -794,6 +820,7 @@ pub(crate) async fn session_chat(
let svc_pw = st.service.clone();
let agent_pw = body.agent;
let notepad_fp_pw = notepad_fp.clone();
let todo_fp_pw = todo_fp.clone();
let tail = futures::stream::once(async move {
let a = acc_end.lock().unwrap().clone();
persist_assistant(&store, &sid, &a, prompt_len).await;
@@ -803,6 +830,7 @@ pub(crate) async fn session_chat(
sid.clone(),
agent_pw,
notepad_fp_pw,
todo_fp_pw,
memory_available,
);
Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]"))
@@ -841,6 +869,7 @@ pub(crate) async fn session_chat(
id.clone(),
body.agent,
notepad_fp.clone(),
todo_fp.clone(),
memory_available,
);
Json(resp).into_response()
@@ -891,17 +920,19 @@ async fn persist_assistant(store: &Arc<dyn Store>, sid: &str, a: &Accum, prompt_
/// next prefix will differ from what the engine just cached. Best-effort: skipped
/// when the engine is busy, and it never STOPs a running pre-warm (a real turn
/// queues on the engine mutex behind it). Not a user turn: no persistence, no
/// PerfMeter. Triggers on a pending rotation OR a notepad header change during the
/// turn (pre-warm-on-change: the model always sees a fresh notepad, no frozen
/// header, no schema migration). Within an agent tool loop the header is composed
/// once and `req.messages` is append-only, so mid-loop notepad writes never
/// invalidate intermediate steps — this fires once, at turn end, in the idle gap.
/// PerfMeter. Triggers on a pending rotation OR a notepad/todo header change
/// during the turn (pre-warm-on-change: the model always sees fresh headers, no
/// frozen header, no schema migration). Within an agent tool loop the header is
/// composed once and `req.messages` is append-only, so mid-loop notepad/todo
/// writes never invalidate intermediate steps — this fires once, at turn end,
/// in the idle gap.
fn schedule_prewarm(
service: ChatService,
store: Arc<dyn Store>,
sid: String,
agent_mode: bool,
notepad_fp: String,
todo_fp: String,
memory_available: bool,
) {
tokio::spawn(async move {
@@ -918,6 +949,7 @@ fn schedule_prewarm(
let history = store.message_window(&sid_load, ws).ok()?.0;
let sections = store.context_sections().ok()?;
let notepad = store.notepad(&sid_load).ok()?;
let todos = store.todos(&sid_load).ok()?;
let connectors = store.mcp_connectors().ok()?;
let user_name = store
.get_defaults()
@@ -926,12 +958,15 @@ fn schedule_prewarm(
.map(|n| n.trim().to_string())
.filter(|n| !n.is_empty())
.unwrap_or_else(|| "User".to_string());
Some((sess, ws, history, sections, notepad, user_name, connectors))
Some((
sess, ws, history, sections, notepad, todos, user_name, connectors,
))
})
.await
.ok()
.flatten();
let Some((sess, ws, history, sections, notepad, user_name, connectors)) = loaded else {
let Some((sess, ws, history, sections, notepad, todos, user_name, connectors)) = loaded
else {
return;
};
let sel = window::select(&history, ws);
@@ -950,7 +985,8 @@ fn schedule_prewarm(
};
let rotation_pending = sel.start_id != cur_start;
let notepad_dirty = context::notepad_fingerprint(&notepad) != notepad_fp;
if !rotation_pending && !notepad_dirty {
let todo_dirty = context::todo_fingerprint(&todos) != todo_fp;
if !rotation_pending && !notepad_dirty && !todo_dirty {
return;
}
// Rebuild the SAME curated MCP surface the real turn uses (persisted
@@ -958,6 +994,7 @@ fn schedule_prewarm(
let (mcp_decls, mcp_sections) = mcp_surface(&connectors, &sess.settings.mcp_enabled);
let mut all_sections = sections.clone();
all_sections.extend(mcp_sections);
all_sections.extend(context::todo_section(&todos));
let prefix = context::compose_prefix(
&sess,
&history[sel.start..],
+68 -1
View File
@@ -9,7 +9,7 @@
use crate::api::types::{now_unix, ChatMessage, Role};
use crate::i18n::t;
use crate::store::{ContextSection, NotepadEntry, Session, StoredMessage};
use crate::store::{ContextSection, NotepadEntry, Session, StoredMessage, TodoItem};
/// Compose the full context message list: static sections, then the DIALOG region.
/// `user_content` is the new turn's typed text plus attachment context.
@@ -194,6 +194,36 @@ pub fn notepad_fingerprint(notepad: &[NotepadEntry]) -> String {
.join("\n")
}
/// The rendered `<TODO>` body: one `seq [status] content` line per OPEN item
/// (pending/doing), in store order (seq). Done items stay in the Store for
/// history/GUI but never enter the prompt. Like the notepad fingerprint this is
/// exactly the injected header body, so it doubles as the pre-warm-on-change
/// trigger; `updated_at` is excluded (an identical re-set is not a change).
pub fn todo_fingerprint(todos: &[TodoItem]) -> String {
todos
.iter()
.filter(|i| i.status != "done")
.map(|i| format!("{} [{}] {}", i.seq, i.status, i.content.replace('\n', " ")))
.collect::<Vec<_>>()
.join("\n")
}
/// The dynamic `<TODO>` pinned section, built from the session's open tasks
/// (None when there are none). Appended to the static sections like the MCP
/// surface, so the real turn and the cache pre-warm share a byte-identical
/// prefix with no extra compositor parameter.
pub fn todo_section(todos: &[TodoItem]) -> Option<ContextSection> {
let body = todo_fingerprint(todos);
if body.is_empty() {
return None;
}
Some(ContextSection {
name: "TODO".into(),
content: body,
position: 3,
})
}
fn role_of(s: &str) -> Role {
match s {
"system" | "developer" => Role::System,
@@ -631,4 +661,41 @@ mod tests {
assert_eq!(notepad_fingerprint(&d), "state: coding now");
assert_eq!(notepad_fingerprint(&[]), "");
}
#[test]
fn todo_section_renders_open_items_only_and_fingerprint_ignores_done() {
let item = |seq: i64, status: &str, content: &str, updated_at: i64| TodoItem {
seq,
content: content.into(),
status: status.into(),
created_at: 0,
updated_at,
};
let todos = vec![
item(1, "doing", "wire the tool", 1),
item(2, "done", "design the schema", 5),
item(3, "pending", "write\ntests", 1),
];
let sec = todo_section(&todos).unwrap();
assert_eq!(sec.name, "TODO");
assert_eq!(
sec.content,
"1 [doing] wire the tool\n3 [pending] write tests"
);
// updated_at does not affect the rendered body (no wasted pre-warm).
let bumped = vec![
item(1, "doing", "wire the tool", 999),
item(3, "pending", "write\ntests", 999),
];
assert_eq!(todo_fingerprint(&todos), todo_fingerprint(&bumped));
// A status change IS a change.
let moved = vec![
item(1, "done", "wire the tool", 1),
item(3, "pending", "write\ntests", 1),
];
assert_ne!(todo_fingerprint(&todos), todo_fingerprint(&moved));
// All done (or empty) -> no section at all.
assert!(todo_section(&[item(2, "done", "x", 0)]).is_none());
assert!(todo_section(&[]).is_none());
}
}
+199 -2
View File
@@ -219,6 +219,20 @@ pub struct NotepadEntry {
pub updated_at: i64,
}
/// One task of a session's persistent todo list: the operational work queue
/// (pending / doing / done), addressed by a stable per-session `seq` that is
/// never reused or renumbered. Open items are injected as the pinned <TODO>
/// section above DIALOG; done items stay in history until pruned. Distinct from
/// the notepad: the notepad curates durable knowledge, the todo tracks work.
#[derive(Debug, Clone, Serialize)]
pub struct TodoItem {
pub seq: i64,
pub content: String,
pub status: String,
pub created_at: i64,
pub updated_at: i64,
}
/// One external MCP server in the GLOBAL connector catalog (shared across
/// sessions). Connection parameters, including the Bearer `token`, live in the
/// database like all other persistent state (no env vars / files: that would
@@ -254,6 +268,10 @@ const TOOL_USE_SECTION_PRE_SHARE: &str = "Strumenti: shell_exec(command, cwd?, t
/// Kept separate so the seed can refresh untouched older rows without duplicating
/// the long notepad text (and never clobber a user-edited section).
const SHARE_FILE_SUFFIX: &str = " share_file(path, name?) espone un file che hai su disco come link di scaricamento cliccabile nella chat web: restituisce un link Markdown già pronto da incollare testualmente nella risposta per l'utente. Usalo quando produci un file che l'utente deve scaricare (report, script, dati, immagini, archivi). Sono ammessi solo file regolari dentro la tua cartella personale o la cartella uploads condivisa, entro 64 MiB; `path` può essere assoluto o relativo alla tua cartella personale, `name` opzionalmente sostituisce il nome del file scaricato.";
/// Prose appended to the share_file-era TOOL_USE manual to document `todo`.
/// Same refresh discipline: untouched older rows are upgraded, user-edited rows
/// are never clobbered.
const TODO_SUFFIX: &str = " todo(action, ...) gestisce la tua lista di task persistente, sempre visibile sopra il dialogo: action=add(content) aggiunge un task (stato pending); action=update(seq, status?, content?) aggiorna lo stato (pending|doing|done) o il testo del task `seq`; action=remove(seq) elimina un task; action=clear_done rimuove i task completati. Usalo per il lavoro operativo multi-step: pianifica i passi, marca doing ciò su cui stai lavorando e done appena completato — è il tuo punto di ripresa dopo un riavvio o un risveglio. Il notepad resta per le conoscenze durature (goal, decisioni, vincoli), il todo per la coda di lavoro. Gli id `seq` sono stabili e non vengono mai rinumerati; nel contesto vedi solo i task aperti, al massimo 30: completa o rimuovi quelli vecchi.";
/// The storage interface. Synchronous; call via `spawn_blocking` from async code.
pub trait Store: Send + Sync {
@@ -294,6 +312,23 @@ pub trait Store: Send + Sync {
fn remove_notepad_entry(&self, session_id: &str, key: &str) -> Result<bool>;
/// Empty the session's notepad.
fn clear_notepad(&self, session_id: &str) -> Result<()>;
/// The session's todo items, ordered by seq (stable addressing).
fn todos(&self, session_id: &str) -> Result<Vec<TodoItem>>;
/// Append a new pending task; its seq comes from a per-session high-water
/// mark (never reused, even after a remove).
fn add_todo(&self, session_id: &str, content: &str) -> Result<TodoItem>;
/// Update status and/or content of task `seq`; returns whether it existed.
fn update_todo(
&self,
session_id: &str,
seq: i64,
status: Option<&str>,
content: Option<&str>,
) -> Result<bool>;
/// Remove task `seq`; returns whether it existed.
fn remove_todo(&self, session_id: &str, seq: i64) -> Result<bool>;
/// Prune all completed (done) tasks; returns how many were removed.
fn clear_done_todos(&self, session_id: &str) -> Result<usize>;
fn save_upload(&self, meta: &UploadMeta) -> Result<()>;
fn get_upload(&self, id: &str) -> Result<Option<UploadMeta>>;
/// The global MCP connector catalog, ordered by name.
@@ -385,6 +420,19 @@ CREATE TABLE IF NOT EXISTS notepad_entries (
updated_at INTEGER NOT NULL,
PRIMARY KEY (session_id, key)
);
CREATE TABLE IF NOT EXISTS todo_items (
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
seq INTEGER NOT NULL,
content TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (session_id, seq)
);
CREATE TABLE IF NOT EXISTS todo_counters (
session_id TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
next_seq INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS mcp_connectors (
name TEXT PRIMARY KEY,
url TEXT NOT NULL,
@@ -505,8 +553,9 @@ fn migrate(conn: &Connection) -> Result<()> {
/// Seed the static context sections once (idempotent); afterwards the stored
/// rows are authoritative and editable.
fn seed_context_sections(conn: &Connection) -> Result<()> {
// The current TOOL_USE manual = notepad-era prose + the share_file paragraph.
let tool_use = format!("{TOOL_USE_SECTION_PRE_SHARE}{SHARE_FILE_SUFFIX}");
// The current TOOL_USE manual = notepad-era prose + share_file + todo.
let tool_use_pre_todo = format!("{TOOL_USE_SECTION_PRE_SHARE}{SHARE_FILE_SUFFIX}");
let tool_use = format!("{tool_use_pre_todo}{TODO_SUFFIX}");
conn.execute(
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('SYSTEM_PROMPT', ?1, 0)",
params![SYSTEM_PROMPT_SECTION],
@@ -527,6 +576,12 @@ fn seed_context_sections(conn: &Connection) -> Result<()> {
"UPDATE context_sections SET content = ?1 WHERE name = 'TOOL_USE' AND content = ?2",
params![tool_use, TOOL_USE_SECTION_PRE_SHARE],
)?;
// And refresh an untouched share_file-era row so the todo manual reaches
// databases created before todo existed.
conn.execute(
"UPDATE context_sections SET content = ?1 WHERE name = 'TOOL_USE' AND content = ?2",
params![tool_use, tool_use_pre_todo],
)?;
Ok(())
}
@@ -920,6 +975,106 @@ impl Store for SqliteStore {
Ok(())
}
fn todos(&self, session_id: &str) -> Result<Vec<TodoItem>> {
let conn = self.lock();
let mut stmt = conn.prepare(
"SELECT seq, content, status, created_at, updated_at FROM todo_items
WHERE session_id = ?1 ORDER BY seq ASC",
)?;
let rows = stmt.query_map(params![session_id], |r| {
Ok(TodoItem {
seq: r.get(0)?,
content: r.get(1)?,
status: r.get(2)?,
created_at: r.get(3)?,
updated_at: r.get(4)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
fn add_todo(&self, session_id: &str, content: &str) -> Result<TodoItem> {
let conn = self.lock();
let now = now_secs();
// Per-session high-water mark: a seq is NEVER reused, even after the
// highest item is removed (a stale reference must not hit a new task).
let seq: i64 = conn
.query_row(
"SELECT next_seq FROM todo_counters WHERE session_id = ?1",
params![session_id],
|r| r.get(0),
)
.optional()?
.unwrap_or(1);
conn.execute(
"INSERT INTO todo_counters (session_id, next_seq) VALUES (?1, ?2)
ON CONFLICT(session_id) DO UPDATE SET next_seq = ?2",
params![session_id, seq + 1],
)?;
conn.execute(
"INSERT INTO todo_items (session_id, seq, content, status, created_at, updated_at)
VALUES (?1, ?2, ?3, 'pending', ?4, ?4)",
params![session_id, seq, content, now],
)?;
Ok(TodoItem {
seq,
content: content.to_string(),
status: "pending".into(),
created_at: now,
updated_at: now,
})
}
fn update_todo(
&self,
session_id: &str,
seq: i64,
status: Option<&str>,
content: Option<&str>,
) -> Result<bool> {
let conn = self.lock();
let existing: Option<(String, String)> = conn
.query_row(
"SELECT content, status FROM todo_items WHERE session_id = ?1 AND seq = ?2",
params![session_id, seq],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
let Some((cur_content, cur_status)) = existing else {
return Ok(false);
};
conn.execute(
"UPDATE todo_items SET content = ?3, status = ?4, updated_at = ?5
WHERE session_id = ?1 AND seq = ?2",
params![
session_id,
seq,
content.unwrap_or(&cur_content),
status.unwrap_or(&cur_status),
now_secs()
],
)?;
Ok(true)
}
fn remove_todo(&self, session_id: &str, seq: i64) -> Result<bool> {
let conn = self.lock();
let n = conn.execute(
"DELETE FROM todo_items WHERE session_id = ?1 AND seq = ?2",
params![session_id, seq],
)?;
Ok(n > 0)
}
fn clear_done_todos(&self, session_id: &str) -> Result<usize> {
let conn = self.lock();
let n = conn.execute(
"DELETE FROM todo_items WHERE session_id = ?1 AND status = 'done'",
params![session_id],
)?;
Ok(n)
}
fn save_upload(&self, meta: &UploadMeta) -> Result<()> {
let conn = self.lock();
conn.execute(
@@ -1542,6 +1697,48 @@ mod tests {
let secs = s.context_sections().unwrap();
let tool_use = secs.iter().find(|x| x.name == "TOOL_USE").unwrap();
assert!(tool_use.content.contains("notepad("));
assert!(tool_use.content.contains("todo("));
}
#[test]
fn todo_add_update_remove_clear_done_and_cascade() {
let s = store();
let sess = s
.create_session("Chat", "m", &SessionSettings::default())
.unwrap();
assert!(s.todos(&sess.id).unwrap().is_empty());
let a = s.add_todo(&sess.id, "step one").unwrap();
let b = s.add_todo(&sess.id, "step two").unwrap();
assert_eq!(a.seq, 1);
assert_eq!(b.seq, 2);
assert_eq!(a.status, "pending");
// Update status only keeps content; update content only keeps status.
assert!(s.update_todo(&sess.id, 1, Some("doing"), None).unwrap());
assert!(s
.update_todo(&sess.id, 1, None, Some("step one (revised)"))
.unwrap());
let items = s.todos(&sess.id).unwrap();
assert_eq!(items[0].content, "step one (revised)");
assert_eq!(items[0].status, "doing");
// Absent id -> false, no panic.
assert!(!s.update_todo(&sess.id, 99, Some("done"), None).unwrap());
assert!(!s.remove_todo(&sess.id, 99).unwrap());
// clear_done prunes only completed items.
s.update_todo(&sess.id, 1, Some("done"), None).unwrap();
assert_eq!(s.clear_done_todos(&sess.id).unwrap(), 1);
let items = s.todos(&sess.id).unwrap();
assert_eq!(items.len(), 1);
assert_eq!(items[0].seq, 2);
// seq is never reused after a remove.
assert!(s.remove_todo(&sess.id, 2).unwrap());
assert_eq!(s.add_todo(&sess.id, "step three").unwrap().seq, 3);
// Per-session isolation + cascade on delete.
let other = s
.create_session("Other", "m", &SessionSettings::default())
.unwrap();
assert!(s.todos(&other.id).unwrap().is_empty());
s.delete_session(&sess.id).unwrap();
assert!(s.todos(&sess.id).unwrap().is_empty());
}
#[test]