Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 86 additions & 20 deletions llm-tool-runtime/src/tool_observation_store.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,35 @@
//! Durable `ToolObservationMemory` implementation backed by `semantic-memory`.
//!
//! `llm-tool-runtime` previously defined the trait but shipped only
//! `InMemoryToolObservationMemory` (and the trait module was not even wired
//! into the crate root). This module provides the durable store-backed impl.
//! Search results are candidates only. Each candidate is re-read by its canonical
//! fact ID and returned only when its owner-stored source and versioned metadata
//! identify it as a tool observation. Search is approximate: the candidate limit
//! applies before filtering, so fewer than `limit` observations may be returned.

use crate::semantic_memory::{
ToolObservationDerivedCandidateTraceV1, ToolObservationMemory, ToolObservationMemoryRecordV1,
ToolObservationMemorySearchV1,
};
use crate::{ToolError, ToolErrorClass};
use async_trait::async_trait;
use semantic_memory::MemoryStore;
use semantic_memory::{MemoryStore, SearchSource, SearchSourceType};
use serde::Deserialize;

/// Fixed source label stamped onto stored tool observations.
const OBSERVATION_SOURCE: &str = "llm-tool-runtime";
const OBSERVATION_KIND: &str = "tool_observation_v1";

/// Metadata persisted alongside the fact content by this adapter.
#[derive(Debug, Deserialize)]
struct StoredToolObservationMetadataV1 {
kind: String,
tool_name: String,
invocation_id: String,
session_id: Option<String>,
status: String,
started_at: Option<String>,
completed_at: Option<String>,
receipt_id: Option<String>,
}

