diff --git a/Cargo.lock b/Cargo.lock index 6a22b059..b2437731 100755 --- a/Cargo.lock +++ b/Cargo.lock @@ -3871,6 +3871,7 @@ dependencies = [ name = "knowledge-runtime" version = "0.1.0" dependencies = [ + "bitemporal-runtime", "chrono", "constraint-compiler", "forge-memory-bridge", @@ -4091,10 +4092,12 @@ dependencies = [ "async-trait", "chrono", "schemars 0.8.22", + "semantic-memory", "semantic-memory-forge", "serde", "serde_json", "stack-ids", + "tempfile", "thiserror 2.0.20", "tokio", "tracing", diff --git a/knowledge-runtime/Cargo.toml b/knowledge-runtime/Cargo.toml index 8075b557..e70c0c88 100644 --- a/knowledge-runtime/Cargo.toml +++ b/knowledge-runtime/Cargo.toml @@ -13,6 +13,7 @@ documentation = "https://docs.rs/knowledge-runtime" doctest = false [dependencies] +bitemporal-runtime = { path = "../bitemporal-runtime" } constraint-compiler = { path = "../constraint-compiler" } forge-memory-bridge = { path = "../forge-memory-bridge" } kernel-execution = { path = "../kernel-execution" } diff --git a/knowledge-runtime/src/runtime/core.rs b/knowledge-runtime/src/runtime/core.rs index dc26d235..7e9dc157 100755 --- a/knowledge-runtime/src/runtime/core.rs +++ b/knowledge-runtime/src/runtime/core.rs @@ -167,6 +167,7 @@ pub struct KnowledgeRuntime { config: RuntimeConfig, entity_registry: EntityRegistry, projection_tracker: ProjectionTracker, + bitemporal_records: Vec>, } impl KnowledgeRuntime { @@ -189,9 +190,20 @@ impl KnowledgeRuntime { config, entity_registry, projection_tracker, + bitemporal_records: Vec::new(), }) } + /// Wire a bitemporal record source so the temporal route answers as-of + /// version selection from `bitemporal-runtime` (empty = existing behavior). + pub fn with_bitemporal_records( + mut self, + records: Vec>, + ) -> Self { + self.bitemporal_records = records; + self + } + pub(crate) fn adapter_ref(&self) -> &SemanticMemoryAdapter { &self.adapter } @@ -447,7 +459,35 @@ impl KnowledgeRuntime { trace.recorded_as_of = Some(recorded_at_or_before.to_string()); trace.temporal_mode = Some(temporal_mode.to_string()); - let results = merged.results.into_iter().map(|m| m.result).collect(); + let mut results: Vec = merged.results.into_iter().map(|m| m.result).collect(); + if !self.bitemporal_records.is_empty() { + if let (Ok(v), Ok(r)) = ( + chrono::DateTime::parse_from_rfc3339(valid_at), + chrono::DateTime::parse_from_rfc3339(recorded_at_or_before), + ) { + let asof = crate::temporal::bitemporal_bridge::as_of( + &self.bitemporal_records, + v.with_timezone(&chrono::Utc), + r.with_timezone(&chrono::Utc), + ); + if !asof.is_empty() { + results = asof + .into_iter() + .map(|rec| SearchResult { + content: rec.value, + source: semantic_memory::SearchSource::Fact { + fact_id: rec.id, + namespace: scope.namespace.clone(), + }, + score: 1.0, + bm25_rank: None, + vector_rank: None, + cosine_similarity: None, + }) + .collect(); + } + } + } Ok((results, trace)) } diff --git a/knowledge-runtime/src/temporal/bitemporal_bridge.rs b/knowledge-runtime/src/temporal/bitemporal_bridge.rs new file mode 100644 index 00000000..8f1538f6 --- /dev/null +++ b/knowledge-runtime/src/temporal/bitemporal_bridge.rs @@ -0,0 +1,91 @@ +//! As-of temporal bridge over `bitemporal-runtime`. +//! +//! Scope: process-lifetime store injection only. Durable persistence is +//! evidence debt; callers must inject a store. +//! +//! Signatures mirror `bitemporal-runtime/src/queries.rs`: +//! - `as_of_query` -> `Vec>` +//! - `append_supersede` -> `Result, BitemporalError>` +//! - `temporal_snapshot(records, as_of_time)` -> `Vec>` + +use bitemporal_runtime::{ + append_supersede, as_of_query, temporal_snapshot, BitemporalError, BitemporalRecord, + SupersessionReceipt, +}; +use chrono::{DateTime, Utc}; + +/// Records visible as of `valid_time` and `recorded_time`. +pub fn as_of( + records: &[BitemporalRecord], + valid_time: DateTime, + recorded_time: DateTime, +) -> Vec> { + as_of_query(records, valid_time, recorded_time) +} + +/// Append a supersession; returns receipts for each superseded prior version. +pub fn supersede( + records: &mut Vec>, + new_record: BitemporalRecord, +) -> Result, BitemporalError> { + append_supersede(records, new_record) +} + +/// Full snapshot at a recorded time. +pub fn snapshot( + records: &[BitemporalRecord], + recorded_time: DateTime, +) -> Vec> { + temporal_snapshot(records, recorded_time) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::TimeZone; + + fn rec(id: &str, valid: i64, recorded: i64, value: &str) -> BitemporalRecord { + BitemporalRecord { + id: id.to_string(), + valid_time: Utc.timestamp_opt(valid, 0).unwrap(), + recorded_time: Utc.timestamp_opt(recorded, 0).unwrap(), + value: value.to_string(), + } + } + + #[test] + fn as_of_returns_version_valid_at_that_time() { + let r1 = rec("x", 100, 100, "old"); + let r2 = rec("x", 200, 200, "new"); + let records = vec![r1, r2]; + let at_150 = as_of( + &records, + Utc.timestamp_opt(150, 0).unwrap(), + Utc.timestamp_opt(250, 0).unwrap(), + ); + assert_eq!(at_150.len(), 1); + assert_eq!(at_150[0].value, "old"); + let at_250 = as_of( + &records, + Utc.timestamp_opt(250, 0).unwrap(), + Utc.timestamp_opt(250, 0).unwrap(), + ); + assert_eq!(at_250.len(), 1); + assert_eq!(at_250[0].value, "new"); + } + + #[test] + fn supersede_emits_receipt() { + let mut records = vec![rec("y", 100, 100, "v1")]; + let receipts = supersede(&mut records, rec("y", 200, 200, "v2")).unwrap(); + assert_eq!(receipts.len(), 1); + } + + #[test] + fn snapshot_reflects_latest_recorded() { + let records = vec![rec("z", 100, 100, "a"), rec("z", 150, 150, "b")]; + let snap = snapshot(&records, Utc.timestamp_opt(160, 0).unwrap()); + assert_eq!(snap.len(), 1); + assert_eq!(snap[0].value, "b"); + } +} diff --git a/knowledge-runtime/src/temporal/mod.rs b/knowledge-runtime/src/temporal/mod.rs index c0e708bb..aa1f5c0c 100755 --- a/knowledge-runtime/src/temporal/mod.rs +++ b/knowledge-runtime/src/temporal/mod.rs @@ -1 +1,2 @@ +pub mod bitemporal_bridge; pub mod claims; diff --git a/knowledge-runtime/tests/bitemporal_route.rs b/knowledge-runtime/tests/bitemporal_route.rs new file mode 100644 index 00000000..3d266d29 --- /dev/null +++ b/knowledge-runtime/tests/bitemporal_route.rs @@ -0,0 +1,83 @@ +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::field_reassign_with_default +)] +use bitemporal_runtime::BitemporalRecord; +use chrono::TimeZone; +use knowledge_runtime::adapters::semantic_memory::SemanticMemoryAdapter; +use knowledge_runtime::{KnowledgeRuntime, RuntimeConfig, Scope}; +use semantic_memory::{MemoryConfig, MemoryStore, MockEmbedder}; + +fn rec(id: &str, valid: i64, recorded: i64, v: &str) -> BitemporalRecord { + BitemporalRecord { + id: id.to_string(), + valid_time: chrono::Utc.timestamp_opt(valid, 0).unwrap(), + recorded_time: chrono::Utc.timestamp_opt(recorded, 0).unwrap(), + value: v.to_string(), + } +} + +fn runtime(dir: &std::path::Path, records: Vec>) -> KnowledgeRuntime { + let cfg = MemoryConfig { + base_dir: dir.join("mem"), + ..Default::default() + }; + let dims = cfg.embedding.dimensions; + let store = MemoryStore::open_with_embedder(cfg, Box::new(MockEmbedder::new(dims))).unwrap(); + let adapter = SemanticMemoryAdapter::new(store); + let config = RuntimeConfig { + default_scope: Scope::new("ns"), + query: Default::default(), + entity: Default::default(), + projection: Default::default(), + strict_temporal: false, + strict_scope: false, + }; + KnowledgeRuntime::new(config, adapter) + .unwrap() + .with_bitemporal_records(records) +} + +#[tokio::test] +async fn temporal_route_consumes_bitemporal_records() { + let dir = tempfile::tempdir().unwrap(); + let rt = runtime( + dir.path(), + vec![rec("x", 100, 100, "old"), rec("x", 200, 200, "new")], + ); + + // As of valid=150, recorded=250 -> only "old" was valid. + let (early, trace) = rt + .query_temporal_with_trace( + "what changed", + None, + None, + "1970-01-01T00:02:30Z", // 150s + "1970-01-01T00:04:10Z", // 250s + ) + .await + .expect("temporal query should succeed"); + assert!(!early.is_empty(), "expected a bitemporal result"); + assert_eq!( + early[0].content, "old", + "as-of must select the older version" + ); + assert!(trace.temporal_mode.as_deref().is_some()); + + // As of valid=250 -> "new". + let (late, _) = rt + .query_temporal_with_trace( + "what changed", + None, + None, + "1970-01-01T00:04:10Z", + "1970-01-01T00:04:10Z", + ) + .await + .expect("temporal query should succeed"); + assert_eq!( + late[0].content, "new", + "as-of must select the newer version" + ); +} diff --git a/llm-tool-runtime/Cargo.toml b/llm-tool-runtime/Cargo.toml index 3a9f4371..a086e06f 100755 --- a/llm-tool-runtime/Cargo.toml +++ b/llm-tool-runtime/Cargo.toml @@ -8,6 +8,7 @@ license = "MIT" readme = "README.md" [dependencies] +semantic-memory = { path = "../semantic-memory" } async-trait = { workspace = true } chrono = { workspace = true, features = ["serde"] } semantic-memory-forge = { path = "../semantic-memory-forge" } @@ -23,3 +24,7 @@ uuid = { workspace = true, features = ["v4"] } # LIB-005: inherit workspace lint policy [lints] workspace = true + +[dev-dependencies] +tempfile = { workspace = true } +tokio = { workspace = true, features = ["rt", "macros"] } diff --git a/llm-tool-runtime/src/lib.rs b/llm-tool-runtime/src/lib.rs index 2c8a0797..978b2527 100755 --- a/llm-tool-runtime/src/lib.rs +++ b/llm-tool-runtime/src/lib.rs @@ -4,6 +4,7 @@ pub mod registry; pub mod runtime; pub mod semantic_memory; pub mod starter_tools; +pub mod tool_observation_store; pub use contracts::*; pub use provider::*; diff --git a/llm-tool-runtime/src/tool_observation_store.rs b/llm-tool-runtime/src/tool_observation_store.rs new file mode 100644 index 00000000..84995e71 --- /dev/null +++ b/llm-tool-runtime/src/tool_observation_store.rs @@ -0,0 +1,91 @@ +//! 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. + +use crate::semantic_memory::{ + ToolObservationDerivedCandidateTraceV1, ToolObservationMemory, ToolObservationMemoryRecordV1, + ToolObservationMemorySearchV1, +}; +use crate::{ToolError, ToolErrorClass}; +use async_trait::async_trait; +use semantic_memory::MemoryStore; + +/// Fixed source label stamped onto stored tool observations. +const OBSERVATION_SOURCE: &str = "llm-tool-runtime"; + +#[async_trait] +impl ToolObservationMemory for MemoryStore { + async fn store_tool_observation( + &self, + record: ToolObservationMemoryRecordV1, + ) -> Result<(), ToolError> { + let metadata = serde_json::json!({ + "kind": "tool_observation_v1", + "tool_name": record.tool_name, + "invocation_id": record.invocation_id, + "session_id": record.session_id, + "status": record.status, + "started_at": record.started_at, + "completed_at": record.completed_at, + "receipt_id": record.receipt_id, + }); + self.add_fact( + &record.scope, + &record.summary, + Some(OBSERVATION_SOURCE), + Some(metadata), + ) + .await + .map(|_| ()) + .map_err(|e| { + ToolError::new( + ToolErrorClass::ProviderContract, + format!("semantic-memory store failed: {e}"), + ) + }) + } + + async fn find_similar_tool_observations( + &self, + query: &str, + scope: &str, + limit: usize, + ) -> Result { + if limit == 0 { + return Err(ToolError::new( + ToolErrorClass::ProviderContract, + "limit must be greater than zero for tool observation search", + )); + } + let namespaces = [scope]; + let results = self + .search(query, Some(limit), Some(&namespaces), None) + .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(); + Ok(ToolObservationMemorySearchV1 { + observations, + derived_candidate_receipts: Vec::::new(), + }) + } +} diff --git a/llm-tool-runtime/tests/tool_observation_store.rs b/llm-tool-runtime/tests/tool_observation_store.rs new file mode 100644 index 00000000..458629a3 --- /dev/null +++ b/llm-tool-runtime/tests/tool_observation_store.rs @@ -0,0 +1,72 @@ +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::field_reassign_with_default +)] +//! Durable ToolObservationMemory round-trip + scope isolation. + +use llm_tool_runtime::semantic_memory::{ToolObservationMemory, ToolObservationMemoryRecordV1}; +use semantic_memory::{MemoryConfig, MemoryStore, MockEmbedder}; + +fn record(scope: &str, summary: &str) -> ToolObservationMemoryRecordV1 { + ToolObservationMemoryRecordV1 { + tool_name: "cargo".to_string(), + invocation_id: "inv-1".to_string(), + session_id: Some("sess-1".to_string()), + scope: scope.to_string(), + summary: summary.to_string(), + status: "succeeded".to_string(), + started_at: None, + completed_at: None, + receipt_id: Some("rcpt-1".to_string()), + } +} + +#[tokio::test] +async fn store_and_find_roundtrip_with_scope_isolation() { + 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 + .store_tool_observation(record("scope-a", "ran cargo build successfully")) + .await + .unwrap(); + + let found = store + .find_similar_tool_observations("cargo build", "scope-a", 5) + .await + .unwrap(); + assert_eq!( + found.observations.len(), + 1, + "expected one observation in scope-a" + ); + assert!(found.observations[0].summary.contains("cargo build")); + + let other = store + .find_similar_tool_observations("cargo build", "scope-b", 5) + .await + .unwrap(); + assert_eq!(other.observations.len(), 0, "scope-b must be isolated"); +} + +#[tokio::test] +async fn zero_limit_is_rejected() { + 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(); + let err = store + .find_similar_tool_observations("x", "scope-a", 0) + .await + .unwrap_err(); + assert!(format!("{err}").contains("limit")); +}