Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

Merge upstream/main into todo-goals-e2e

Steven Enamakel19dbbf670d76
diff --cc crates/openhuman-core/src/agent/todos/ops.rs
index 148dac1002,229865d335..a220e00fa4
--- a/crates/openhuman-core/src/agent/todos/ops.rs
+++ b/crates/openhuman-core/src/agent/todos/ops.rs
@@@ -1,26 -1,19 +1,19 @@@
- //! OpenHuman host adapter over [`tinyagents_graph::todos`].
-//! OpenHuman host adapter over TinyAgents' `todos::session_list`.
++//! OpenHuman host adapter over TinyAgents' `todos`.
//!
//! A todo list is scoped to one agent session ([`TodoScope::Session`]) or,
//! when a tool runs with no session at all, to a scratch list
- //! ([`TodoScope::Scratch`]). Both live in the one in-process store; the
- //! normalisation and rendering are TinyAgents'. The whole-list `replace` is
- //! the only write the `todo` tool needs; `clear` is for tests and cleanup.
+ //! ([`TodoScope::Scratch`]). Both live in the one in-process [`store`];
+ //! validation, the whole-list write and rendering are TinyAgents'. This file
+ //! only maps a scope onto a store key. `clear` is for tests and cleanup.
+
+ use std::sync::Arc;
- use serde::{Deserialize, Serialize};
-use tinyagents_graph::todos::session_list;
+use tinyagents_graph::todos::store as todos;
+ use tinyagents_harness::store::Store;
use crate::agent::tinyagents::todos::{session_todos_store, SCRATCH_SESSION_ID};
-pub use crate::agent::todos::types::{TaskBoardCard, TaskCardStatus};
+pub use crate::agent::todos::types::{TodoItem, TodoStatus};
-
- pub use tinyagents_graph::todos::{parse_status, render_markdown};
-
- #[derive(Debug, Clone, Serialize, Deserialize)]
- #[serde(rename_all = "camelCase")]
- pub struct TodosSnapshot {
- pub session_id: Option<String>,
- pub items: Vec<TodoItem>,
- pub markdown: String,
- }
+ pub use tinyagents_graph::todos::TodosSnapshot;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TodoScope {
@@@ -41,36 -35,28 +35,27 @@@ impl TodoScope
}
}
- fn snapshot(scope: &TodoScope, value: tinyagents_graph::todos::TodosSnapshot) -> TodosSnapshot {
- TodosSnapshot {
- session_id: scope.session_id().map(str::to_owned),
- items: value.items,
- markdown: value.markdown,
- }
- }
-
- fn finish(
- scope: &TodoScope,
- result: tinyagents_harness::error::Result<tinyagents_graph::todos::TodosSnapshot>,
- ) -> Result<TodosSnapshot, String> {
- result
- .map(|value| snapshot(scope, value))
- .map_err(|error| error.to_string())
+ /// The process-wide store every session's list lives in.
+ pub fn store() -> Arc<dyn Store> {
+ session_todos_store()
}
-pub async fn replace(
- scope: &TodoScope,
- cards: Vec<TaskBoardCard>,
-) -> Result<TodosSnapshot, String> {
- session_list::write(&store(), scope.key(), cards)
+pub async fn replace(scope: &TodoScope, items: Vec<TodoItem>) -> Result<TodosSnapshot, String> {
- let store = session_todos_store();
- finish(scope, todos::replace(&store, scope.key(), items).await)
++ todos::replace(&store(), scope.key(), items)
+ .await
+ .map_err(|error| error.to_string())
}
pub async fn clear(scope: &TodoScope) -> Result<TodosSnapshot, String> {
- let store = session_todos_store();
- finish(scope, todos::clear(&store, scope.key()).await)
- replace(scope, Vec::new()).await
++ todos::clear(&store(), scope.key())
++ .await
++ .map_err(|error| error.to_string())
}
pub async fn list(scope: &TodoScope) -> Result<TodosSnapshot, String> {
- let store = session_todos_store();
- finish(scope, todos::list(&store, scope.key()).await)
- session_list::read(&store(), scope.key())
++ todos::list(&store(), scope.key())
+ .await
+ .map_err(|error| error.to_string())
}
#[cfg(test)]
diff --cc crates/openhuman-core/src/agent/todos/types.rs
index 28eba6af56,5a68fee050..766bfa46b9
--- a/crates/openhuman-core/src/agent/todos/types.rs
+++ b/crates/openhuman-core/src/agent/todos/types.rs
@@@ -1,3 -1,3 +1,3 @@@
- //! TinyAgents todo types, re-exported at the OpenHuman transcript boundary.
+ //! TinyAgents todo types, re-exported for OpenHuman callers.
- pub use tinyagents_graph::todos::{TodoItem, TodoList, TodoStatus};
-pub use tinyagents_graph::todos::{TaskBoardCard, TaskCardStatus};
++pub use tinyagents_graph::todos::{TodoItem, TodoStatus};
diff --cc crates/openhuman-core/src/agent/tools/todo.rs
index a2c9c80b38,b1fa6bb0ef..4d7f2d94a5
--- a/crates/openhuman-core/src/agent/tools/todo.rs
+++ b/crates/openhuman-core/src/agent/tools/todo.rs
@@@ -1,24 -1,25 +1,25 @@@
//! `todo` — the session's todo list, the way Claude Code and Codex have it.
//!
- //! One call writes the whole list: `{"todos": [{"content", "status"}]}`.
- //! There is no per-item CRUD; the list is a progress checklist the model
- //! rewrites as it works. It is scoped to the agent session the turn runs in
- //! (in memory, for the life of the process) via [`crate::agent::todos::ops`];
- //! without a session (a bare `execute` in a test) it falls back to a scratch
- //! list. Calling with no `todos` returns the current list.
-//! The tool itself is TinyAgents' `todos::session_list` (schema, argument
++//! The tool itself is TinyAgents' `todos::TodoTool` (schema, argument
+ //! validation, the whole-list write, markdown). This file is only the host
+ //! adapter: it decides **which** list a call is about — the agent session the
+ //! turn runs in, in memory for the life of the process — and registers the
+ //! harness dispatch. Nothing here may turn a bad argument into an `Err`: a
+ //! dispatch `Err` is fatal to the run, and a turn died that way when a model
-//! sent the retired `{"cards": …}` shape to the previous host-side copy.
++//! sent the retired `{"cards": …}` shape to a previous host-side copy.
use crate::agent::harness::fork_context::ParentExecutionContext;
use crate::agent::todos::ops::{self, TodoScope};
- use crate::agent::todos::types::{TodoItem, TodoStatus};
use async_trait::async_trait;
- use serde::Deserialize;
- use serde_json::json;
use std::sync::Arc;
-use tinyagents_graph::todos::session_list;
++use tinyagents_graph::todos as graph_todos;
use tinyagents_harness::context::RunContext;
use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};
use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};
- pub struct TodoTool;
+ pub struct TodoTool {
- inner: session_list::SessionTodoTool,
++ inner: graph_todos::TodoTool,
+ }
pub(crate) struct TodoToolDispatch {
tool: Arc<dyn Tool>,
@@@ -50,7 -58,9 +58,9 @@@ impl ToolDispatch<(), crate::agent::tin
impl TodoTool {
pub fn new() -> Self {
- Self
+ Self {
- inner: session_list::SessionTodoTool::new(ops::store()),
++ inner: graph_todos::TodoTool::new(ops::store()),
+ }
}
}
@@@ -60,16 -70,6 +70,19 @@@ impl Default for TodoTool
}
}
- /// One item as the model writes it. `status` accepts the Claude-style
- /// `pending` / `in_progress` / `completed` plus the older `todo` / `done`
- /// spellings the store already parses.
- #[derive(Deserialize)]
- struct TodoArg {
- content: String,
- #[serde(default)]
- status: Option<String>,
++/// The scope's store key, handed to the crate tool the only way it accepts
++/// one: as the `thread_id` of a tool context. The crate keys a list by the
++/// caller's thread; OpenHuman keys it by the agent session the turn runs in
++/// (see [`current_scope`]), so the host substitutes its own key here rather
++/// than letting the crate read a thread id that would address the wrong list.
++struct ScopedKey<'a>(&'a str);
++
++impl ToolRunContext for ScopedKey<'_> {
++ fn thread_id(&self) -> Option<&str> {
++ Some(self.0)
++ }
+}
+
#[async_trait]
impl Tool for TodoTool {
fn name(&self) -> &str {
@@@ -135,39 -113,7 +126,10 @@@ impl TodoTool
) -> anyhow::Result<ToolResult> {
let scope = current_scope(parent.as_ref(), tool_context);
tracing::debug!(session_id = ?scope.session_id(), "[tool][todo] dispatch");
-
- let result = match args.get("todos") {
- None | Some(serde_json::Value::Null) => ops::list(&scope).await,
- Some(raw) => {
- let items: Vec<TodoArg> = serde_json::from_value(raw.clone())
- .map_err(|e| anyhow::anyhow!("invalid `todos`: {e}"))?;
- let mut todos = Vec::with_capacity(items.len());
- for item in items {
- let content = item.content.trim();
- if content.is_empty() {
- anyhow::bail!("every todo needs non-empty `content`");
- }
- let status = match item.status.as_deref() {
- None => TodoStatus::Pending,
- Some(raw) => ops::parse_status(raw).map_err(anyhow::Error::msg)?,
- };
- todos.push(TodoItem::with_status(content, status));
- }
- ops::replace(&scope, todos).await
- }
- };
-
- match result {
- Ok(snap) => {
- let payload = json!({
- "sessionId": snap.session_id,
- "todos": snap.items,
- "markdown": snap.markdown,
- });
- Ok(ToolResult::success(payload.to_string()))
- }
- Err(err) => Ok(ToolResult::error(err)),
- }
- Ok(session_list::call(&ops::store(), scope.key(), &args).await?)
++ let key = ScopedKey(scope.key());
++ self.inner
++ .execute_with_context(args, ToolCallOptions::default(), Some(&key))
++ .await
}
}
diff --cc crates/openhuman-core/src/agent/tools/todo_tests.rs
index e1c0910a29,a23249e654..fe63054e45
--- a/crates/openhuman-core/src/agent/tools/todo_tests.rs
+++ b/crates/openhuman-core/src/agent/tools/todo_tests.rs
@@@ -1,5 -1,6 +1,6 @@@
use super::*;
- use serde_json::Value;
-use crate::agent::todos::ops::{TaskBoardCard, TaskCardStatus};
++use crate::agent::todos::ops::{TodoItem, TodoStatus};
+ use serde_json::{json, Value};
/// Serialize tests that share the process-global scratch store. Same lock
/// as `todos::ops` — otherwise the two test modules race under `cargo test`'s
@@@ -77,22 -78,40 +78,46 @@@ async fn two_in_progress_items_are_reje
reset_scratch().await;
}
+ /// Bad input is a tool error the model can correct, never an `Err`: a
+ /// dispatch `Err` is fatal to the whole run in the harness, and a turn died
+ /// exactly that way when a model sent the retired `{"cards": …}` shape.
#[tokio::test]
- async fn empty_content_and_unknown_status_are_errors() {
+ async fn bad_input_is_a_tool_error_not_a_harness_error() {
let tool = TodoTool::new();
- let err = tool
- .execute(json!({ "todos": [{ "content": " ", "status": "pending" }] }))
- .await
- .unwrap_err();
- assert!(err.to_string().contains("content"), "{err}");
-
- let err = tool
- .execute(json!({ "todos": [{ "content": "x", "status": "someday" }] }))
- .await
- .unwrap_err();
- assert!(err.to_string().contains("invalid status"), "{err}");
+ for (args, expect) in [
+ (
+ json!({ "todos": [{ "content": " ", "status": "pending" }] }),
+ "content",
+ ),
+ (
++ // The exact phrasing belongs to TinyAgents; assert only that the
++ // rejection names the field the model got wrong.
+ json!({ "todos": [{ "content": "x", "status": "someday" }] }),
- "status must be",
++ "status",
+ ),
+ (json!({ "todos": "not a list" }), "invalid `todos`"),
+ (
+ json!({ "cards": [{ "content": "x", "status": "todo" }] }),
+ "pass `todos`",
+ ),
+ ] {
+ let result = tool
+ .execute(args.clone())
+ .await
+ .expect("never an Err: {args}");
+ assert!(result.is_error, "{args}");
+ assert!(
+ result.output().contains(expect),
+ "{args}: {}",
+ result.output()
+ );
+ }
}
++/// The schema is TinyAgents' (`todos::TodoTool`); this pins the parts the
++/// product depends on: one `todos` argument and no per-card `op`, and a
++/// `status` enum whose distinct states are exactly the Claude three — the
++/// other spellings it lists are aliases of those three, not extra states.
#[test]
fn schema_is_the_claude_shape() {
let tool = TodoTool::new();
@@@ -104,10 -123,10 +129,22 @@@
1,
"no per-card ops: {props}"
);
-- assert_eq!(
-- props["todos"]["items"]["properties"]["status"]["enum"],
-- json!(["pending", "in_progress", "completed"])
-- );
++ assert!(props.get("op").is_none(), "no op multiplexer: {props}");
++ let statuses: Vec<&str> = props["todos"]["items"]["properties"]["status"]["enum"]
++ .as_array()
++ .expect("status enum")
++ .iter()
++ .map(|value| value.as_str().expect("status spelling"))
++ .collect();
++ for required in ["pending", "in_progress", "completed"] {
++ assert!(statuses.contains(&required), "missing {required}: {statuses:?}");
++ }
++ for retired in ["blocked", "ready", "awaiting_approval", "rejected"] {
++ assert!(
++ !statuses.contains(&retired),
++ "board state {retired} is not a todo status: {statuses:?}"
++ );
++ }
let desc = tool.description();
assert!(desc.contains("3+ steps"), "missing when-to-use guidance");
assert!(
diff --cc tests/agent_harness_e2e.rs
index eafae2fd66,e4df817362..39890a931c
--- a/tests/agent_harness_e2e.rs
+++ b/tests/agent_harness_e2e.rs
@@@ -4365,539 -4365,3 +4365,541 @@@ mod tool_policy_boundary_placement
);
}
}
+
+// ─── Harness work state: the session todo list and the thread goal ──────────
+//
+// Two harness-level primitives the orchestrator drives with its own tools and
+// the chat pane renders read-only above the composer:
+//
+// - `todo` — the session checklist. One call writes the whole list
+// (`{"todos": [{content, status}]}`), Claude Code / Codex style. Scoped to
+// the thread's orchestrator session, alive for the process.
+// - `goal_set` / `goal_get` / `goal_complete` — the thread's durable
+// objective, persisted in the crate `graph.goals` store.
+//
+// Both answer with a JSON payload. The frontend reads the newest one off the
+// tool timeline (`app/src/features/conversations/utils/harnessState.ts`), so
+// these tests pin the two contracts the UI depends on: the payload shape on
+// the live `tool_result` socket event, and the same payload persisted in the
+// turn-state snapshot a reloaded thread rehydrates from.
+
+/// Every `tool_result` frame the turn emitted, in order, plus the terminal
+/// event. Collected on one connection so no frame is lost between waits.
+async fn collect_turn_tool_results(
+ rx: &mut tokio::sync::mpsc::UnboundedReceiver<Value>,
+ timeout: Duration,
+) -> (Value, Vec<Value>) {
+ let deadline = tokio::time::Instant::now() + timeout;
+ let mut results = Vec::new();
+ loop {
+ let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
+ match tokio::time::timeout(remaining, rx.recv()).await {
+ Ok(Some(v)) => match v.get("event").and_then(Value::as_str) {
+ Some("tool_result") => results.push(v),
+ Some("chat_done") | Some("chat_error") => return (v, results),
+ _ => {}
+ },
+ Ok(None) => panic!("SSE channel closed waiting for terminal event"),
+ Err(_) => panic!(
+ "timed out waiting for terminal web-chat event; tool results so far: {results:?}"
+ ),
+ }
+ }
+}
+
+/// The JSON payload a named tool answered with on the live socket.
+///
+/// Found by `tool_call_id` (`call_<name>`, stamped by [`tool_call_completion`])
+/// rather than by `tool_name`: `goal_set` / `goal_get` live in the `goals`
+/// tool pack, so the model reaches them through `use_skill` and the frame is
+/// named for the wrapper.
+fn tool_result_payload(results: &[Value], tool_name: &str) -> Value {
+ let call_id = format!("call_{tool_name}");
+ let frame = results
+ .iter()
+ .find(|frame| frame.get("tool_call_id").and_then(Value::as_str) == Some(call_id.as_str()))
+ .unwrap_or_else(|| panic!("no tool_result frame for `{tool_name}` in {results:?}"));
+ assert_eq!(
+ frame.get("success"),
+ Some(&json!(true)),
+ "`{tool_name}` should succeed: {frame}"
+ );
+ let output = frame
+ .get("output")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| panic!("`{tool_name}` result carries no output: {frame}"));
+ serde_json::from_str(output)
+ .unwrap_or_else(|e| panic!("`{tool_name}` output is not JSON ({e}): {output}"))
+}
+
+/// The statuses of a `todo` payload's items, in list order.
+fn todo_statuses(payload: &Value) -> Vec<String> {
+ payload["todos"]
+ .as_array()
+ .unwrap_or_else(|| panic!("todo payload has no `todos` array: {payload}"))
+ .iter()
+ .map(|item| item["status"].as_str().unwrap_or("").to_string())
+ .collect()
+}
+
+/// A `todo` write: `steps` in order, the first `completed` of them done, the
+/// next one in progress, the rest pending — the shape an agent writes as it
+/// works down a list one item at a time.
+fn todo_write(steps: &[&str], completed: usize) -> Value {
+ let todos: Vec<Value> = steps
+ .iter()
+ .enumerate()
+ .map(|(i, content)| {
+ let status = if i < completed {
+ "completed"
+ } else if i == completed {
+ "in_progress"
+ } else {
+ "pending"
+ };
+ json!({ "content": content, "status": status })
+ })
+ .collect();
+ tool_call_completion("todo", json!({ "todos": todos }))
+}
+
+/// The persisted turn-state snapshots for a thread, newest first, through
+/// the RPC the reloaded pane uses.
+async fn turn_state_history(rpc_base: &str, id: i64, thread_id: &str) -> Vec<Value> {
+ let resp = post_json_rpc(
+ rpc_base,
+ id,
+ "openhuman.threads_turn_state_history",
+ json!({ "thread_id": thread_id }),
+ )
+ .await;
+ assert_no_jsonrpc_error(&resp, "threads_turn_state_history")
+ .get("data")
+ .and_then(|d| d.get("turnStates"))
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_else(|| panic!("turn_state_history has no turnStates: {resp}"))
+}
+
+/// Persisted tool rows whose id is `call_<tool_name>`, oldest first, across
+/// every turn of the thread — what a cold-booted pane rehydrates its timeline
+/// from. Keyed on the call id for the same reason as [`tool_result_payload`]:
+/// a packed tool's row is named for the `use_skill` wrapper.
+fn persisted_tool_rows(turns: &[Value], tool_name: &str) -> Vec<Value> {
+ let call_id = format!("call_{tool_name}");
+ turns
+ .iter()
+ .rev()
+ .flat_map(|turn| {
+ turn["toolTimeline"]
+ .as_array()
+ .cloned()
+ .unwrap_or_default()
+ .into_iter()
+ .filter(|row| row["id"].as_str() == Some(call_id.as_str()))
+ })
+ .collect()
+}
+
+const FIVE_STEPS: [&str; 5] = [
+ "Read the request",
+ "Draft the outline",
+ "Write the sections",
+ "Review for accuracy",
+ "Send the summary",
+];
+
+/// A five-item todo list worked one item per turn: the agent writes all five
+/// up front, then rewrites the list each turn moving one more item to
+/// `completed`. Every write reaches the pane on the live socket and survives
+/// in the persisted turn state; the last write is all five completed.
+#[test]
+fn todo_list_ticks_off_five_items_across_turns() {
+ run_on_agent_stack(
+ "todo_list_ticks_off_five_items_across_turns",
+ todo_list_ticks_off_five_items_across_turns_inner,
+ );
+}
+
+async fn todo_list_ticks_off_five_items_across_turns_inner() {
+ let _lock = env_lock();
+ // Turn 1 writes the plan (item 1 in progress). Turns 2-6 each complete
+ // one more item; the final write has every item completed.
+ let mut script = vec![
+ todo_write(&FIVE_STEPS, 0),
+ text_completion("Plan written; starting on the first step."),
+ ];
+ for completed in 1..=FIVE_STEPS.len() {
+ script.push(todo_write(&FIVE_STEPS, completed));
+ script.push(text_completion(&format!("Step {completed} done.")));
+ }
+ reset_script(script);
+ let stack = boot_stack().await;
+
+ let mut events = spawn_sse_collector(format!(
+ "{}/events?client_id=harness-todo-five",
+ stack.rpc_base
+ ));
+
+ // Turn 1: the whole plan lands, first item in progress.
+ send_web_chat(
+ &stack.rpc_base,
+ 600,
+ "harness-todo-five",
+ "thread-todo-five",
+ "Summarise the report in five steps and work through them.",
+ )
+ .await;
+ let (terminal, results) = collect_turn_tool_results(&mut events, Duration::from_secs(60)).await;
+ assert_eq!(
+ terminal.get("event").and_then(Value::as_str),
+ Some("chat_done"),
+ "turn 1: {terminal}"
+ );
+ let first = tool_result_payload(&results, "todo");
+ assert_eq!(
+ todo_statuses(&first),
+ vec!["in_progress", "pending", "pending", "pending", "pending"],
+ "turn 1 payload: {first}"
+ );
+ let contents: Vec<&str> = first["todos"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|item| item["content"].as_str().unwrap())
+ .collect();
+ assert_eq!(contents, FIVE_STEPS.to_vec());
+ assert!(
+ first["markdown"]
+ .as_str()
+ .unwrap()
+ .starts_with("- [~] Read the request\n- [ ] Draft the outline"),
+ "markdown mirrors the list: {first}"
+ );
+ assert!(
- first["sessionId"].as_str().is_some_and(|s| !s.is_empty()),
- "the list is bound to the orchestrator's session: {first}"
++ first["threadId"]
++ .as_str()
++ .is_some_and(|key| key.contains("thread-todo-five")),
++ "the list is keyed by the session of the thread the turn ran in: {first}"
+ );
+
+ // Turns 2-6: one more item completed each turn.
+ for completed in 1..=FIVE_STEPS.len() {
+ send_web_chat(
+ &stack.rpc_base,
+ 600 + completed as i64,
+ "harness-todo-five",
+ "thread-todo-five",
+ "continue",
+ )
+ .await;
+ let (terminal, results) =
+ collect_turn_tool_results(&mut events, Duration::from_secs(60)).await;
+ assert_eq!(
+ terminal.get("event").and_then(Value::as_str),
+ Some("chat_done"),
+ "turn {}: {terminal}",
+ completed + 1
+ );
+ let payload = tool_result_payload(&results, "todo");
+ let expected: Vec<String> = FIVE_STEPS
+ .iter()
+ .enumerate()
+ .map(|(i, _)| {
+ if i < completed {
+ "completed"
+ } else if i == completed {
+ "in_progress"
+ } else {
+ "pending"
+ }
+ .to_string()
+ })
+ .collect();
+ assert_eq!(
+ todo_statuses(&payload),
+ expected,
+ "after {completed} done: {payload}"
+ );
+ }
+
+ // The model was told what it wrote back: the tool message in the next
+ // upstream request is the same payload the socket carried.
+ let requests = with_captured(|c| c.clone());
+ let last_turn = serde_json::to_string(
+ requests
+ .last()
+ .unwrap()
+ .pointer("/body/messages")
+ .expect("upstream request carries messages"),
+ )
+ .unwrap();
+ assert!(
+ last_turn.contains(r#"\"todos\""#),
+ "the model is handed the JSON list back, not a bare acknowledgement: {last_turn}"
+ );
+
+ // What a reloaded pane sees: every write persisted in the turn state,
+ // the newest with all five completed.
+ let turns = turn_state_history(&stack.rpc_base, 650, "thread-todo-five").await;
+ assert_eq!(turns.len(), FIVE_STEPS.len() + 1, "one snapshot per turn");
+ let rows = persisted_tool_rows(&turns, "todo");
+ assert_eq!(
+ rows.len(),
+ FIVE_STEPS.len() + 1,
+ "one todo row per turn: {rows:?}"
+ );
+ for row in &rows {
+ assert_eq!(row["status"].as_str(), Some("success"), "{row}");
+ assert!(
+ row["output"].as_str().is_some(),
+ "persisted row keeps the output: {row}"
+ );
+ }
+ let last: Value = serde_json::from_str(rows.last().unwrap()["output"].as_str().unwrap())
+ .expect("persisted output is the JSON payload");
+ assert_eq!(
+ todo_statuses(&last),
+ vec!["completed"; FIVE_STEPS.len()],
+ "final persisted list: {last}"
+ );
+
+ stack.shutdown();
+}
+
+/// Two `in_progress` items break the single-focus invariant: the store
+/// refuses the write, the agent gets a tool error it can correct, and the
+/// list it wrote before is untouched.
+#[test]
+fn todo_list_rejects_two_items_in_progress() {
+ run_on_agent_stack(
+ "todo_list_rejects_two_items_in_progress",
+ todo_list_rejects_two_items_in_progress_inner,
+ );
+}
+
+async fn todo_list_rejects_two_items_in_progress_inner() {
+ let _lock = env_lock();
+ reset_script(vec![
+ todo_write(&["Only step", "Next step"], 0),
+ tool_call_completion(
+ "todo",
+ json!({ "todos": [
+ { "content": "Only step", "status": "in_progress" },
+ { "content": "Next step", "status": "in_progress" }
+ ] }),
+ ),
+ // A read (no `todos`) shows the earlier write survived the rejection.
+ tool_call_completion("todo", json!({})),
+ text_completion("Kept one thing in progress."),
+ ]);
+ let stack = boot_stack().await;
+
+ let mut events = spawn_sse_collector(format!(
+ "{}/events?client_id=harness-todo-invariant",
+ stack.rpc_base
+ ));
+ send_web_chat(
+ &stack.rpc_base,
+ 700,
+ "harness-todo-invariant",
+ "thread-todo-invariant",
+ "track two things at once",
+ )
+ .await;
+ let (terminal, results) = collect_turn_tool_results(&mut events, Duration::from_secs(60)).await;
+ assert_eq!(
+ terminal.get("event").and_then(Value::as_str),
+ Some("chat_done"),
+ "{terminal}"
+ );
+
+ let todo_frames: Vec<&Value> = results
+ .iter()
+ .filter(|frame| frame.get("tool_name").and_then(Value::as_str) == Some("todo"))
+ .collect();
+ assert!(
+ todo_frames
+ .iter()
+ .all(|frame| frame["tool_call_id"].as_str() == Some("call_todo")),
+ "the todo tool is unpacked — every frame is a direct `todo` call: {todo_frames:?}"
+ );
+ assert_eq!(
+ todo_frames.len(),
+ 3,
+ "write, rejected write, read: {results:?}"
+ );
+ assert_eq!(todo_frames[0]["success"], json!(true), "{}", todo_frames[0]);
+ assert_eq!(
+ todo_frames[1]["success"],
+ json!(false),
+ "two in_progress must be rejected: {}",
+ todo_frames[1]
+ );
+ assert!(
+ todo_frames[1]["output"]
+ .as_str()
+ .unwrap_or("")
+ .contains("in_progress"),
+ "the error names the invariant: {}",
+ todo_frames[1]
+ );
+ let read: Value = serde_json::from_str(todo_frames[2]["output"].as_str().unwrap()).unwrap();
+ assert_eq!(
+ todo_statuses(&read),
+ vec!["in_progress", "pending"],
+ "the rejected write left the list untouched: {read}"
+ );
+
+ stack.shutdown();
+}
+
+/// The thread goal across turns: `goal_set` records the objective with a
+/// budget and answers with the structured goal; a later turn's `goal_get`
+/// reads the same goal back (it persisted); `goal_complete` closes it. Each
+/// payload is what the goal banner renders, live and after reload.
+#[test]
+fn thread_goal_is_set_read_back_and_completed_across_turns() {
+ run_on_agent_stack(
+ "thread_goal_is_set_read_back_and_completed_across_turns",
+ thread_goal_is_set_read_back_and_completed_across_turns_inner,
+ );
+}
+
+async fn thread_goal_is_set_read_back_and_completed_across_turns_inner() {
+ let _lock = env_lock();
+ reset_script(vec![
+ tool_call_completion(
+ "goal_set",
+ json!({ "objective": "Ship the v2 release notes", "token_budget": 50000 }),
+ ),
+ text_completion("Goal recorded."),
+ tool_call_completion("goal_get", json!({})),
+ text_completion("Still on it."),
+ tool_call_completion("goal_complete", json!({})),
+ text_completion("Release notes shipped."),
+ ]);
+ let stack = boot_stack().await;
+
+ let mut events =
+ spawn_sse_collector(format!("{}/events?client_id=harness-goal", stack.rpc_base));
+
+ // Turn 1: goal_set.
+ send_web_chat(
+ &stack.rpc_base,
+ 800,
+ "harness-goal",
+ "thread-goal",
+ "Ship the v2 release notes.",
+ )
+ .await;
+ let (terminal, results) = collect_turn_tool_results(&mut events, Duration::from_secs(60)).await;
+ assert_eq!(terminal["event"].as_str(), Some("chat_done"), "{terminal}");
+ let set = tool_result_payload(&results, "goal_set");
+ assert_eq!(
+ set["goal"]["objective"], "Ship the v2 release notes",
+ "{set}"
+ );
+ assert_eq!(set["goal"]["status"], "active", "{set}");
+ assert_eq!(set["goal"]["tokenBudget"], 50000, "{set}");
+ assert_eq!(
+ set["goal"]["threadId"], "thread-goal",
+ "bound to the chat thread: {set}"
+ );
+ let goal_id = set["goal"]["goalId"]
+ .as_str()
+ .filter(|id| !id.is_empty())
+ .expect("goal_set mints a goal id")
+ .to_string();
+ assert!(
+ set["text"].as_str().unwrap().starts_with("Goal set."),
+ "the model-facing text: {set}"
+ );
+
+ // Turn 2: goal_get reads the persisted goal back — same id, same objective
+ // and budget, still active. (Token accounting is not asserted here: the
+ // scripted upstream returns no `usage`, so a turn charges nothing against
+ // the budget. `agent::goals::runtime`'s unit tests cover the accounting
+ // and the budget-limit transition directly.)
+ send_web_chat(
+ &stack.rpc_base,
+ 801,
+ "harness-goal",
+ "thread-goal",
+ "status?",
+ )
+ .await;
+ let (terminal, results) = collect_turn_tool_results(&mut events, Duration::from_secs(60)).await;
+ assert_eq!(terminal["event"].as_str(), Some("chat_done"), "{terminal}");
+ let got = tool_result_payload(&results, "goal_get");
+ assert_eq!(
+ got["goal"]["goalId"], goal_id,
+ "same goal across turns: {got}"
+ );
+ assert_eq!(got["goal"]["status"], "active", "{got}");
+ assert_eq!(
+ got["goal"]["objective"], "Ship the v2 release notes",
+ "{got}"
+ );
+ assert_eq!(
+ got["goal"]["tokenBudget"], 50000,
+ "the budget persisted: {got}"
+ );
+
+ // Turn 3: goal_complete.
+ send_web_chat(&stack.rpc_base, 802, "harness-goal", "thread-goal", "done?").await;
+ let (terminal, results) = collect_turn_tool_results(&mut events, Duration::from_secs(60)).await;
+ assert_eq!(terminal["event"].as_str(), Some("chat_done"), "{terminal}");
+ let done = tool_result_payload(&results, "goal_complete");
+ assert_eq!(done["goal"]["goalId"], goal_id, "{done}");
+ assert_eq!(done["goal"]["status"], "complete", "{done}");
+ assert!(
+ done["text"]
+ .as_str()
+ .unwrap()
+ .starts_with("Goal marked complete."),
+ "{done}"
+ );
+
+ // The persisted turn state carries every goal payload for a reload: the
+ // newest row is the completion.
+ let turns = turn_state_history(&stack.rpc_base, 850, "thread-goal").await;
+ assert_eq!(turns.len(), 3, "one snapshot per turn");
+ for name in ["goal_set", "goal_get", "goal_complete"] {
+ let rows = persisted_tool_rows(&turns, name);
+ assert_eq!(rows.len(), 1, "one persisted `{name}` row: {rows:?}");
+ assert_eq!(rows[0]["status"].as_str(), Some("success"), "{}", rows[0]);
+ }
+ let persisted_done: Value = serde_json::from_str(
+ persisted_tool_rows(&turns, "goal_complete")[0]["output"]
+ .as_str()
+ .expect("persisted goal_complete keeps its output"),
+ )
+ .unwrap();
+ assert_eq!(
+ persisted_done["goal"]["status"], "complete",
+ "{persisted_done}"
+ );
+
+ // A thread that never set a goal reads back none — the payload the pane
+ // treats as "no banner".
+ reset_script(vec![
+ tool_call_completion("goal_get", json!({})),
+ text_completion("No goal here."),
+ ]);
+ send_web_chat(
+ &stack.rpc_base,
+ 803,
+ "harness-goal",
+ "thread-goal-none",
+ "any goal?",
+ )
+ .await;
+ let (terminal, results) = collect_turn_tool_results(&mut events, Duration::from_secs(60)).await;
+ assert_eq!(terminal["event"].as_str(), Some("chat_done"), "{terminal}");
+ let none = tool_result_payload(&results, "goal_get");
+ assert!(none["goal"].is_null(), "{none}");
+ assert_eq!(none["text"], "no goal set for this thread", "{none}");
+
+ stack.shutdown();
+}