#[async_trait]
impl ToolObservationMemory for MemoryStore {
Expand All @@ -22,7 +38,7 @@ impl ToolObservationMemory for MemoryStore {
record: ToolObservationMemoryRecordV1,
) -> Result<(), ToolError> {
let metadata = serde_json::json!({
"kind": "tool_observation_v1",
"kind": OBSERVATION_KIND,
"tool_name": record.tool_name,
"invocation_id": record.invocation_id,
"session_id": record.session_id,
Expand Down Expand Up @@ -59,30 +75,80 @@ impl ToolObservationMemory for MemoryStore {
"limit must be greater than zero for tool observation search",
));
}

let namespaces = [scope];
let source_types = [SearchSourceType::Facts];
let results = self
.search(query, Some(limit), Some(&namespaces), None)
.search(query, Some(limit), Some(&namespaces), Some(&source_types))
.await
.map_err(|e| {
ToolError::new(
ToolErrorClass::ProviderContract,
format!("semantic-memory search failed: {e}"),
)
})?;
let observations = results
.into_iter()
.map(|r| ToolObservationMemoryRecordV1 {
tool_name: String::new(),
invocation_id: String::new(),
session_id: None,
scope: scope.to_string(),
summary: r.content,
status: String::new(),
started_at: None,
completed_at: None,
receipt_id: None,
})
.collect();

let mut observations = Vec::with_capacity(limit.min(results.len()));
for result in results {
let SearchSource::Fact { fact_id, namespace } = result.source else {
continue;
};
if namespace != scope {
continue;
}

// The search index is a derived candidate source; fetch the canonical
// fact so metadata and source are not fabricated from search text.
let fact = self.get_fact(&fact_id).await.map_err(|e| {
ToolError::new(
ToolErrorClass::ProviderContract,
format!("semantic-memory fact read failed: {e}"),
)
})?;
let Some(fact) = fact else {
// A concurrent delete can invalidate an index candidate.
continue;
};
if fact.namespace != scope || fact.source.as_deref() != Some(OBSERVATION_SOURCE) {
continue;
}

let Some(metadata) = fact.metadata else {
return Err(ToolError::new(
ToolErrorClass::ProviderContract,
format!("tool observation fact {fact_id} is missing metadata"),
));
};
if metadata.get("kind").and_then(serde_json::Value::as_str) != Some(OBSERVATION_KIND) {
continue;
}
let stored: StoredToolObservationMetadataV1 = serde_json::from_value(metadata)
.map_err(|e| {
ToolError::new(
ToolErrorClass::ProviderContract,
format!("tool observation fact {fact_id} has invalid metadata: {e}"),
)
})?;
if stored.kind != OBSERVATION_KIND {
continue;
}

observations.push(ToolObservationMemoryRecordV1 {
tool_name: stored.tool_name,
invocation_id: stored.invocation_id,
session_id: stored.session_id,
scope: fact.namespace,
summary: fact.content,
status: stored.status,
started_at: stored.started_at,
completed_at: stored.completed_at,
receipt_id: stored.receipt_id,
});
if observations.len() == limit {
break;
}
}

Ok(ToolObservationMemorySearchV1 {
observations,
derived_candidate_receipts: Vec::<ToolObservationDerivedCandidateTraceV1>::new(),
Expand Down
60 changes: 58 additions & 2 deletions llm-tool-runtime/tests/tool_observation_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ fn record(scope: &str, summary: &str) -> ToolObservationMemoryRecordV1 {
scope: scope.to_string(),
summary: summary.to_string(),
status: "succeeded".to_string(),
started_at: None,
completed_at: None,
started_at: Some("2026-11-25T12:00:00Z".to_string()),
completed_at: Some("2026-11-25T12:00:03Z".to_string()),
receipt_id: Some("rcpt-1".to_string()),
}
}
Expand Down Expand Up @@ -47,6 +47,20 @@ async fn store_and_find_roundtrip_with_scope_isolation() {
"expected one observation in scope-a"
);
assert!(found.observations[0].summary.contains("cargo build"));
assert_eq!(found.observations[0].tool_name, "cargo");
assert_eq!(found.observations[0].invocation_id, "inv-1");
assert_eq!(found.observations[0].session_id.as_deref(), Some("sess-1"));
assert_eq!(found.observations[0].status, "succeeded");
assert_eq!(
found.observations[0].started_at.as_deref(),
Some("2026-11-25T12:00:00Z")
);
assert_eq!(
found.observations[0].completed_at.as_deref(),
Some("2026-11-25T12:00:03Z")
);
assert_eq!(found.observations[0].receipt_id.as_deref(), Some("rcpt-1"));
assert_eq!(found.observations[0].scope, "scope-a");

let other = store
.find_similar_tool_observations("cargo build", "scope-b", 5)
Expand All @@ -55,6 +69,48 @@ async fn store_and_find_roundtrip_with_scope_isolation() {
assert_eq!(other.observations.len(), 0, "scope-b must be isolated");
}

#[tokio::test]
async fn ordinary_facts_in_the_same_scope_are_not_tool_observations() {
let dir = tempfile::tempdir().unwrap();
let cfg = MemoryConfig {
base_dir: dir.path().join("mem"),
..Default::default()
};
let dims = cfg.embedding.dimensions;
let store = MemoryStore::open_with_embedder(cfg, Box::new(MockEmbedder::new(dims))).unwrap();

store
.add_fact(
"scope-a",
"cargo build command is documented in the handbook",
Some("handbook"),
None,
)
.await
.unwrap();
store
.add_fact(
"scope-a",
"cargo build is mentioned by a non-observation runtime record",
Some("llm-tool-runtime"),
Some(serde_json::json!({"kind": "other_runtime_record_v1"})),
)
.await
.unwrap();
store
.store_tool_observation(record("scope-a", "ran cargo build successfully"))
.await
.unwrap();

let found = store
.find_similar_tool_observations("cargo build", "scope-a", 10)
.await
.unwrap();
assert_eq!(found.observations.len(), 1);
assert_eq!(found.observations[0].tool_name, "cargo");
assert_eq!(found.observations[0].invocation_id, "inv-1");
}

#[tokio::test]
async fn zero_limit_is_rejected() {
let dir = tempfile::tempdir().unwrap();
Expand Down
Loading