Skip to content

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

fix(memory): name only the write tools a session holds, widen the derived key

Shanucda5c95a3978
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 66756f0e9c..299c35092d 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
@@ -691,3 +691,40 @@ async fn memory_write_instruction_is_absent_when_no_write_tool_is_visible() {
"a rule about tools the model cannot see would only teach it to apologise"
);
}
+
+/// The live case both reviewers pointed at: `archivist`'s `[tools] named`
+/// scope carries `memory_store` but not `save_preference` (so do
+/// `trigger_reactor` and `workflow_builder`). Naming both routes there would
+/// mandate a tool the session cannot call — the failure the visibility gate
+/// exists to prevent.
+#[tokio::test]
+async fn memory_write_instruction_names_only_the_write_tool_a_scoped_agent_holds() {
+ 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 archivist = builtin_def("archivist");
+ let agent =
+ Agent::build_session_agent_inner(&config, "archivist", Some(&archivist), None, false, None)
+ .expect("build archivist session");
+
+ let prompt = agent
+ .build_system_prompt(LearnedContextData::default())
+ .expect("build_system_prompt");
+ let block = prompt
+ .split("## Remembering")
+ .nth(1)
+ .expect("the archivist offers memory_store, so the write rule must be present");
+ // Read only this section: other sections may mention other tools.
+ let block = block.split("\n## ").next().unwrap_or(block);
+ assert!(
+ block.contains("`memory_store`"),
+ "the offered write tool must be named: {block}"
+ );
+ assert!(
+ !block.contains("`save_preference`"),
+ "a scope without save_preference must not be routed to it: {block}"
+ );
+}
diff --git a/src/openhuman/agent/harness/session/builder/helpers.rs b/src/openhuman/agent/harness/session/builder/helpers.rs
index 046dd3c865..f8321001d5 100644
--- a/src/openhuman/agent/harness/session/builder/helpers.rs
+++ b/src/openhuman/agent/harness/session/builder/helpers.rs
@@ -100,7 +100,7 @@ pub(super) fn add_memory_prompt_sections(
) -> SystemPromptBuilder {
use crate::openhuman::agent::learning::{
any_tool_offered, MemoryAccessSection, MemoryWriteSection, MEMORY_READ_TOOLS,
- MEMORY_WRITE_TOOLS,
+ MEMORY_STORE_TOOL, SAVE_PREFERENCE_TOOL,
};
let mut prompt_builder = prompt_builder;
if config.learning.enabled {
@@ -114,9 +114,18 @@ pub(super) fn add_memory_prompt_sections(
);
}
}
- 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}");
+ // Asked per tool, not once for the pair: the section names the routes it
+ // is given, so a profile carrying only one write tool must not be told
+ // about the other (review finding).
+ let preferences = any_tool_offered(&[SAVE_PREFERENCE_TOOL], tools, delegation_tools, visible);
+ let facts = any_tool_offered(&[MEMORY_STORE_TOOL], tools, delegation_tools, visible);
+ if preferences || facts {
+ prompt_builder =
+ prompt_builder.add_section(Box::new(MemoryWriteSection::new(preferences, facts)));
+ log::debug!(
+ "[memory_write] prompt section registered for agent={agent_id} \
+ save_preference={preferences} memory_store={facts}"
+ );
} else {
log::debug!(
"[memory_write] skipping MemoryWriteSection — neither memory_store nor \
diff --git a/src/openhuman/agent/learning/mod.rs b/src/openhuman/agent/learning/mod.rs
index 8c929f103f..36a15ecbc7 100644
--- a/src/openhuman/agent/learning/mod.rs
+++ b/src/openhuman/agent/learning/mod.rs
@@ -46,9 +46,9 @@ pub use cache::FacetCache;
pub use candidate::{Buffer, CueFamily, EvidenceRef, FacetClass, LearningCandidate};
pub use profile_md_renderer::ProfileMdRenderer;
pub use prompt_sections::{
- any_tool_offered, load_learned_from_cache, LearnedContextSection, MemoryAccessSection,
- MemoryWriteSection, UserProfileSection, MEMORY_ACCESS_INSTRUCTION, MEMORY_READ_TOOLS,
- MEMORY_WRITE_INSTRUCTION, MEMORY_WRITE_TOOLS,
+ any_tool_offered, load_learned_from_cache, memory_write_instruction, LearnedContextSection,
+ MemoryAccessSection, MemoryWriteSection, UserProfileSection, MEMORY_ACCESS_INSTRUCTION,
+ MEMORY_READ_TOOLS, MEMORY_STORE_TOOL, MEMORY_WRITE_TOOLS, SAVE_PREFERENCE_TOOL,
};
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 873828e20e..086a00fbfd 100644
--- a/src/openhuman/agent/learning/prompt_sections.rs
+++ b/src/openhuman/agent/learning/prompt_sections.rs
@@ -133,25 +133,53 @@ impl PromptSection for MemoryAccessSection {
// ── MemoryWriteSection ────────────────────────────────────────────────────────
-/// Static instruction that turns "remember this" into a write before the reply.
+/// 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.";
+/// made and the next chat had nothing to find (#6048).
+///
+/// It names only the routes this session actually holds. Naming both
+/// unconditionally would point a profile that carries just one of them at a
+/// tool it cannot see — the failure [`any_tool_offered`] exists to prevent
+/// (review finding).
+pub struct MemoryWriteSection {
+ preferences: bool,
+ facts: bool,
+}
+
+impl MemoryWriteSection {
+ /// `preferences` = `save_preference` is offered here, `facts` =
+ /// `memory_store` is.
+ #[must_use]
+ pub fn new(preferences: bool, facts: bool) -> Self {
+ Self { preferences, facts }
+ }
+}
+
+/// The instruction for a session offering `save_preference` (`preferences`)
+/// and/or `memory_store` (`facts`).
+///
+/// Kept at ≤ 80 words in every variant (the composition test pins the ceiling).
+/// Empty when neither tool is offered — which is also when nothing registers
+/// the section, so the empty string is a guard, not a path in normal use.
+#[must_use]
+pub fn memory_write_instruction(preferences: bool, facts: bool) -> String {
+ let route = match (preferences, facts) {
+ (true, true) => "— `save_preference` for preferences, `memory_store` for everything else",
+ (true, false) => "with `save_preference`",
+ (false, true) => "with `memory_store`",
+ (false, false) => return String::new(),
+ };
+ format!(
+ "## 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 \
+ {route}. 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 {
@@ -159,15 +187,21 @@ impl PromptSection for MemoryWriteSection {
}
fn build(&self, _ctx: &PromptContext<'_>) -> Result<String> {
- Ok(MEMORY_WRITE_INSTRUCTION.to_string())
+ Ok(memory_write_instruction(self.preferences, self.facts))
}
}
/// The retrieval tools [`MemoryAccessSection`] is keyed on.
pub const MEMORY_READ_TOOLS: [&str; 2] = ["memory_recall", "memory_search"];
+/// The tool a preference is written through.
+pub const SAVE_PREFERENCE_TOOL: &str = "save_preference";
+
+/// The tool every other remembered fact is written through.
+pub const MEMORY_STORE_TOOL: &str = "memory_store";
+
/// The writing tools [`MemoryWriteSection`] is keyed on.
-pub const MEMORY_WRITE_TOOLS: [&str; 2] = ["memory_store", "save_preference"];
+pub const MEMORY_WRITE_TOOLS: [&str; 2] = [MEMORY_STORE_TOOL, SAVE_PREFERENCE_TOOL];
/// Whether any of `names` is registered on this session **and** survives tool
/// filtering.
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 801e4b480e..769001c38f 100644
--- a/src/openhuman/agent/learning/prompt_sections_tests_2_tests.rs
+++ b/src/openhuman/agent/learning/prompt_sections_tests_2_tests.rs
@@ -331,26 +331,75 @@ fn visible(names: &[&str]) -> HashSet<String> {
}
#[test]
-fn memory_write_section_renders_the_frozen_instruction() {
- let section = MemoryWriteSection;
+fn memory_write_section_states_the_rule_the_bug_needed() {
+ let section = MemoryWriteSection::new(true, true);
assert_eq!(section.name(), "memory_write");
let rendered = section
.build(&prompt_context(LearnedContextData::default()))
.unwrap();
- assert_eq!(rendered.trim(), MEMORY_WRITE_INSTRUCTION.trim());
+ assert_eq!(rendered.trim(), memory_write_instruction(true, true).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();
+ // Not context-gated: it renders for an empty learned context too.
+ let empty = MemoryWriteSection::new(true, true)
+ .build(&prompt_context(LearnedContextData::default()))
+ .unwrap();
+ assert!(!empty.trim().is_empty());
+}
+
+/// The section names the routes it was given and no others. Telling a session
+/// that holds one write tool to call the other is the same class of mistake as
+/// registering the section with no write tool at all.
+#[test]
+fn memory_write_instruction_names_only_the_offered_tools() {
+ let both = memory_write_instruction(true, true);
+ assert!(
+ both.contains("`save_preference`") && both.contains("`memory_store`"),
+ "{both}"
+ );
+
+ let preferences_only = memory_write_instruction(true, false);
+ assert!(
+ preferences_only.contains("`save_preference`"),
+ "{preferences_only}"
+ );
assert!(
- word_count <= 80,
- "MemoryWriteSection is too long ({word_count} words, ceiling 80)"
+ !preferences_only.contains("`memory_store`"),
+ "a session without memory_store must not be sent to it: {preferences_only}"
);
+
+ let facts_only = memory_write_instruction(false, true);
+ assert!(facts_only.contains("`memory_store`"), "{facts_only}");
+ assert!(
+ !facts_only.contains("`save_preference`"),
+ "a session without save_preference must not be sent to it: {facts_only}"
+ );
+
+ // Every variant still carries the heading, the rule, and the word ceiling.
+ for rendered in [&both, &preferences_only, &facts_only] {
+ assert!(rendered.contains("## Remembering"), "{rendered}");
+ assert!(rendered.contains("Never say saved"), "{rendered}");
+ let words = rendered.split_whitespace().count();
+ assert!(
+ words <= 80,
+ "instruction is too long ({words} words): {rendered}"
+ );
+ }
+}
+
+/// Neither tool offered renders nothing — the guard behind the gate, so a
+/// future caller that registers the section unconditionally still cannot name
+/// a tool the session lacks.
+#[test]
+fn memory_write_instruction_is_empty_without_a_write_tool() {
+ assert!(memory_write_instruction(false, false).is_empty());
+ let rendered = MemoryWriteSection::new(false, false)
+ .build(&prompt_context(LearnedContextData::default()))
+ .unwrap();
+ assert!(rendered.is_empty(), "{rendered}");
}
#[test]
diff --git a/src/openhuman/memory/tools/store.rs b/src/openhuman/memory/tools/store.rs
index 53ddd08a59..85e6ca150b 100644
--- a/src/openhuman/memory/tools/store.rs
+++ b/src/openhuman/memory/tools/store.rs
@@ -8,6 +8,7 @@ use crate::openhuman::security::SecurityPolicy;
use crate::openhuman::tools::traits::{Tool, ToolResult};
use async_trait::async_trait;
use serde_json::json;
+use sha2::{Digest, Sha256};
use std::sync::Arc;
/// Let the agent store memories — its own brain writes
@@ -29,6 +30,15 @@ const DERIVED_KEY_WORDS: usize = 6;
/// Longest stem a derived key carries before its hash suffix.
const DERIVED_KEY_STEM_CHARS: usize = 48;
+/// Hex characters of digest a derived key carries — 16 hex, so 64 bits.
+///
+/// The stem collides constantly by design (a mailbox of "meeting with …"
+/// notes opens the same way), so the suffix is the whole of what keeps two
+/// facts apart, and a collision does not merely duplicate — it overwrites an
+/// unrelated memory under the same key. 24 bits made that likely within a few
+/// thousand notes (review finding); 64 keeps it out of reach.
+const DERIVED_KEY_HASH_CHARS: usize = 16;
+
/// 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 —
@@ -59,8 +69,12 @@ fn resolve_key(args: &serde_json::Value, content: &str) -> anyhow::Result<String
}
/// 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.
+/// stem, plus a digest of the whole text so two notes that open the same way
+/// do not overwrite each other.
+///
+/// SHA-256 rather than a cheap non-cryptographic hash: the input is user text,
+/// the cost is irrelevant beside the write it precedes, and the same digest ->
+/// same key property is what makes re-saving a sentence idempotent.
fn derive_key(content: &str) -> String {
let stem = content
.split(|c: char| !c.is_alphanumeric())
@@ -74,15 +88,8 @@ fn derive_key(content: &str) -> 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)
- })
+ let digest = hex::encode(Sha256::digest(content.trim().as_bytes()));
+ format!("{stem}_{}", &digest[..DERIVED_KEY_HASH_CHARS])
}
#[async_trait]
diff --git a/src/openhuman/memory/tools/store_tests.rs b/src/openhuman/memory/tools/store_tests.rs
index f7cb3f9796..9f0bd203e7 100644
--- a/src/openhuman/memory/tools/store_tests.rs
+++ b/src/openhuman/memory/tools/store_tests.rs
@@ -275,7 +275,11 @@ fn resolve_key_derives_one_from_the_content_when_absent() {
"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_eq!(
+ suffix.len(),
+ DERIVED_KEY_HASH_CHARS,
+ "the digest suffix is what keeps two notes with the same opening words apart: {key}"
+ );
assert!(suffix.chars().all(|c| c.is_ascii_hexdigit()), "{key}");
}
@@ -314,3 +318,23 @@ fn derive_key_caps_the_stem() {
let stem = key.rsplit_once('_').map(|(stem, _)| stem).unwrap();
assert_eq!(stem.chars().count(), DERIVED_KEY_STEM_CHARS);
}
+
+/// A shared stem is the normal case, so the suffix carries the whole burden of
+/// telling two notes apart — at 24 bits that failed within a few thousand
+/// writes, and the loser was silently overwritten (review finding).
+#[test]
+fn derive_key_suffix_is_wide_enough_to_separate_a_shared_stem() {
+ assert!(
+ DERIVED_KEY_HASH_CHARS >= 16,
+ "a derived key needs at least 64 bits of digest"
+ );
+ let a = derive_key("the meeting with sam is about the budget for next quarter");
+ let b = derive_key("the meeting with sam is about the roadmap for next quarter");
+ let stem = |key: &str| key.rsplit_once('_').map(|(s, _)| s.to_string()).unwrap();
+ assert_eq!(
+ stem(&a),
+ stem(&b),
+ "the fixture must share a stem to be meaningful"
+ );
+ assert_ne!(a, b, "a shared stem must still yield distinct keys");
+}