Skip to content

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

feat(agent): a finished plan's notes go to active and long-term memory

sanil-234508f4212be1
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs
index eeb5422052..680a5e99cb 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs
@@ -361,6 +361,13 @@ impl OpenHumanTurnPrelude {
&self,
receipt: &CommitReceipt<OpenHumanRunContext>,
) {
- self.memory_post_turn(receipt);
+ // A plan that finished this turn hands its notes over: they stay for
+ // the thread's next turns and go to long-term memory with the reply.
+ let finished_plan = crate::agent::tinyagents::state_block::close_finished_plan(
+ &self.workspace_dir,
+ self.thread_id.as_deref(),
+ )
+ .await;
+ self.memory_post_turn(receipt, finished_plan);
}
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/state_block.rs b/crates/openhuman-core/src/agent/tinyagents/state_block.rs
index 6652102323..1fd16a0b05 100644
--- a/crates/openhuman-core/src/agent/tinyagents/state_block.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/state_block.rs
@@ -11,11 +11,19 @@
//! once, current on every call, and a paused goal comes with the choice to
//! resume it, replace it or leave it, which the model makes with the goal
//! tools after reading the message.
+//!
+//! The block also shows the agent's own notes (facts, blockers, current
+//! approach), written through the `todo` tool. After a turn's final reply,
+//! [`close_finished_plan`] checks whether the plan finished: if so its notes
+//! move to the thread's "last finished task" (active memory, shown on the
+//! thread's next turns) and come back for the session host to queue into
+//! long-term memory (`memory::lifecycle::plan_notes`).
use std::sync::Arc;
use tinyagents_harness::runtime::AgentHarness;
use tinyagents_harness::store::Store;
+use tinyagents_harness_tools::scratchpad::{store as scratchpad_store, ClosedPlan};
use tinyagents_harness_tools::state_block::StateBlockMiddleware;
/// Whether a turn gets the run-state block.
@@ -46,6 +54,46 @@ pub(super) fn install<C: Send + Sync + 'static>(
}
}
+/// A plan that finished this turn, with what it was for.
+pub(crate) struct FinishedPlan {
+ /// The plan with its notes.
+ pub plan: ClosedPlan,
+ /// The thread goal's objective when the plan finished, if it had one.
+ pub goal: Option<String>,
+}
+
+/// After the final reply: when the thread's plan finished, moves its notes to
+/// the thread's last finished task and returns the plan with its notes for
+/// long-term memory. `None` without a thread, while the plan is open, without
+/// notes, or when the store cannot be read.
+pub(crate) async fn close_finished_plan(
+ workspace_dir: &std::path::Path,
+ thread_id: Option<&str>,
+) -> Option<FinishedPlan> {
+ let thread_id = thread_id.map(str::trim).filter(|id| !id.is_empty())?;
+ let store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;
+ match scratchpad_store::close_finished_plan(&store, thread_id).await {
+ Ok(Some(plan)) => {
+ tracing::debug!(
+ thread_id,
+ facts = plan.notes.facts.len(),
+ blockers = plan.notes.blockers.len(),
+ "[state_block] plan finished: notes moved to the last task"
+ );
+ let goal =
+ crate::agent::goals::runtime::load_for_thread(workspace_dir, Some(thread_id))
+ .await
+ .map(|goal| goal.objective);
+ Some(FinishedPlan { plan, goal })
+ }
+ Ok(None) => None,
+ Err(error) => {
+ tracing::debug!(thread_id, %error, "[state_block] close_finished_plan failed");
+ None
+ }
+ }
+}
+
#[cfg(test)]
#[path = "state_block_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/state_block_tests.rs b/crates/openhuman-core/src/agent/tinyagents/state_block_tests.rs
index b03603adcb..206013c7dd 100644
--- a/crates/openhuman-core/src/agent/tinyagents/state_block_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/state_block_tests.rs
@@ -35,3 +35,45 @@ fn install_needs_the_scope_and_a_store() {
);
assert_eq!(installed(Some(store), false, Some("planner")), 0);
}
+
+#[tokio::test]
+async fn a_finished_plan_hands_its_notes_over_at_the_end_of_the_turn() {
+ use tinyagents_harness_tools::scratchpad::ScratchpadUpdate;
+ use tinyagents_harness_tools::todos::{store as todo_store, TodoItem};
+
+ let workspace = tempfile::tempdir().unwrap();
+ let store = crate::storage::sessions::stores_or_ephemeral(workspace.path()).kv;
+ todo_store::replace(&store, "t", vec![TodoItem::new("Write the migration")])
+ .await
+ .unwrap();
+ scratchpad_store::apply(
+ &store,
+ "t",
+ &ScratchpadUpdate {
+ facts: vec!["the table is auth_users".to_string()],
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+
+ assert!(close_finished_plan(workspace.path(), None).await.is_none());
+ assert!(
+ close_finished_plan(workspace.path(), Some("t"))
+ .await
+ .is_none(),
+ "the plan is still open"
+ );
+ todo_store::complete(&store, "t", 1).await.unwrap();
+ let finished = close_finished_plan(workspace.path(), Some("t"))
+ .await
+ .expect("the plan finished with notes");
+ assert_eq!(finished.plan.notes.facts, ["the table is auth_users"]);
+ assert_eq!(finished.goal, None, "the thread has no goal");
+ assert!(
+ close_finished_plan(workspace.path(), Some("t"))
+ .await
+ .is_none(),
+ "handed over once"
+ );
+}
diff --git a/crates/openhuman-core/src/memory/README.md b/crates/openhuman-core/src/memory/README.md
index 32dac9d419..de5d7667f9 100644
--- a/crates/openhuman-core/src/memory/README.md
+++ b/crates/openhuman-core/src/memory/README.md
@@ -133,6 +133,17 @@ memory_summarizer -------> prefetch::compaction
memory_summarizer.rs) queues recall of the folded-away turns
```
+A finished plan's notes go to memory at the same point. The agent writes
+facts and blockers through the `todo` tool while it works (TinyAgents
+`scratchpad`, shown in the run-state block). After the commit, the session
+host calls `agent::tinyagents::state_block::close_finished_plan`; if the
+thread's plan has steps and none open, its notes move to the thread's "last
+finished task" (the block shows them on the next turns, before recall could
+return them), and [`lifecycle/plan_notes.rs`](./lifecycle/plan_notes.rs)
+queues each one as a learning through the memory tool's write queue: facts as
+`fact`, blockers as `correction`, with the goal or first plan step as
+evidence. An open plan's notes stay in the scratchpad for the next turn.
+
Turn indices follow the committed transcript: the user message of the turn
after `n` committed turns is `2n` and its reply `2n + 1`. They are stable
across retries and restarts, which is what lets TinyMemory treat a retried
diff --git a/crates/openhuman-core/src/memory/lifecycle/mod.rs b/crates/openhuman-core/src/memory/lifecycle/mod.rs
index ea89630045..7b45772227 100644
--- a/crates/openhuman-core/src/memory/lifecycle/mod.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/mod.rs
@@ -18,6 +18,7 @@
pub mod date_hint;
pub mod hooks;
pub mod jobs;
+pub mod plan_notes;
pub(crate) mod prefetch;
pub mod sender;
pub mod views;
diff --git a/crates/openhuman-core/src/memory/lifecycle/plan_notes.rs b/crates/openhuman-core/src/memory/lifecycle/plan_notes.rs
new file mode 100644
index 0000000000..5ff7c56fba
--- /dev/null
+++ b/crates/openhuman-core/src/memory/lifecycle/plan_notes.rs
@@ -0,0 +1,122 @@
+//! A finished plan's notes, kept in long-term memory.
+//!
+//! The agent writes facts and blockers to its scratchpad through the `todo`
+//! tool while it works (TinyAgents `scratchpad`). After the final reply of a
+//! turn in which the plan finished, the session host takes them
+//! (`scratchpad::store::close_finished_plan`) and this module queues each one
+//! as a learning on the agent's node, through the same durable queue as the
+//! `memory` tool's `learn`: facts as `fact`, blockers as `correction`. The
+//! queue scrubs and confines them exactly as it does a model's own write, and
+//! nothing here waits on the engine.
+
+use std::sync::Arc;
+
+use serde_json::json;
+use tinyagents_harness_tools::scratchpad::ClosedPlan;
+use tinymemory_tools::layout::identity::ResolvedIdentity;
+use tinymemory_tools::{CallContext, SingleTool};
+
+use crate::config::Config;
+use crate::memory::tool_writes::HostWriteSink;
+use crate::memory::tools::{CallFacts, MEMORY_TOOL_NAME};
+
+/// Longest task label carried as a learning's evidence, in characters.
+const MAX_TASK_CHARS: usize = 160;
+
+/// One learning per note: `(text, kind)`.
+fn learnings(plan: &ClosedPlan) -> Vec<(String, &'static str)> {
+ let facts = plan.notes.facts.iter().map(|fact| (fact.clone(), "fact"));
+ let blockers = plan
+ .notes
+ .blockers
+ .iter()
+ .map(|blocker| (format!("Blocker: {blocker}"), "correction"));
+ facts.chain(blockers).collect()
+}
+
+/// What the notes came from: the goal, else the plan's first step.
+fn task_label(plan: &ClosedPlan, goal: Option<&str>) -> String {
+ let task = goal
+ .or_else(|| plan.items.first().map(|item| item.content.as_str()))
+ .unwrap_or_default();
+ let line = task.split_whitespace().collect::<Vec<_>>().join(" ");
+ if line.chars().count() <= MAX_TASK_CHARS {
+ return line;
+ }
+ let mut cut: String = line.chars().take(MAX_TASK_CHARS - 1).collect();
+ cut.push('…');
+ cut
+}
+
+/// Queues `plan`'s notes as learnings of `identity`, with the thread `goal`
+/// (else the plan's first step) as their evidence, returning how many were
+/// queued. Best-effort: a refused write (memory off, queue full) is logged and
+/// skipped.
+pub async fn learn_plan_notes(
+ config: Arc<Config>,
+ identity: &ResolvedIdentity,
+ workspace: Option<String>,
+ plan: &ClosedPlan,
+ goal: Option<&str>,
+) -> usize {
+ let scope = CallFacts {
+ workspace,
+ thread_id: Some(plan.thread_id.clone()),
+ ..CallFacts::of_resolved(identity)
+ }
+ .native_scope(&config);
+ let tool = SingleTool::queued(
+ MEMORY_TOOL_NAME,
+ scope,
+ Arc::new(HostWriteSink::new(config.clone())),
+ );
+ let evidence = format!(
+ "noted by the agent while working on: {}",
+ task_label(plan, goal)
+ );
+ let notes = learnings(plan);
+ let total = notes.len();
+ // The queue does blocking file I/O, as it does for the memory tool.
+ let runtime = tokio::runtime::Handle::current();
+ let queued = tokio::task::spawn_blocking(move || {
+ runtime.block_on(async {
+ let mut queued = 0;
+ for (text, kind) in notes {
+ let args = json!({
+ "action": "learn",
+ "text": text,
+ "kind": kind,
+ "evidence": evidence,
+ });
+ match tool
+ .call(
+ args,
+ CallContext {
+ thread_window: None,
+ },
+ )
+ .await
+ {
+ Ok(_) => queued += 1,
+ Err(error) => {
+ tracing::debug!(%error, "[memory] plan_notes: learning not queued");
+ }
+ }
+ }
+ queued
+ })
+ })
+ .await
+ .unwrap_or(0);
+ tracing::debug!(
+ thread_id = %plan.thread_id,
+ queued,
+ total,
+ "[memory] plan_notes: finished plan's notes queued as learnings"
+ );
+ queued
+}
+
+#[cfg(test)]
+#[path = "plan_notes_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/lifecycle/plan_notes_tests.rs b/crates/openhuman-core/src/memory/lifecycle/plan_notes_tests.rs
new file mode 100644
index 0000000000..8f10973538
--- /dev/null
+++ b/crates/openhuman-core/src/memory/lifecycle/plan_notes_tests.rs
@@ -0,0 +1,45 @@
+use super::*;
+
+use tinyagents_harness_tools::scratchpad::TaskNotes;
+use tinyagents_harness_tools::todos::{TodoItem, TodoStatus};
+
+fn plan(first_step: &str) -> ClosedPlan {
+ ClosedPlan {
+ thread_id: "t".to_string(),
+ items: vec![TodoItem::with_status(first_step, TodoStatus::Completed)],
+ notes: TaskNotes {
+ facts: vec!["the table is auth_users".to_string()],
+ blockers: vec!["ALTER without a default timed out".to_string()],
+ },
+ }
+}
+
+#[test]
+fn facts_become_fact_learnings_and_blockers_corrections() {
+ assert_eq!(
+ learnings(&plan("Dump the schema")),
+ vec![
+ ("the table is auth_users".to_string(), "fact"),
+ (
+ "Blocker: ALTER without a default timed out".to_string(),
+ "correction"
+ ),
+ ]
+ );
+}
+
+#[test]
+fn the_task_is_the_goal_else_the_first_step_on_one_bounded_line() {
+ assert_eq!(
+ task_label(&plan("Dump"), Some("Add org_id\nwithout downtime")),
+ "Add org_id without downtime"
+ );
+ assert_eq!(
+ task_label(&plan("Dump the schema"), None),
+ "Dump the schema"
+ );
+ let long = "x".repeat(MAX_TASK_CHARS + 10);
+ let label = task_label(&plan(&long), None);
+ assert_eq!(label.chars().count(), MAX_TASK_CHARS);
+ assert!(label.ends_with('…'));
+}
diff --git a/crates/openhuman-core/src/memory/lifecycle/session_hooks.rs b/crates/openhuman-core/src/memory/lifecycle/session_hooks.rs
index b53916edd9..16908edbca 100644
--- a/crates/openhuman-core/src/memory/lifecycle/session_hooks.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/session_hooks.rs
@@ -200,9 +200,14 @@ impl OpenHumanTurnPrelude {
}))
}
- /// Logs the committed reply (spawned; never delays the commit) and
- /// publishes `ConversationTurnCommitted`.
- pub(super) fn memory_post_turn(&self, receipt: &CommitReceipt<OpenHumanRunContext>) {
+ /// Logs the committed reply (spawned; never delays the commit), queues a
+ /// plan that finished this turn's notes as learnings, and publishes
+ /// `ConversationTurnCommitted`.
+ pub(super) fn memory_post_turn(
+ &self,
+ receipt: &CommitReceipt<OpenHumanRunContext>,
+ finished_plan: Option<crate::agent::tinyagents::state_block::FinishedPlan>,
+ ) {
let (user_text, pending) = {
let mut mutable = self
.mutable
@@ -263,6 +268,16 @@ impl OpenHumanTurnPrelude {
pending.channel,
)
.await;
+ if let Some(finished) = finished_plan {
+ crate::memory::lifecycle::plan_notes::learn_plan_notes(
+ config.clone(),
+ &pending.identity,
+ Some(prelude.action_dir.display().to_string()),
+ &finished.plan,
+ finished.goal.as_deref(),
+ )
+ .await;
+ }
};
self.dispatch_ctx()
.spawn(deferred_memory_work(profile_context, work));
diff --git a/crates/openhuman-core/src/memory/lifecycle/session_hooks_tests.rs b/crates/openhuman-core/src/memory/lifecycle/session_hooks_tests.rs
index 96c046a241..bf4d449f82 100644
--- a/crates/openhuman-core/src/memory/lifecycle/session_hooks_tests.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/session_hooks_tests.rs
@@ -102,7 +102,7 @@ async fn session_pre_and_post_turn_use_the_external_channel_origin_not_event_lab
},
transcript: None,
};
- prelude.memory_post_turn(&receipt);
+ prelude.memory_post_turn(&receipt, None);
tokio::time::timeout(std::time::Duration::from_secs(5), async {
loop {
diff --git a/crates/openhuman-core/src/memory/tools.rs b/crates/openhuman-core/src/memory/tools.rs
index b8dac7d55f..d4301aa026 100644
--- a/crates/openhuman-core/src/memory/tools.rs
+++ b/crates/openhuman-core/src/memory/tools.rs
@@ -85,7 +85,12 @@ impl CallFacts {
/// The facts of a call made by `identity`, without a run context.
#[must_use]
pub fn of(config: &Config, identity: &tinymemory_tools::layout::identity::Identity) -> Self {
- let resolved = identity.resolve(&crate::memory::scope::identity_pins(config));
+ Self::of_resolved(&identity.resolve(&crate::memory::scope::identity_pins(config)))
+ }
+
+ /// The facts of a call made by an already resolved identity.
+ #[must_use]
+ pub fn of_resolved(resolved: &tinymemory_tools::layout::identity::ResolvedIdentity) -> Self {
Self {
agent_id: Some(resolved.agent_id.clone()),
namespace: resolved.layout.learnings().clone(),
@@ -94,7 +99,7 @@ impl CallFacts {
}
}
- fn native_scope(&self, config: &Config) -> ToolScope {
+ pub(crate) fn native_scope(&self, config: &Config) -> ToolScope {
ToolScope {
place: self.namespace.clone(),
reach: Some(self.reach.clone()),