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
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions knowledge-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down
42 changes: 41 additions & 1 deletion knowledge-runtime/src/runtime/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ pub struct KnowledgeRuntime {
config: RuntimeConfig,
entity_registry: EntityRegistry,
projection_tracker: ProjectionTracker,
bitemporal_records: Vec<bitemporal_runtime::BitemporalRecord<String>>,
}

impl KnowledgeRuntime {
Expand All @@ -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<bitemporal_runtime::BitemporalRecord<String>>,
) -> Self {
self.bitemporal_records = records;
self
}

pub(crate) fn adapter_ref(&self) -> &SemanticMemoryAdapter {
&self.adapter
}
Expand Down Expand Up @@ -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<SearchResult> = 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
Comment on lines +473 to +474

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve empty results from the configured temporal source

When injected records exist but none are visible at the requested valid/recorded coordinates, this condition discards the empty as-of answer and retains the earlier pipeline results. With no projection imports and non-strict temporal mode, that pipeline performs ordinary hybrid search, so querying before the first injected version can return current facts instead of the empty historical state. Distinguish an unconfigured source from a configured source with no visible records, and preserve the latter's empty answer rather than treating it as a reason to fall back. The scoped guidance specifically forbids substituting hybrid fact search for temporal behavior.

AGENTS.md reference: knowledge-runtime/AGENTS.md:L38-L39

Useful? React with 👍 / 👎.

.into_iter()
.map(|rec| SearchResult {
Comment on lines +473 to +476

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Apply query selection and result limits to the temporal source

Whenever any injected records are visible at the requested timestamps, this replaces the query pipeline's results with every visible record, regardless of the query text, resolved entity, or configured result limit. For example, a targeted temporal query with default_limit = 10 can return hundreds of unrelated records while discarding matching projection results. Integrate the temporal source into retrieval and merge rather than substituting a full snapshot after merging. This also violates the crate-specific requirement to preserve projection-backed retrieval as the supported substrate.

AGENTS.md reference: knowledge-runtime/AGENTS.md:L23-L24

Useful? React with 👍 / 👎.

content: rec.value,
source: semantic_memory::SearchSource::Fact {
fact_id: rec.id,
namespace: scope.namespace.clone(),
Comment on lines +476 to +480

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Enforce scope before returning injected bitemporal records

When a runtime has injected records, querying another namespace or a narrower workspace/repository scope returns the same records: as_of receives only timestamps, and the mapping simply labels every returned record with the requested namespace. This bypasses the scope filtering performed by the projection adapter and can expose records outside the requested scope, even when projection-backed execution enforced that scope successfully. Associate injected records with their originating scope and filter them before returning results; do not relabel unscoped records as belonging to the caller's namespace. The crate's scoped guidance explicitly requires scope pushdown and disclosure of widening.

AGENTS.md reference: knowledge-runtime/AGENTS.md:L23-L25

Useful? React with 👍 / 👎.

},
score: 1.0,
bm25_rank: None,
vector_rank: None,
cosine_similarity: None,
})
.collect();
}
}
}
Ok((results, trace))
}

Expand Down
91 changes: 91 additions & 0 deletions knowledge-runtime/src/temporal/bitemporal_bridge.rs
Original file line number Diff line number Diff line change
@@ -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<BitemporalRecord<T>>`
//! - `append_supersede` -> `Result<Vec<SupersessionReceipt>, BitemporalError>`
//! - `temporal_snapshot(records, as_of_time)` -> `Vec<BitemporalRecord<T>>`

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<String>],
valid_time: DateTime<Utc>,
recorded_time: DateTime<Utc>,
) -> Vec<BitemporalRecord<String>> {
as_of_query(records, valid_time, recorded_time)
}

/// Append a supersession; returns receipts for each superseded prior version.
pub fn supersede(
records: &mut Vec<BitemporalRecord<String>>,
new_record: BitemporalRecord<String>,
) -> Result<Vec<SupersessionReceipt>, BitemporalError> {
append_supersede(records, new_record)
}

/// Full snapshot at a recorded time.
pub fn snapshot(
records: &[BitemporalRecord<String>],
recorded_time: DateTime<Utc>,
) -> Vec<BitemporalRecord<String>> {
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<String> {
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");
}
}
1 change: 1 addition & 0 deletions knowledge-runtime/src/temporal/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod bitemporal_bridge;
pub mod claims;
83 changes: 83 additions & 0 deletions knowledge-runtime/tests/bitemporal_route.rs
Original file line number Diff line number Diff line change
@@ -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<String> {
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<BitemporalRecord<String>>) -> 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"
);
}
5 changes: 5 additions & 0 deletions llm-tool-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand All @@ -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"] }
1 change: 1 addition & 0 deletions llm-tool-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down
91 changes: 91 additions & 0 deletions llm-tool-runtime/src/tool_observation_store.rs
Original file line number Diff line number Diff line change
@@ -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),
Comment on lines +34 to +38

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve distinct invocations with identical summaries

When two invocations in the same scope produce the same summary, the second observation is silently discarded. MemoryStore::add_fact_with_trace deduplicates solely by namespace and content and returns the existing fact ID without updating metadata, so different invocation IDs, statuses, or receipt IDs do not make these writes distinct. Use observation identity in the persistence scheme rather than relying on summary-only fact insertion, otherwise repeated tool runs cannot be durably represented.

Useful? React with 👍 / 👎.

)
.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<ToolObservationMemorySearchV1, ToolError> {
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
Comment on lines +62 to +65

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restrict observation searches to observation records

If the supplied MemoryStore also contains ordinary facts in the requested namespace, this unrestricted search returns those facts and then converts them into tool observations. The stored kind marker and OBSERVATION_SOURCE are never checked, so unrelated facts can both appear as fabricated observations and consume the result limit ahead of real observations. Filter by the observation source/kind before applying the observation limit.

Useful? React with 👍 / 👎.

.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(),
Comment on lines +74 to +78

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore observation fields from persisted metadata

Searching for a stored observation always replaces its tool name, invocation ID, status, session, timestamps, and receipt ID with empty values, despite persisting those fields in metadata. Consequently, even a successful store/search round trip cannot identify the invocation or dereference its receipt, unlike the existing in-memory implementation, which returns the original record. Resolve each matching fact and deserialize its stored observation metadata instead of constructing a summary-only placeholder.

Useful? React with 👍 / 👎.

summary: r.content,
status: String::new(),
started_at: None,
completed_at: None,
receipt_id: None,
})
.collect();
Ok(ToolObservationMemorySearchV1 {
observations,
derived_candidate_receipts: Vec::<ToolObservationDerivedCandidateTraceV1>::new(),
})
}
}
Loading
Loading