Skip to content

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

fix(memory): make "remember this" a write before the reply

Shanue3dd532a2dfa
diff --git a/.claude/memory.md b/.claude/memory.md
index 3fc20a2c08..ec822b6d93 100644
--- a/.claude/memory.md
+++ b/.claude/memory.md
@@ -365,3 +365,4 @@ Quick reference for anyone starting with Claude on this project. Updated by the
- **`SYNC_PASS_MAX_ITEMS` (200) sizes one `AcceptSourceItems` call** — the module embeds each document in turn (~1.7 s each) against the 15-min `module_call_slow!` deadline; 500 tripped it. The Sources-row loop (`composio_sync_budgeted`, ≤50 passes) is unaffected; the four entry points that sync once per invocation (`periodic.rs`, `memory/ops/sync.rs`, `bus_part_02.rs` `connection_created`, `slack/rpc.rs`) go through `ops::pass_budget::run_sync_within_budget`, which repeats the pass within a 500-**record** budget. Charge that budget by `records_read`, never by `written`: a module returning already-ingested pages with `more_pending` would otherwise be asked forever.
- **`providers_ops.rs` sits at exactly 750 lines** — the `check-openhuman-rust-layout.mjs` limit; edits there must be net-zero lines or split the file.
- **`node app/scripts/build-parallel.mjs` fails with `vite: command not found`** when run directly — it shells out to bare `tsc`/`vite`; use `pnpm build` or prefix `PATH=app/node_modules/.bin:$PATH`.
+- **"Got it, saved" with zero tool calls (issue #6048)** — the memory *write* tools (`memory_store`, `save_preference`) are always registered, but nothing in the prompt said a request to remember must become a tool call, or forbade claiming a save without one; `memory_store` also required an invented `namespace` + `key`. Now `MemoryWriteSection` (`agent/learning/prompt_sections.rs`, `## Remembering`) is registered by `builder/helpers.rs::add_memory_prompt_sections` whenever a write tool is registered **and** visible, independent of `learning.enabled`; `memory_store` defaults `namespace` to `DEFAULT_AGENT_MEMORY_NAMESPACE` (`global`) and derives `key` from the content (`derive_key`, FNV suffix). The archivist is not a safety net here: it writes the turn to the FTS5 episodic table only, and files raw prose into the tree at segment close. `factory.rs` sits at its legacy cap (1552): put new gating in `helpers.rs`, not inline.
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index ed70f46315..6e55471825 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -351,6 +351,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an
| 8.4.4 | Same-Topic Contradiction (replace) | RU | `src/openhuman/agent/tools/save_preference_tests.rs::recategorising_moves_pref_between_namespaces` | ✅ | `ON CONFLICT REPLACE`; a topic lives in exactly one scope |
| 8.4.5 | Cross-Topic Contradiction Surfacing | RU | `src/openhuman/agent/tools/save_preference_tests.rs::save_surfaces_related_preference_for_contradiction_check` | ✅ | Related prefs surfaced in the tool result for the chat agent to resolve |
| 8.4.6 | vector_chunks Model-Signature Recall Guard | RU | `src/openhuman/memory/store/namespace_store/query_tests.rs::vector_recall_excludes_other_model_signature` | ✅ | Excludes cross-model vectors; dim-guards legacy rows |
+| 8.4.10 | Memory-Write Instruction + `memory_store` defaults | RU | `src/openhuman/agent/learning/prompt_sections_tests_2_tests.rs::memory_write_*`, `src/openhuman/agent/learning/prompt_sections_tests_2_tests.rs::write_tool_gate_*`, `src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs::memory_write_instruction_*`, `src/openhuman/memory/tools/store_tests.rs::resolve_*` | ✅ | #6048: "remember X" must be a write before the reply; section keyed on write-tool visibility, not `learning.enabled`; `memory_store` namespace/key optional |
### 8.5 Long-term Goals
diff --git a/src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs b/src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs
index 84732e0712..66756f0e9c 100644
--- a/src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs
+++ b/src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs
@@ -619,3 +619,75 @@ async fn from_config_for_agent_synthesizes_custom_registry_entry_with_named_scop
"a tool outside the custom agent's allowlist must not be visible: {visible:?}"
);
}
+
+// ── Memory-write instruction (#6048) ─────────────────────────────────────────
+//
+// "Please remember …" was answered with "saved" and zero tool calls. The rule
+// that a request to remember must become a write before the reply is keyed on
+// the write tools being offered — never on `learning.enabled`, which the
+// default install leaves off.
+
+#[tokio::test]
+async fn memory_write_instruction_is_present_with_learning_disabled() {
+ crate::openhuman::memory::host_impls::install_for_tests();
+ use crate::openhuman::agent::context::prompt::LearnedContextData;
+ use crate::openhuman::agent::harness::session::types::Agent;
+
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ assert!(
+ !config.learning.enabled,
+ "the default install has learning off; the write rule must not depend on it"
+ );
+ let orchestrator = builtin_def("orchestrator");
+ let agent = Agent::build_session_agent_inner(
+ &config,
+ "orchestrator",
+ Some(&orchestrator),
+ None,
+ false,
+ None,
+ )
+ .expect("build session");
+
+ let prompt = agent
+ .build_system_prompt(LearnedContextData::default())
+ .expect("build_system_prompt");
+ assert!(
+ prompt.contains("## Remembering"),
+ "a session offering memory_store / save_preference must carry the write rule"
+ );
+}
+
+#[tokio::test]
+async fn memory_write_instruction_is_absent_when_no_write_tool_is_visible() {
+ crate::openhuman::memory::host_impls::install_for_tests();
+ use crate::openhuman::agent::context::prompt::LearnedContextData;
+ use crate::openhuman::agent::harness::session::types::Agent;
+
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let orchestrator = builtin_def("orchestrator");
+ let mut profile = crate::openhuman::agent::profiles::store::built_in_default_profile();
+ profile.id = "alice".to_string();
+ profile.built_in = false;
+ profile.allowed_tools = Some(vec!["file_read".to_string()]);
+
+ let agent = Agent::build_session_agent_inner(
+ &config,
+ "orchestrator",
+ Some(&orchestrator),
+ None,
+ false,
+ Some(&profile),
+ )
+ .expect("build profile-scoped session");
+
+ let prompt = agent
+ .build_system_prompt(LearnedContextData::default())
+ .expect("build_system_prompt");
+ assert!(
+ !prompt.contains("## Remembering"),
+ "a rule about tools the model cannot see would only teach it to apologise"
+ );
+}
diff --git a/src/openhuman/agent/harness/session/builder/factory.rs b/src/openhuman/agent/harness/session/builder/factory.rs
index bd3d76c029..2228e54561 100644
--- a/src/openhuman/agent/harness/session/builder/factory.rs
+++ b/src/openhuman/agent/harness/session/builder/factory.rs
@@ -978,34 +978,16 @@ impl Agent {
}
}
- // Phase 4 (#566): add the MemoryAccessSection bias instruction only
- // when at least one retrieval tool is actually loaded AND survives
- // filtering. We require both because:
- // - the tool may be filtered out by the agent's scope config
- // - the tool may not be registered at all on this agent (tool
- // listing is build-time configurable)
- // An empty `visible` set means "no filter" (wildcard / orchestrator
- // path); in that case any registered retrieval tool is reachable.
- if config.learning.enabled {
- let recall_tools = ["memory_recall", "memory_search"];
- let has_retrieval = recall_tools.iter().any(|name| {
- let registered = tools.iter().any(|t| t.name() == *name)
- || delegation_tools.iter().any(|t| t.name() == *name);
- let allowed_by_filter = visible.is_empty() || visible.contains(*name);
- registered && allowed_by_filter
- });
- if has_retrieval {
- prompt_builder = prompt_builder.add_section(Box::new(
- crate::openhuman::agent::learning::MemoryAccessSection,
- ));
- log::debug!("[learning] memory_access prompt section registered");
- } else {
- log::debug!(
- "[learning] skipping MemoryAccessSection — neither memory_recall nor \
- memory_search is registered+visible for agent={agent_id}"
- );
- }
- }
+ // Memory prompt sections — the read side (#566) and the write side
+ // (#6048); both gates live in `helpers::add_memory_prompt_sections`.
+ prompt_builder = super::helpers::add_memory_prompt_sections(
+ prompt_builder,
+ config,
+ &tools,
+ &delegation_tools,
+ &visible,
+ agent_id,
+ );
// De-duplicate: some synthesised tool names may collide with
// already-registered tools (unlikely for `delegate_*` names but
diff --git a/src/openhuman/agent/harness/session/builder/helpers.rs b/src/openhuman/agent/harness/session/builder/helpers.rs
index c205c4fada..046dd3c865 100644
--- a/src/openhuman/agent/harness/session/builder/helpers.rs
+++ b/src/openhuman/agent/harness/session/builder/helpers.rs
@@ -21,6 +21,11 @@ use crate::openhuman::memory::tool_memory::{tool_memory_store, ToolMemoryRule};
use crate::openhuman::memory::Memory;
use std::sync::Arc;
+use crate::openhuman::agent::context::prompt::SystemPromptBuilder;
+use crate::openhuman::config::Config;
+use crate::openhuman::tools::traits::Tool;
+use std::collections::HashSet;
+
/// (#1400) Best-effort synchronous prefetch of eager tool-scoped rules.
///
/// `from_config_*` is sync but typically runs inside a multi-threaded
@@ -70,3 +75,53 @@ pub(super) fn prefetch_tool_memory_rules_blocking(
})
})
}
+
+/// Register the memory prompt sections a session should carry.
+///
+/// Two independent gates, one per direction:
+///
+/// - `MemoryAccessSection` (read side, #566): only when `learning.enabled` and
+/// a retrieval tool is offered.
+/// - `MemoryWriteSection` (write side, #6048): whenever a writing tool is
+/// offered, regardless of `learning.enabled`. The tools are registered either
+/// way, and a model that holds them with no rule on when to use them narrates
+/// a save it never made — "got it, saved" with zero tool calls.
+///
+/// Each gate needs the tool registered **and** visible after filtering
+/// (`any_tool_offered`): a rule about a tool the model cannot see would only
+/// teach it to apologise.
+pub(super) fn add_memory_prompt_sections(
+ prompt_builder: SystemPromptBuilder,
+ config: &Config,
+ tools: &[Box<dyn Tool>],
+ delegation_tools: &[Box<dyn Tool>],
+ visible: &HashSet<String>,
+ agent_id: &str,
+) -> SystemPromptBuilder {
+ use crate::openhuman::agent::learning::{
+ any_tool_offered, MemoryAccessSection, MemoryWriteSection, MEMORY_READ_TOOLS,
+ MEMORY_WRITE_TOOLS,
+ };
+ let mut prompt_builder = prompt_builder;
+ if config.learning.enabled {
+ if any_tool_offered(&MEMORY_READ_TOOLS, tools, delegation_tools, visible) {
+ prompt_builder = prompt_builder.add_section(Box::new(MemoryAccessSection));
+ log::debug!("[learning] memory_access prompt section registered");
+ } else {
+ log::debug!(
+ "[learning] skipping MemoryAccessSection — neither memory_recall nor \
+ memory_search is registered+visible for agent={agent_id}"
+ );
+ }
+ }
+ if any_tool_offered(&MEMORY_WRITE_TOOLS, tools, delegation_tools, visible) {
+ prompt_builder = prompt_builder.add_section(Box::new(MemoryWriteSection));
+ log::debug!("[memory_write] prompt section registered for agent={agent_id}");
+ } else {
+ log::debug!(
+ "[memory_write] skipping MemoryWriteSection — neither memory_store nor \
+ save_preference is registered+visible for agent={agent_id}"
+ );
+ }
+ prompt_builder
+}
diff --git a/src/openhuman/agent/learning/mod.rs b/src/openhuman/agent/learning/mod.rs
index 80b39788da..8c929f103f 100644
--- a/src/openhuman/agent/learning/mod.rs
+++ b/src/openhuman/agent/learning/mod.rs
@@ -46,8 +46,9 @@ pub use cache::FacetCache;
pub use candidate::{Buffer, CueFamily, EvidenceRef, FacetClass, LearningCandidate};
pub use profile_md_renderer::ProfileMdRenderer;
pub use prompt_sections::{
- load_learned_from_cache, LearnedContextSection, MemoryAccessSection, UserProfileSection,
- MEMORY_ACCESS_INSTRUCTION,
+ any_tool_offered, load_learned_from_cache, LearnedContextSection, MemoryAccessSection,
+ MemoryWriteSection, UserProfileSection, MEMORY_ACCESS_INSTRUCTION, MEMORY_READ_TOOLS,
+ MEMORY_WRITE_INSTRUCTION, MEMORY_WRITE_TOOLS,
};
pub use reflection::ReflectionHook;
pub use schemas::{
diff --git a/src/openhuman/agent/learning/prompt_sections.rs b/src/openhuman/agent/learning/prompt_sections.rs
index 1260fe5bde..873828e20e 100644
--- a/src/openhuman/agent/learning/prompt_sections.rs
+++ b/src/openhuman/agent/learning/prompt_sections.rs
@@ -19,7 +19,9 @@
//! prior sessions. Registered after `LearnedContextSection` in the section chain.
use crate::openhuman::agent::context::prompt::{PromptContext, PromptSection};
+use crate::openhuman::tools::traits::Tool;
use anyhow::Result;
+use std::collections::HashSet;
/// Injects recent observations and patterns from the learning subsystem.
pub struct LearnedContextSection;
@@ -129,6 +131,68 @@ impl PromptSection for MemoryAccessSection {
}
}
+// ── MemoryWriteSection ────────────────────────────────────────────────────────
+
+/// Static instruction that turns "remember this" into a write before the reply.
+///
+/// The read-side rule above tells the model when to look. Nothing told it that
+/// an explicit request to remember must become a tool call, or that it may not
+/// say "saved" without one — so, left to itself, it narrated a save it never
+/// made and the next chat had nothing to find (#6048). The text is frozen at
+/// compile time — no I/O at build time.
+pub struct MemoryWriteSection;
+
+/// The static prose injected whenever a memory-writing tool is offered. Kept
+/// at ≤ 80 words (the composition test pins the ceiling).
+pub const MEMORY_WRITE_INSTRUCTION: &str = "\
+## Remembering\n\
+\n\
+When the user asks you to remember, note, or keep something — a date, plan, \
+person, decision, or preference — write it before you confirm: `save_preference` \
+for preferences, `memory_store` for everything else. Never say saved, noted, or \
+remembered unless that write succeeded in this turn; if it failed or was refused, \
+say so instead.";
+
+impl PromptSection for MemoryWriteSection {
+ fn name(&self) -> &str {
+ "memory_write"
+ }
+
+ fn build(&self, _ctx: &PromptContext<'_>) -> Result<String> {
+ Ok(MEMORY_WRITE_INSTRUCTION.to_string())
+ }
+}
+
+/// The retrieval tools [`MemoryAccessSection`] is keyed on.
+pub const MEMORY_READ_TOOLS: [&str; 2] = ["memory_recall", "memory_search"];
+
+/// The writing tools [`MemoryWriteSection`] is keyed on.
+pub const MEMORY_WRITE_TOOLS: [&str; 2] = ["memory_store", "save_preference"];
+
+/// Whether any of `names` is registered on this session **and** survives tool
+/// filtering.
+///
+/// Both are required: a tool can be registered but filtered out by the agent's
+/// scope, or allowed by the filter but never registered on this agent. An empty
+/// `visible` set means "no filter" (the wildcard / orchestrator path), so any
+/// registered tool is reachable. A section that tells the model to call a tool
+/// it cannot see would only teach it to apologise.
+pub fn any_tool_offered(
+ names: &[&str],
+ tools: &[Box<dyn Tool>],
+ delegation_tools: &[Box<dyn Tool>],
+ visible: &HashSet<String>,
+) -> bool {
+ names.iter().any(|name| {
+ let registered = tools
+ .iter()
+ .chain(delegation_tools)
+ .any(|tool| tool.name() == *name);
+ let allowed_by_filter = visible.is_empty() || visible.contains(*name);
+ registered && allowed_by_filter
+ })
+}
+
// ── Cache-backed loader ───────────────────────────────────────────────────────
/// Maximum number of facets to include in the ambient prompt injection.
diff --git a/src/openhuman/agent/learning/prompt_sections_tests_2_tests.rs b/src/openhuman/agent/learning/prompt_sections_tests_2_tests.rs
index 71a9a08056..801e4b480e 100644
--- a/src/openhuman/agent/learning/prompt_sections_tests_2_tests.rs
+++ b/src/openhuman/agent/learning/prompt_sections_tests_2_tests.rs
@@ -289,3 +289,127 @@ fn memory_access_section_present_in_system_prompt_compose() {
"must render regardless of learned context"
);
}
+
+// ── MemoryWriteSection + tool gating (#6048) ─────────────────────────────────
+
+/// A tool that is nothing but a name: the gate reads names only.
+struct NamedTool(&'static str);
+
+#[async_trait]
+impl Tool for NamedTool {
+ fn name(&self) -> &str {
+ self.0
+ }
+
+ fn description(&self) -> &str {
+ "stub"
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({})
+ }
+
+ async fn execute(
+ &self,
+ _args: serde_json::Value,
+ ) -> anyhow::Result<crate::openhuman::tools::traits::ToolResult> {
+ Ok(crate::openhuman::tools::traits::ToolResult::success(
+ String::new(),
+ ))
+ }
+}
+
+fn named(names: &[&'static str]) -> Vec<Box<dyn Tool>> {
+ names
+ .iter()
+ .map(|name| Box::new(NamedTool(name)) as Box<dyn Tool>)
+ .collect()
+}
+
+fn visible(names: &[&str]) -> HashSet<String> {
+ names.iter().map(|name| (*name).to_string()).collect()
+}
+
+#[test]
+fn memory_write_section_renders_the_frozen_instruction() {
+ let section = MemoryWriteSection;
+ assert_eq!(section.name(), "memory_write");
+ let rendered = section
+ .build(&prompt_context(LearnedContextData::default()))
+ .unwrap();
+ assert_eq!(rendered.trim(), MEMORY_WRITE_INSTRUCTION.trim());
+ assert!(rendered.contains("## Remembering"), "{rendered}");
+ // Both write tools are named, and the rule the bug needed is stated.
+ assert!(rendered.contains("`memory_store`") && rendered.contains("`save_preference`"));
+ assert!(
+ rendered.contains("Never say saved"),
+ "the instruction must forbid claiming a save that did not happen: {rendered}"
+ );
+ // Not context-gated: renders for an empty learned context too.
+ let word_count = rendered.split_whitespace().count();
+ assert!(
+ word_count <= 80,
+ "MemoryWriteSection is too long ({word_count} words, ceiling 80)"
+ );
+}
+
+#[test]
+fn write_tool_gate_needs_a_registered_and_visible_tool() {
+ let tools = named(&["shell", "memory_store"]);
+ let none: Vec<Box<dyn Tool>> = Vec::new();
+ // Registered, no filter (empty visible set = wildcard): offered.
+ assert!(any_tool_offered(
+ &MEMORY_WRITE_TOOLS,
+ &tools,
+ &none,
+ &visible(&[])
+ ));
+ // Registered and allowed by the filter: offered.
+ assert!(any_tool_offered(
+ &MEMORY_WRITE_TOOLS,
+ &tools,
+ &none,
+ &visible(&["memory_store"])
+ ));
+ // Registered but filtered out by the agent's scope: not offered.
+ assert!(!any_tool_offered(
+ &MEMORY_WRITE_TOOLS,
+ &tools,
+ &none,
+ &visible(&["shell"])
+ ));
+ // Allowed by the filter but never registered on this agent: not offered.
+ assert!(!any_tool_offered(
+ &MEMORY_WRITE_TOOLS,
+ &named(&["shell"]),
+ &none,
+ &visible(&["memory_store", "save_preference"])
+ ));
+}
+
+#[test]
+fn write_tool_gate_counts_delegation_tools_and_either_write_tool() {
+ let none: Vec<Box<dyn Tool>> = Vec::new();
+ // A write tool synthesised on the delegation side counts the same.
+ assert!(any_tool_offered(
+ &MEMORY_WRITE_TOOLS,
+ &none,
+ &named(&["save_preference"]),
+ &visible(&[])
+ ));
+ // The read-side list is disjoint: a session with only retrieval tools gets
+ // no write rule, and a session with only write tools gets no read rule.
+ let readers = named(&["memory_recall"]);
+ assert!(any_tool_offered(
+ &MEMORY_READ_TOOLS,
+ &readers,
+ &none,
+ &visible(&[])
+ ));
+ assert!(!any_tool_offered(
+ &MEMORY_WRITE_TOOLS,
+ &readers,
+ &none,
+ &visible(&[])
+ ));
+}
diff --git a/src/openhuman/memory/tools/store.rs b/src/openhuman/memory/tools/store.rs
index 0fa1e947d2..53ddd08a59 100644
--- a/src/openhuman/memory/tools/store.rs
+++ b/src/openhuman/memory/tools/store.rs
@@ -1,3 +1,4 @@
+use crate::openhuman::agent::tinyagents::host::agent_memory::DEFAULT_AGENT_MEMORY_NAMESPACE;
use crate::openhuman::memory::api::provider::MemoryCore;
use crate::openhuman::memory::api::types::{MemoryCategory, MemoryTaint};
use crate::openhuman::memory::ops::guard::active_memory_guard;
@@ -22,6 +23,68 @@ impl MemoryStoreTool {
}
}
+/// Words of the content a derived key is built from.
+const DERIVED_KEY_WORDS: usize = 6;
+
+/// Longest stem a derived key carries before its hash suffix.
+const DERIVED_KEY_STEM_CHARS: usize = 48;
+
+/// The namespace to write to: the caller's, or the assistant's own scope.
+///
+/// Absent means the default scope — the one `memory_recall` reads back from —
+/// so a one-line "remember X" needs no namespace at all (#6048). A value that
+/// is present but not a string is a caller mistake, not a request for the
+/// default: a `null` or a number must not silently widen the write. An explicit
+/// empty string is left for the caller to report, never defaulted.
+fn resolve_namespace(args: &serde_json::Value) -> anyhow::Result<String> {
+ match args.get("namespace") {
+ None => Ok(DEFAULT_AGENT_MEMORY_NAMESPACE.to_string()),
+ Some(serde_json::Value::String(namespace)) => Ok(namespace.trim().to_string()),
+ Some(other) => anyhow::bail!("'namespace' must be a string, got {other}"),
+ }
+}
+
+/// The key to file under: the caller's, or one derived from the content.
+///
+/// The model should not have to invent a key to honour "remember X". A derived
+/// key is deterministic for the same content, so re-saving the same sentence
+/// overwrites rather than duplicating, while different content lands under a
+/// different key. A present-but-non-string key is a caller mistake.
+fn resolve_key(args: &serde_json::Value, content: &str) -> anyhow::Result<String> {
+ match args.get("key") {
+ None => Ok(derive_key(content)),
+ Some(serde_json::Value::String(key)) => Ok(key.trim().to_string()),
+ Some(other) => anyhow::bail!("'key' must be a string, got {other}"),
+ }
+}
+
+/// A stable, readable key for `content`: its first few words as a snake_case
+/// stem, plus a short hash of the whole text so two notes that open the same
+/// way do not overwrite each other.
+fn derive_key(content: &str) -> String {
+ let stem = content
+ .split(|c: char| !c.is_alphanumeric())
+ .filter(|word| !word.is_empty())
+ .take(DERIVED_KEY_WORDS)
+ .map(str::to_lowercase)
+ .collect::<Vec<_>>()
+ .join("_");
+ let stem: String = if stem.is_empty() {
+ "note".to_string()
+ } else {
+ stem.chars().take(DERIVED_KEY_STEM_CHARS).collect()
+ };
+ format!("{stem}_{:06x}", fnv1a_32(content.trim()) & 0x00ff_ffff)
+}
+
+/// FNV-1a over the bytes — stable across builds and platforms, unlike
+/// `DefaultHasher`, so a derived key never changes under the caller.
+fn fnv1a_32(text: &str) -> u32 {
+ text.bytes().fold(0x811c_9dc5_u32, |hash, byte| {
+ (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193)
+ })
+}
+
#[async_trait]
impl Tool for MemoryStoreTool {
fn name(&self) -> &str {
@@ -29,48 +92,41 @@ impl Tool for MemoryStoreTool {
}
fn description(&self) -> &str {
- "Store a general fact or note in an explicit namespace (e.g. global, background, autocomplete, skill-{id}). NOT for preferences — those go to `save_preference`, which writes the store the assistant actually reads. Check `memory_recall` for a near-duplicate first, and call `update_memory_md` afterwards, when you have those tools."
+ "Remember a fact, event, plan, or note the user asks you to keep — e.g. \"next scrum meeting on 10 September\". Call it BEFORE you confirm, whenever the user says remember, note, or keep in mind. NOT for preferences — those go to `save_preference`, which writes the store the assistant actually reads. `namespace` and `key` are optional: the default namespace is the assistant's own memory and the key is derived from the content. Check `memory_recall` for a near-duplicate first, and call `update_memory_md` afterwards, when you have those tools."
}
fn parameters_schema(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
- "key": {
+ "content": {
"type": "string",
- "description": "Unique key for this memory (e.g. 'user_lang', 'project_stack')"
+ "description": "The information to remember, in plain language"
},
- "namespace": {
+ "key": {
"type": "string",
- "description": "Target namespace (e.g. 'global', 'background', 'autocomplete', or 'skill-{id}')"
+ "description": "Optional short snake_case slug (e.g. 'next_scrum_meeting'); derived from the content when absent. Re-using a key overwrites."
},
- "content": {
+ "namespace": {
"type": "string",
- "description": "The information to remember"
+ "description": "Optional. Defaults to the assistant's own memory ('global'); name one only for a skill-scoped note ('skill-{id}')."
},
"category": {
"type": "string",
"description": "Memory category: 'core' (permanent), 'daily' (session), 'conversation' (chat), or a custom category name. Defaults to 'core'."
}
},
- "required": ["namespace", "key", "content"]
+ "required": ["content"]
})
}
async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let namespace = args
- .get("namespace")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing 'namespace' parameter"))?;
- let key = args
- .get("key")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing 'key' parameter"))?;
-
let content = args
.get("content")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing 'content' parameter"))?;
+ let namespace = resolve_namespace(&args)?;
+ let key = resolve_key(&args, content)?;
let category = match args.get("category").and_then(|v| v.as_str()) {
Some("core") | None => MemoryCategory::Core,
@@ -95,11 +151,9 @@ impl Tool for MemoryStoreTool {
return Ok(ToolResult::error(error));
}
- let namespace = namespace.trim();
if namespace.is_empty() {
return Ok(ToolResult::error("namespace cannot be empty".to_string()));
}
- let key = key.trim();
if key.is_empty() {
return Ok(ToolResult::error("key cannot be empty".to_string()));
}
@@ -122,8 +176,8 @@ impl Tool for MemoryStoreTool {
.map_err(|e| anyhow::anyhow!("memory_store: {e}"))?;
match guard
.store(
- namespace,
- key,
+ &namespace,
+ &key,
content,
category,
None,
diff --git a/src/openhuman/memory/tools/store_tests.rs b/src/openhuman/memory/tools/store_tests.rs
index b02e748da5..f7cb3f9796 100644
--- a/src/openhuman/memory/tools/store_tests.rs
+++ b/src/openhuman/memory/tools/store_tests.rs
@@ -152,10 +152,17 @@ async fn store_rejects_secret_like_content() {
#[tokio::test]
#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \
the tool resolves the bound driver rather than being handed a memory handle"]
-async fn store_missing_key() {
+async fn store_without_key_files_under_a_derived_key() {
+ // "remember X" carries no key; the tool derives one instead of refusing
+ // (#6048), and files under the default scope `memory_recall` reads back.
let tool = MemoryStoreTool::new(test_security());
- let result = tool.execute(json!({"content": "no key"})).await;
- assert!(result.is_err());
+ let result = tool.execute(json!({"content": "no key"})).await.unwrap();
+ assert!(!result.is_error, "{}", result.output());
+ assert!(
+ stored(DEFAULT_AGENT_MEMORY_NAMESPACE, &derive_key("no key"))
+ .await
+ .is_some()
+ );
}
#[tokio::test]
@@ -204,3 +211,106 @@ async fn store_blocked_when_rate_limited() {
assert!(result.output().contains("Rate limit exceeded"));
assert!(stored("global", "ratelimited_lang").await.is_none());
}
+
+// ── Argument resolution (#6048) — pure, no store needed ──────────────────────
+
+/// Only the content is required: a one-line "remember X" must not send the
+/// model off to invent a namespace and a key first.
+#[test]
+fn schema_requires_only_the_content() {
+ let schema = MemoryStoreTool::new(test_security()).parameters_schema();
+ assert_eq!(schema["required"], json!(["content"]));
+ assert!(schema["properties"]["namespace"].is_object());
+ assert!(schema["properties"]["key"].is_object());
+}
+
+#[test]
+fn resolve_namespace_defaults_when_absent() {
+ let namespace = resolve_namespace(&json!({"content": "x"})).unwrap();
+ assert_eq!(namespace, DEFAULT_AGENT_MEMORY_NAMESPACE);
+}
+
+#[test]
+fn resolve_namespace_keeps_an_explicit_one_trimmed() {
+ let namespace =
+ resolve_namespace(&json!({"namespace": " skill-gmail ", "content": "x"})).unwrap();
+ assert_eq!(namespace, "skill-gmail");
+}
+
+#[test]
+fn resolve_namespace_leaves_an_explicit_empty_one_for_the_caller_to_refuse() {
+ // Empty is not "absent": the caller reports it rather than widening the
+ // write to the default scope behind the model's back.
+ let namespace = resolve_namespace(&json!({"namespace": " ", "content": "x"})).unwrap();
+ assert!(namespace.is_empty());
+}
+
+#[test]
+fn resolve_namespace_rejects_a_non_string_namespace() {
+ assert!(resolve_namespace(&json!({"namespace": null, "content": "x"})).is_err());
+ assert!(resolve_namespace(&json!({"namespace": 7, "content": "x"})).is_err());
+ assert!(resolve_namespace(&json!({"namespace": ["a"], "content": "x"})).is_err());
+}
+
+#[test]
+fn resolve_key_keeps_an_explicit_one_trimmed() {
+ let key = resolve_key(&json!({"key": " next_scrum ", "content": "x"}), "x").unwrap();
+ assert_eq!(key, "next_scrum");
+}
+
+#[test]
+fn resolve_key_rejects_a_non_string_key() {
+ assert!(resolve_key(&json!({"key": null, "content": "x"}), "x").is_err());
+ assert!(resolve_key(&json!({"key": 3, "content": "x"}), "x").is_err());
+}
+
+#[test]
+fn resolve_key_derives_one_from_the_content_when_absent() {
+ let content = "Next scrum meeting is on 10 September, 10am.";
+ let key = resolve_key(&json!({"content": content}), content).unwrap();
+ assert_eq!(key, derive_key(content));
+ // Readable stem from the first words, then a short hash of the whole text.
+ assert!(
+ key.starts_with("next_scrum_meeting_is_on_10_"),
+ "stem must come from the content's first words: {key}"
+ );
+ let suffix = key.rsplit('_').next().unwrap();
+ assert_eq!(suffix.len(), 6, "six hex digits of hash: {key}");
+ assert!(suffix.chars().all(|c| c.is_ascii_hexdigit()), "{key}");
+}
+
+#[test]
+fn derive_key_is_deterministic_and_content_sensitive() {
+ let a = "next scrum meeting on 10 september";
+ assert_eq!(
+ derive_key(a),
+ derive_key(a),
+ "re-saving must overwrite, not duplicate"
+ );
+ assert_ne!(
+ derive_key(a),
+ derive_key("next scrum meeting on 17 september"),
+ "a different fact must not overwrite the first"
+ );
+ // Same opening words, different tail: the hash keeps them apart.
+ assert_ne!(
+ derive_key("the meeting with sam is about the budget"),
+ derive_key("the meeting with sam is about the roadmap")
+ );
+ // Whitespace around the text is not part of the identity.
+ assert_eq!(derive_key(a), derive_key(&format!(" {a}\n")));
+}
+
+#[test]
+fn derive_key_falls_back_when_the_content_has_no_words() {
+ let key = derive_key("!!! ???");
+ assert!(key.starts_with("note_"), "{key}");
+}
+
+#[test]
+fn derive_key_caps_the_stem() {
+ let content = "a".repeat(200);
+ let key = derive_key(&content);
+ let stem = key.rsplit_once('_').map(|(stem, _)| stem).unwrap();
+ assert_eq!(stem.chars().count(), DERIVED_KEY_STEM_CHARS);
+}