diff --git a/knowledge-runtime/src/runtime/core.rs b/knowledge-runtime/src/runtime/core.rs index 7e9dc157..1356563f 100755 --- a/knowledge-runtime/src/runtime/core.rs +++ b/knowledge-runtime/src/runtime/core.rs @@ -194,8 +194,9 @@ impl KnowledgeRuntime { }) } - /// Wire a bitemporal record source so the temporal route answers as-of - /// version selection from `bitemporal-runtime` (empty = existing behavior). + /// Attach process-local reference records for [`Self::reference_bitemporal_as_of`]. + /// These records have no scope or search-source identity and are never + /// used by scoped or ranked search. pub fn with_bitemporal_records( mut self, records: Vec>, @@ -204,6 +205,20 @@ impl KnowledgeRuntime { self } + /// Select a snapshot of the caller-supplied reference records. This is not + /// a scoped search, a fact lookup, or a read from the persisted owner. + pub fn reference_bitemporal_as_of( + &self, + valid_at: chrono::DateTime, + recorded_at_or_before: chrono::DateTime, + ) -> Vec> { + crate::temporal::bitemporal_bridge::as_of( + &self.bitemporal_records, + valid_at, + recorded_at_or_before, + ) + } + pub(crate) fn adapter_ref(&self) -> &SemanticMemoryAdapter { &self.adapter } @@ -459,35 +474,7 @@ impl KnowledgeRuntime { trace.recorded_as_of = Some(recorded_at_or_before.to_string()); trace.temporal_mode = Some(temporal_mode.to_string()); - 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(); - } - } - } + let results = merged.results.into_iter().map(|m| m.result).collect(); Ok((results, trace)) } diff --git a/knowledge-runtime/tests/bitemporal_route.rs b/knowledge-runtime/tests/bitemporal_route.rs index 3d266d29..4b18a2a3 100644 --- a/knowledge-runtime/tests/bitemporal_route.rs +++ b/knowledge-runtime/tests/bitemporal_route.rs @@ -39,45 +39,55 @@ fn runtime(dir: &std::path::Path, records: Vec>) -> Kno .with_bitemporal_records(records) } -#[tokio::test] -async fn temporal_route_consumes_bitemporal_records() { +#[test] +fn explicit_reference_snapshot_respects_both_time_coordinates() { let dir = tempfile::tempdir().unwrap(); let rt = runtime( dir.path(), vec![rec("x", 100, 100, "old"), rec("x", 200, 200, "new")], ); + let cutoff = |seconds| chrono::Utc.timestamp_opt(seconds, 0).unwrap(); + for (valid, recorded, expected) in [(150, 250, "old"), (250, 150, "old"), (250, 250, "new")] { + let hits = rt.reference_bitemporal_as_of(cutoff(valid), cutoff(recorded)); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].id, "x"); + assert_eq!(hits[0].value, expected); + } +} - // 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" +#[tokio::test] +async fn reference_snapshot_does_not_fabricate_search_hits_across_scopes() { + let dir = tempfile::tempdir().unwrap(); + let rt = runtime( + dir.path(), + vec![ + rec("amber", 100, 100, "amber deployment status"), + rec("indigo", 100, 100, "indigo inventory status"), + rec("amber", 90, 200, "amber retroactive correction"), + ], ); - assert!(trace.temporal_mode.as_deref().is_some()); + let default = Scope::new("ns"); + let other = Scope::new("unrelated-namespace"); - // 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" - ); + // The adapter has no imports or facts in either scope. A reference vector + // has no scope, search ranking or dereferenceable fact IDs. + for (scope, query, recorded) in [ + (&default, "amber deployment", "1970-01-01T00:02:30Z"), + (&other, "indigo inventory", "1970-01-01T00:04:10Z"), + ] { + let (hits, trace) = rt + .query_temporal_with_trace(query, Some(scope), None, "1970-01-01T00:02:30Z", recorded) + .await + .expect("permissive route explicitly degrades when imports are absent"); + assert_eq!( + hits.len(), + trace.merged_result_count, + "trace must describe the results actually returned" + ); + assert!( + hits.is_empty(), + "unscoped reference records are not search hits" + ); + assert_eq!(trace.temporal_mode.as_deref(), Some("downgraded")); + } } diff --git a/living-memory/living-memory/src/bin/ares-tool-observation-probe.rs b/living-memory/living-memory/src/bin/ares-tool-observation-probe.rs new file mode 100644 index 00000000..a904bc0f --- /dev/null +++ b/living-memory/living-memory/src/bin/ares-tool-observation-probe.rs @@ -0,0 +1,426 @@ +//! OFFLINE, DISPOSABLE canary for the tool-receipt -> observation-memory path. +//! +//! This is NOT a production transport, adapter, or integration, and it makes no +//! production-capability claim. It is a default-off CLI that must be invoked +//! explicitly by an operator, with a mandatory opt-in flag. +//! +//! Safety shape: +//! * Disabled unless `--enable-offline-canary` is passed. Wrong/missing scope or +//! any argument problem is denied BEFORE any filesystem access. +//! * The tool (`ares_offline_available_parallelism`) and namespace +//! (`ares-tool-observation-offline-canary`) are compile-time constants; the +//! caller cannot choose a tool, command, or path to execute. +//! * `--out-dir` must name a directory that does not yet exist (its parent must +//! exist). It is created atomically with `create_dir`; an existing path of any +//! kind (empty, non-empty, file, symlink) is denied and nothing is executed. +//! Both the Forge DB and the memory store live only under that directory. +//! * The tool calls `std::thread::available_parallelism()`: no subprocess, +//! caller-selected files, or network. `MockEmbedder` is used because this canary is +//! explicitly offline and disposable; it must not be used for real memory. +//! * Exactly one execution, one projection attempt, no automatic retry. To try +//! again the operator must supply a different NEW directory. +//! * Output is a single JSON metadata line (status, receipt ID, readback +//! booleans). The tool's backend payload and the raw receipt are never printed. + +use async_trait::async_trait; +use forge_engine::{ForgeStore, ForgeToolReceiptSink}; +use llm_tool_runtime::semantic_memory::ToolObservationMemory; +use llm_tool_runtime::{ + McpSurfaceKind, Tool, ToolApprovalKind, ToolBackendKind, ToolCall, ToolCtx, ToolDescriptor, + ToolError, ToolErrorClass, ToolExposureMode, ToolExposurePolicy, ToolIdempotencyClass, + ToolOriginKind, ToolOutputMode, ToolPlannerStage, ToolReceiptPersistence, ToolRegistry, + ToolResult, ToolRetryOwner, ToolRuntime, ToolSideEffectClass, +}; +use semantic_memory::{MemoryConfig, MemoryStore, MockEmbedder}; +use stack_ids::{AttemptId, TraceCtx, TrialId}; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::sync::Arc; + +/// Fixed tool: not selectable by the caller or by any model. +const TOOL_NAME: &str = "ares_offline_available_parallelism"; +const TOOL_VERSION: &str = "1.0.0"; +/// Fixed observation namespace; `--scope` must equal this exactly. +const NAMESPACE: &str = "ares-tool-observation-offline-canary"; +const ENABLE_FLAG: &str = "--enable-offline-canary"; +const FORGE_DB_FILE: &str = "forge.db"; +const MEMORY_DIR: &str = "mem"; +const CALLER: &str = "ares-tool-observation-probe"; + +const USAGE: &str = "usage: ares-tool-observation-probe --enable-offline-canary \ +--scope ares-tool-observation-offline-canary --out-dir "; + +struct Args { + out_dir: PathBuf, +} + +/// Why the run stopped before touching the filesystem. +enum Refusal { + Disabled, + Denied(&'static str), +} + +fn parse_args(args: Vec) -> Result { + // Default-off: without the explicit flag nothing else is even interpreted. + if !args.iter().any(|arg| arg.to_str() == Some(ENABLE_FLAG)) { + return Err(Refusal::Disabled); + } + let mut enabled = false; + let mut scope: Option = None; + let mut out_dir: Option = None; + let mut iter = args.into_iter(); + while let Some(arg) = iter.next() { + match arg.to_str() { + Some(ENABLE_FLAG) => { + if enabled { + return Err(Refusal::Denied("duplicate argument")); + } + enabled = true; + } + Some("--scope") => { + if scope.is_some() { + return Err(Refusal::Denied("duplicate argument")); + } + let value = iter + .next() + .and_then(|value| value.into_string().ok()) + .ok_or(Refusal::Denied("missing or invalid --scope value"))?; + scope = Some(value); + } + Some("--out-dir") => { + if out_dir.is_some() { + return Err(Refusal::Denied("duplicate argument")); + } + let value = iter + .next() + .ok_or(Refusal::Denied("missing --out-dir value"))?; + out_dir = Some(PathBuf::from(value)); + } + _ => return Err(Refusal::Denied("unrecognized argument")), + } + } + if scope.as_deref() != Some(NAMESPACE) { + return Err(Refusal::Denied("scope not admitted for this canary")); + } + let out_dir = out_dir.ok_or(Refusal::Denied("missing --out-dir"))?; + if out_dir.as_os_str().is_empty() { + return Err(Refusal::Denied("empty --out-dir")); + } + Ok(Args { out_dir }) +} + +/// Atomically create the single NEW sandbox directory. Never creates parents and +/// never reuses an existing path. +fn create_new_sandbox_dir(path: &Path) -> Result<(), &'static str> { + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(false); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + match builder.create(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + Err("out-dir already exists; a new directory is required") + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + Err("out-dir parent does not exist") + } + Err(_) => Err("could not create out-dir"), + } +} + +/// The only tool this canary can run. Reads one OS value, with no caller-selected +/// files, subprocesses, or network. +struct AvailableParallelismTool { + descriptor: ToolDescriptor, +} + +impl AvailableParallelismTool { + fn new() -> Self { + Self { + descriptor: ToolDescriptor { + name: TOOL_NAME.into(), + version: TOOL_VERSION.into(), + description: Some("Offline canary: read std::thread::available_parallelism".into()), + backend_kind: ToolBackendKind::LocalFunction, + input_schema: serde_json::json!({ + "type": "object", + "properties": {}, + "additionalProperties": false + }), + output_mode: ToolOutputMode::StructuredJson, + read_only: true, + side_effect_class: ToolSideEffectClass::ReadOnly, + idempotency_class: ToolIdempotencyClass::Idempotent, + approval_kind: ToolApprovalKind::None, + timeout_ms: 5_000, + concurrency_key: None, + cache_ttl_ms: None, + exposure_mode: ToolExposureMode::Hidden, + mcp_surface_kind: McpSurfaceKind::None, + exposure_policy: ToolExposurePolicy::default(), + receipt_persistence: ToolReceiptPersistence::ForgeRaw, + output_size_limit_bytes: Some(1024), + provider_payload: None, + }, + } + } +} + +#[async_trait] +impl Tool for AvailableParallelismTool { + fn descriptor(&self) -> &ToolDescriptor { + &self.descriptor + } + + async fn invoke(&self, _ctx: &ToolCtx, _call: &ToolCall) -> Result { + let parallelism = std::thread::available_parallelism().map_err(|_| { + ToolError::new(ToolErrorClass::Execution, "available_parallelism failed") + })?; + Ok(ToolResult::json( + serde_json::json!({ "available_parallelism": parallelism.get() }), + )) + } +} + +fn tool_ctx() -> ToolCtx { + ToolCtx { + trace_ctx: TraceCtx::generate(), + attempt_id: AttemptId::generate(), + trial_id: TrialId::generate(), + deadline: None, + workload_class: Some("offline_canary".into()), + budget_context: None, + scope: None, + dry_run: false, + approval_grant: None, + execution_permit: None, + idempotency_key: None, + caller: CALLER.into(), + planner_stage: ToolPlannerStage::Execution, + parent_receipt_id: None, + family_receipt_id: None, + replay_parent_receipt_id: None, + remote_oracle_lease_id: None, + remote_slice_result_id: None, + attestation_envelope_id: None, + cross_runtime_replay_ticket_id: None, + retry_owner: Some(ToolRetryOwner::External), + } +} + +/// A stage failure reported as metadata only (stage + error class). +struct Failure { + stage: &'static str, + class: String, +} + +impl Failure { + fn at(stage: &'static str, class: impl std::fmt::Debug) -> Self { + Self { + stage, + class: format!("{class:?}"), + } + } +} + +fn memory_config(sandbox: &Path) -> MemoryConfig { + MemoryConfig { + base_dir: sandbox.join(MEMORY_DIR), + ..Default::default() + } +} + +/// OFFLINE ONLY: deterministic mock embedder, no network or model. +fn open_memory(sandbox: &Path) -> Result { + let config = memory_config(sandbox); + let embedder = MockEmbedder::new(config.embedding.dimensions); + MemoryStore::open_with_embedder(config, Box::new(embedder)) + .map_err(|_| Failure::at("memory_open", "Open")) +} + +/// Phase 1: execute once, commit the Forge receipt, project by committed ID. +/// Everything opened here is dropped on return so phase 2 truly reopens. +async fn execute_and_project(sandbox: &Path) -> Result { + let store = Arc::new( + ForgeStore::open(&sandbox.join(FORGE_DB_FILE)) + .map_err(|_| Failure::at("forge_open", "Open"))?, + ); + let memory = open_memory(sandbox)?; + let sink = Arc::new( + ForgeToolReceiptSink::with_observation_scope(store, TOOL_NAME, NAMESPACE) + .map_err(|error| Failure::at("sink_scope", error.class))?, + ); + + let mut registry = ToolRegistry::new(); + registry.register(AvailableParallelismTool::new()); + let runtime = ToolRuntime::new(registry).with_receipt_sink(sink.clone()); + + let call = ToolCall::new( + TOOL_NAME, + TOOL_VERSION, + serde_json::json!({}), + ToolOriginKind::Local, + ); + // Single execution. The runtime returns only after the ForgeRaw sink + // acknowledged the receipt; a persistence failure surfaces as `result: Err`. + let execution = runtime.execute(&tool_ctx(), &call, None, None).await; + if let Err(error) = execution.result { + return Err(Failure::at("execute", error.class)); + } + let receipt_id = execution.receipt.receipt_id; + + // Project strictly by committed receipt ID. The payload in `execution.result` + // is dropped without being printed or projected. + sink.project_observation(&memory, &receipt_id) + .await + .map_err(|error| Failure::at("project", error.class))?; + Ok(receipt_id) +} + +struct Readback { + forge_found: bool, + forge_scope_matches: bool, + forge_status_succeeded: bool, + projection_found: bool, + projection_status_succeeded: bool, +} + +/// Phase 2: reopen both stores from disk and read the receipt + projection back. +async fn reopen_and_read_back(sandbox: &Path, receipt_id: &str) -> Result { + let store = ForgeStore::open(&sandbox.join(FORGE_DB_FILE)) + .map_err(|_| Failure::at("forge_reopen", "Open"))?; + let row = store + .get_tool_receipt(receipt_id) + .map_err(|_| Failure::at("forge_readback", "Read"))?; + let (forge_found, forge_scope_matches, forge_status_succeeded) = match &row { + Some(row) => ( + row.receipt_id == receipt_id && row.tool_name == TOOL_NAME, + row.observation_scope.as_deref() == Some(NAMESPACE), + row.error_class.is_none(), + ), + None => (false, false, false), + }; + + let memory = open_memory(sandbox)?; + let found = memory + .find_similar_tool_observations(TOOL_NAME, NAMESPACE, 10) + .await + .map_err(|error| Failure::at("projection_readback", error.class))?; + let matching = found.observations.iter().find(|record| { + record.receipt_id.as_deref() == Some(receipt_id) + && record.tool_name == TOOL_NAME + && record.scope == NAMESPACE + }); + Ok(Readback { + forge_found, + forge_scope_matches, + forge_status_succeeded, + projection_found: matching.is_some(), + projection_status_succeeded: matching.is_some_and(|record| record.status == "succeeded"), + }) +} + +fn emit(value: serde_json::Value) { + println!("{value}"); +} + +fn refuse(refusal: Refusal) -> ExitCode { + let (status, reason) = match refusal { + Refusal::Disabled => ( + "disabled", + "offline canary is off unless explicitly enabled", + ), + Refusal::Denied(reason) => ("denied", reason), + }; + emit(serde_json::json!({ + "canary": "offline_disposable", + "status": status, + "reason": reason, + "executed": false, + })); + eprintln!("{USAGE}"); + ExitCode::from(2) +} + +fn main() -> ExitCode { + let args = match parse_args(std::env::args_os().skip(1).collect()) { + Ok(args) => args, + Err(refusal) => return refuse(refusal), + }; + if let Err(reason) = create_new_sandbox_dir(&args.out_dir) { + return refuse(Refusal::Denied(reason)); + } + + let runtime = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(_) => { + emit(serde_json::json!({ + "canary": "offline_disposable", + "status": "failed", + "stage": "async_runtime", + "executed": false, + })); + return ExitCode::from(1); + } + }; + + // No retry anywhere below: one execution, one projection, one readback. + let outcome = runtime.block_on(async { + let receipt_id = execute_and_project(&args.out_dir).await?; + let readback = reopen_and_read_back(&args.out_dir, &receipt_id).await?; + Ok::<_, Failure>((receipt_id, readback)) + }); + + match outcome { + Ok((receipt_id, readback)) => { + let ok = readback.forge_found + && readback.forge_scope_matches + && readback.forge_status_succeeded + && readback.projection_found + && readback.projection_status_succeeded; + emit(serde_json::json!({ + "canary": "offline_disposable", + "status": if ok { "succeeded" } else { "readback_mismatch" }, + "executed": true, + "tool_name": TOOL_NAME, + "namespace": NAMESPACE, + "receipt_id": receipt_id, + "reopened": true, + "retries": 0, + "embedder": "mock_offline_only", + "forge_readback": { + "found": readback.forge_found, + "scope_matches": readback.forge_scope_matches, + "status": if readback.forge_status_succeeded { "succeeded" } else { "failed" }, + }, + "projection_readback": { + "found": readback.projection_found, + "status": if readback.projection_status_succeeded { "succeeded" } else { "failed" }, + }, + "backend_payload": "withheld", + })); + if ok { + ExitCode::SUCCESS + } else { + ExitCode::from(1) + } + } + Err(failure) => { + emit(serde_json::json!({ + "canary": "offline_disposable", + "status": "failed", + "stage": failure.stage, + "error_class": failure.class, + "retries": 0, + })); + ExitCode::from(1) + } + } +} diff --git a/living-memory/living-memory/src/error.rs b/living-memory/living-memory/src/error.rs index f929fd1a..732bf7ba 100755 --- a/living-memory/living-memory/src/error.rs +++ b/living-memory/living-memory/src/error.rs @@ -90,6 +90,9 @@ pub enum ForgeError { #[error("sealed bundle cannot be mutated")] SealedBundle, + #[error("tool receipt '{receipt_id}' already exists with different content")] + ToolReceiptConflict { receipt_id: String }, + #[error("{0}")] Other(String), } @@ -124,6 +127,7 @@ impl ForgeError { Self::WriteThroughBlocked => "write_through_blocked", Self::PairIncomparable { .. } => "pair_incomparable", Self::SealedBundle => "sealed_bundle", + Self::ToolReceiptConflict { .. } => "tool_receipt_conflict", Self::Other(_) => "other", } } diff --git a/living-memory/living-memory/src/store/db.rs b/living-memory/living-memory/src/store/db.rs index 4ed946ef..a4899c05 100755 --- a/living-memory/living-memory/src/store/db.rs +++ b/living-memory/living-memory/src/store/db.rs @@ -72,6 +72,7 @@ impl ForgeStore { Self::run_migration_v3(&conn)?; Self::run_migration_v4(&conn)?; Self::run_migration_v5(&conn)?; + Self::run_migration_v6(&conn)?; Ok(Self { conn: Mutex::new(conn), @@ -231,6 +232,28 @@ INSERT INTO forge_meta VALUES ('created_at', strftime('%Y-%m-%dT%H:%M:%SZ', Ok(()) } + fn run_migration_v6(conn: &Connection) -> ForgeResult<()> { + let tx = + rusqlite::Transaction::new_unchecked(conn, rusqlite::TransactionBehavior::Immediate)?; + let has_scope: bool = tx.query_row( + "SELECT EXISTS(SELECT 1 FROM pragma_table_info('tool_receipts') WHERE name = 'observation_scope')", + [], + |row| row.get(0), + )?; + if !has_scope { + tx.execute( + "ALTER TABLE tool_receipts ADD COLUMN observation_scope TEXT", + [], + )?; + } + let current: u32 = tx.pragma_query_value(None, "user_version", |row| row.get(0))?; + if current < schema::FORGE_V6_USER_VERSION { + tx.pragma_update(None, "user_version", schema::FORGE_V6_USER_VERSION)?; + } + tx.commit()?; + Ok(()) + } + /// Acquire the connection lock. All public methods use this internally. fn lock_conn(&self) -> ForgeResult> { let started_at = Instant::now(); @@ -1014,20 +1037,37 @@ INSERT INTO forge_meta VALUES ('created_at', strftime('%Y-%m-%dT%H:%M:%SZ', // ── Tool Receipts (v3) ── + /// Insert a receipt once. An exact replay returns `false` without rewriting + /// the first observation time; different bytes for the same ID conflict. pub fn insert_tool_receipt(&self, row: &ToolReceiptRow) -> ForgeResult { - let result = self.lock_conn()?.execute( - "INSERT OR REPLACE INTO tool_receipts ( + let mut conn = self.lock_conn()?; + // Reserve the database writer before looking up this identity. Separate + // ForgeStore handles must not race between the lookup and the insert. + let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; + if let Some(mut stored) = Self::read_tool_receipt(&tx, &row.receipt_id)? { + stored.recorded_at.clone_from(&row.recorded_at); + if stored != *row { + return Err(ForgeError::ToolReceiptConflict { + receipt_id: row.receipt_id.clone(), + }); + } + tx.commit()?; + return Ok(false); + } + + let result = tx.execute( + "INSERT INTO tool_receipts ( receipt_id, tool_run_id, tool_name, tool_version, backend_kind, input_digest, output_digest_or_refs_json, policy_hash, approval_state, host_identity, started_at, finished_at, trace_id, trace_ctx_json, attempt_id, trial_id, error_class, retry_owner, replay_link, - provider_call_id, raw_payload_json, recorded_at + provider_call_id, raw_payload_json, recorded_at, observation_scope ) VALUES ( ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, - ?20, ?21, ?22 + ?20, ?21, ?22, ?23 )", rusqlite::params![ row.receipt_id, @@ -1052,18 +1092,28 @@ INSERT INTO forge_meta VALUES ('created_at', strftime('%Y-%m-%dT%H:%M:%SZ', row.provider_call_id, row.raw_payload_json, row.recorded_at, + row.observation_scope, ], )?; + tx.commit()?; Ok(result > 0) } pub fn get_tool_receipt(&self, receipt_id: &str) -> ForgeResult> { - match self.lock_conn()?.query_row( + let conn = self.lock_conn()?; + Self::read_tool_receipt(&conn, receipt_id) + } + + fn read_tool_receipt( + conn: &Connection, + receipt_id: &str, + ) -> ForgeResult> { + match conn.query_row( "SELECT receipt_id, tool_run_id, tool_name, tool_version, backend_kind, input_digest, output_digest_or_refs_json, policy_hash, approval_state, host_identity, started_at, finished_at, trace_id, trace_ctx_json, attempt_id, trial_id, error_class, retry_owner, replay_link, - provider_call_id, raw_payload_json, recorded_at + provider_call_id, raw_payload_json, recorded_at, observation_scope FROM tool_receipts WHERE receipt_id = ?1", [receipt_id], @@ -1091,6 +1141,7 @@ INSERT INTO forge_meta VALUES ('created_at', strftime('%Y-%m-%dT%H:%M:%SZ', provider_call_id: row.get(19)?, raw_payload_json: row.get(20)?, recorded_at: row.get(21)?, + observation_scope: row.get(22)?, }) }, ) { @@ -1236,7 +1287,7 @@ pub struct RunFailureRow { pub occurred_at: String, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct ToolReceiptRow { pub receipt_id: String, pub tool_run_id: String, @@ -1260,6 +1311,8 @@ pub struct ToolReceiptRow { pub provider_call_id: Option, pub raw_payload_json: String, pub recorded_at: String, + /// Namespace assigned by the admission owner, if projection was permitted. + pub observation_scope: Option, } #[allow(clippy::too_many_arguments)] diff --git a/living-memory/living-memory/src/store/schema.rs b/living-memory/living-memory/src/store/schema.rs index 56abc69e..7cc0a0a9 100755 --- a/living-memory/living-memory/src/store/schema.rs +++ b/living-memory/living-memory/src/store/schema.rs @@ -1,7 +1,7 @@ /// Range of valid user_version values for Forge databases. pub const FORGE_MIN_USER_VERSION: u32 = 1; pub const FORGE_MAX_USER_VERSION: u32 = 999; -pub const FORGE_CURRENT_USER_VERSION: u32 = 5; +pub const FORGE_CURRENT_USER_VERSION: u32 = FORGE_V6_USER_VERSION; /// Required tables in a Forge database. pub const REQUIRED_TABLES: &[&str] = &[ @@ -77,6 +77,7 @@ pub const FORGE_V4_USER_VERSION: u32 = 4; /// The user_version value for schema v5. pub const FORGE_V5_USER_VERSION: u32 = 5; +pub const FORGE_V6_USER_VERSION: u32 = 6; /// Compute the schema hash from the sorted CREATE TABLE statements. pub fn compute_schema_hash() -> String { diff --git a/living-memory/living-memory/src/tool_receipts.rs b/living-memory/living-memory/src/tool_receipts.rs index 6c4b4f4b..f3758402 100755 --- a/living-memory/living-memory/src/tool_receipts.rs +++ b/living-memory/living-memory/src/tool_receipts.rs @@ -1,4 +1,5 @@ use async_trait::async_trait; +use llm_tool_runtime::semantic_memory::{ToolObservationMemory, ToolObservationMemoryRecordV1}; use llm_tool_runtime::{ToolError, ToolErrorClass, ToolReceipt, ToolReceiptSink}; use semantic_memory_forge::{ ForgeToolBudgetContext, ForgeToolReceiptV2, FORGE_TOOL_RECEIPT_V2_SCHEMA, @@ -10,17 +11,107 @@ use crate::{store::db::ToolReceiptRow, ForgeStore}; #[derive(Debug, Clone)] pub struct ForgeToolReceiptSink { store: Arc, + observation_admission: Option<(String, String)>, } impl ForgeToolReceiptSink { pub fn new(store: Arc) -> Self { - Self { store } + Self { + store, + observation_admission: None, + } + } + + /// Bind a single tool and namespace selected by the runtime owner, not by a + /// tool request. Construct only after the caller's profile checks pass. + pub fn with_observation_scope( + store: Arc, + tool_name: &str, + namespace: &str, + ) -> Result { + let valid = |value: &str| { + !value.is_empty() + && value.len() <= 128 + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + }; + if !valid(namespace) || !valid(tool_name) { + return Err(ToolError::new( + ToolErrorClass::Denied, + "invalid tool observation admission", + )); + } + Ok(Self { + store, + observation_admission: Some((tool_name.into(), namespace.into())), + }) + } + + /// Project one previously committed receipt. A projection retry never + /// executes a tool and never rewrites Forge. Legacy and out-of-scope IDs + /// deliberately look the same as unknown IDs. + pub async fn project_observation( + &self, + memory: &impl ToolObservationMemory, + receipt_id: &str, + ) -> Result<(), ToolError> { + let denied = || { + ToolError::new( + ToolErrorClass::Denied, + "tool receipt not admitted for observation", + ) + }; + let (tool_name, namespace) = self.observation_admission.as_ref().ok_or_else(denied)?; + let row = self + .store + .get_tool_receipt(receipt_id) + .map_err(|_| { + ToolError::new( + ToolErrorClass::ReceiptPersistence, + "could not read committed Forge receipt", + ) + })? + .filter(|row| { + row.observation_scope.as_deref() == Some(namespace) && row.tool_name == *tool_name + }) + .ok_or_else(denied)?; + let status = if row.error_class.is_some() { + "failed" + } else { + "succeeded" + }; + memory + .store_tool_observation(ToolObservationMemoryRecordV1 { + summary: format!("Tool {tool_name} {status}"), + tool_name: row.tool_name, + invocation_id: row.tool_run_id, + session_id: None, + scope: namespace.clone(), + status: status.into(), + started_at: Some(row.started_at), + completed_at: Some(row.finished_at), + receipt_id: Some(row.receipt_id), + }) + .await } } #[async_trait] impl ToolReceiptSink for ForgeToolReceiptSink { async fn persist(&self, receipt: &ToolReceipt) -> Result<(), ToolError> { + let observation_scope = match &self.observation_admission { + Some((tool_name, namespace)) if receipt.tool_name == *tool_name => { + Some(namespace.clone()) + } + Some(_) => { + return Err(ToolError::new( + ToolErrorClass::Denied, + "tool is not admitted for observation", + )) + } + None => None, + }; let row = ToolReceiptRow { receipt_id: receipt.receipt_id.clone(), tool_run_id: receipt.tool_run_id.clone(), @@ -65,6 +156,7 @@ impl ToolReceiptSink for ForgeToolReceiptSink { }, )?, recorded_at: chrono::Utc::now().to_rfc3339(), + observation_scope, }; self.store.insert_tool_receipt(&row).map_err(|err| { ToolError::new( diff --git a/living-memory/living-memory/tests/ares_tool_observation_probe.rs b/living-memory/living-memory/tests/ares_tool_observation_probe.rs new file mode 100644 index 00000000..bd998bdc --- /dev/null +++ b/living-memory/living-memory/tests/ares_tool_observation_probe.rs @@ -0,0 +1,277 @@ +//! Tests for the OFFLINE, DISPOSABLE `ares-tool-observation-probe` canary. +//! +//! These drive the real binary as a subprocess. They make no claim about any +//! production transport or capability. + +use forge_engine::ForgeStore; +use llm_tool_runtime::semantic_memory::ToolObservationMemory; +use semantic_memory::{MemoryConfig, MemoryStore, MockEmbedder}; +use std::path::Path; +use std::process::{Command, Output}; +use tempfile::TempDir; + +const BIN: &str = env!("CARGO_BIN_EXE_ares-tool-observation-probe"); +const TOOL_NAME: &str = "ares_offline_available_parallelism"; +const NAMESPACE: &str = "ares-tool-observation-offline-canary"; + +fn run(args: &[&str]) -> Output { + Command::new(BIN) + .args(args) + .env_remove("RUST_LOG") + .output() + .unwrap_or_else(|error| panic!("spawn probe binary: {error}")) +} + +fn run_enabled(scope: &str, out_dir: &Path) -> Output { + run(&[ + "--enable-offline-canary", + "--scope", + scope, + "--out-dir", + out_dir.to_str().unwrap(), + ]) +} + +fn stdout_json(output: &Output) -> serde_json::Value { + let text = String::from_utf8(output.stdout.clone()).unwrap(); + assert_eq!(text.lines().count(), 1, "exactly one metadata line: {text}"); + serde_json::from_str(text.trim()).unwrap() +} + +fn assert_not_executed(output: &Output, expected_status: &str) { + assert!(!output.status.success()); + let json = stdout_json(output); + assert_eq!(json["status"], expected_status); + assert_eq!(json["executed"], false); + assert!(json.get("receipt_id").is_none()); +} + +#[test] +fn disabled_by_default_creates_no_directory() { + let tmp = TempDir::new().unwrap(); + let sandbox = tmp.path().join("sandbox"); + + // No opt-in flag at all. + let output = run(&["--scope", NAMESPACE, "--out-dir", sandbox.to_str().unwrap()]); + assert_not_executed(&output, "disabled"); + assert!(!sandbox.exists()); + + // No arguments at all. + let output = run(&[]); + assert_not_executed(&output, "disabled"); + + // Near-miss flag spellings are not opt-in. + for flag in [ + "--enable", + "--enable-offline-canary=1", + "enable-offline-canary", + ] { + let output = run(&[ + flag, + "--scope", + NAMESPACE, + "--out-dir", + sandbox.to_str().unwrap(), + ]); + assert_not_executed(&output, "disabled"); + assert!(!sandbox.exists()); + } + assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0); +} + +#[test] +fn wrong_or_missing_scope_creates_no_directory() { + let tmp = TempDir::new().unwrap(); + let sandbox = tmp.path().join("sandbox"); + + for scope in ["pilot", "", "ares-tool-observation-offline-canary ", "Ares"] { + let output = run_enabled(scope, &sandbox); + assert_not_executed(&output, "denied"); + assert!(!sandbox.exists(), "scope {scope:?} must not create a dir"); + } + + // Missing --scope. + let output = run(&[ + "--enable-offline-canary", + "--out-dir", + sandbox.to_str().unwrap(), + ]); + assert_not_executed(&output, "denied"); + assert!(!sandbox.exists()); + + // Missing --out-dir, unknown argument, and caller-supplied tool/command. + let output = run(&["--enable-offline-canary", "--scope", NAMESPACE]); + assert_not_executed(&output, "denied"); + let output = run(&[ + "--enable-offline-canary", + "--scope", + NAMESPACE, + "--out-dir", + sandbox.to_str().unwrap(), + "--tool", + "anything", + ]); + assert_not_executed(&output, "denied"); + assert!(!sandbox.exists()); + assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0); +} + +#[test] +fn missing_parent_is_denied_without_creating_parents() { + let tmp = TempDir::new().unwrap(); + let sandbox = tmp.path().join("no-such-parent").join("sandbox"); + let output = run_enabled(NAMESPACE, &sandbox); + assert_not_executed(&output, "denied"); + assert!(!tmp.path().join("no-such-parent").exists()); +} + +#[test] +fn existing_directory_or_file_is_denied_and_left_untouched() { + let tmp = TempDir::new().unwrap(); + + // Existing empty directory. + let empty = tmp.path().join("empty"); + std::fs::create_dir(&empty).unwrap(); + let output = run_enabled(NAMESPACE, &empty); + assert_not_executed(&output, "denied"); + assert_eq!(std::fs::read_dir(&empty).unwrap().count(), 0); + + // Existing non-empty directory. + let nonempty = tmp.path().join("nonempty"); + std::fs::create_dir(&nonempty).unwrap(); + std::fs::write(nonempty.join("keep.txt"), b"keep").unwrap(); + let output = run_enabled(NAMESPACE, &nonempty); + assert_not_executed(&output, "denied"); + let names: Vec<_> = std::fs::read_dir(&nonempty) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(names, vec![std::ffi::OsString::from("keep.txt")]); + assert_eq!(std::fs::read(nonempty.join("keep.txt")).unwrap(), b"keep"); + + // Existing regular file. + let file = tmp.path().join("file"); + std::fs::write(&file, b"x").unwrap(); + let output = run_enabled(NAMESPACE, &file); + assert_not_executed(&output, "denied"); + assert_eq!(std::fs::read(&file).unwrap(), b"x"); +} + +#[tokio::test] +async fn happy_path_reads_back_forge_receipt_and_projection_without_payload() { + let tmp = TempDir::new().unwrap(); + let sandbox = tmp.path().join("sandbox"); + + let output = run_enabled(NAMESPACE, &sandbox); + assert!( + output.status.success(), + "stdout={} stderr={}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let json = stdout_json(&output); + assert_eq!(json["status"], "succeeded"); + assert_eq!(json["executed"], true); + assert_eq!(json["tool_name"], TOOL_NAME); + assert_eq!(json["namespace"], NAMESPACE); + assert_eq!(json["reopened"], true); + assert_eq!(json["retries"], 0); + assert_eq!(json["forge_readback"]["found"], true); + assert_eq!(json["forge_readback"]["scope_matches"], true); + assert_eq!(json["projection_readback"]["found"], true); + assert_eq!(json["projection_readback"]["status"], "succeeded"); + let receipt_id = json["receipt_id"].as_str().unwrap().to_owned(); + assert!(!receipt_id.is_empty()); + + // Independently reopen the Forge store and read the committed receipt. + let forge = ForgeStore::open(&sandbox.join("forge.db")).unwrap(); + let row = forge.get_tool_receipt(&receipt_id).unwrap().unwrap(); + assert_eq!(row.tool_name, TOOL_NAME); + assert_eq!(row.observation_scope.as_deref(), Some(NAMESPACE)); + assert!(row.error_class.is_none()); + assert!(row.raw_payload_json.contains(TOOL_NAME)); + + // The backend payload (value and receipt body) is never printed. + let stdout = String::from_utf8(output.stdout.clone()).unwrap(); + let stderr = String::from_utf8(output.stderr.clone()).unwrap(); + for text in [&stdout, &stderr] { + assert!(!text.contains("\"available_parallelism\":")); + assert!(!text.contains(&row.raw_payload_json)); + assert!(!text.contains(&row.output_digest_or_refs_json)); + } + assert_eq!(json["backend_payload"], "withheld"); + + // Independently reopen the memory store and read the derived projection. + let config = MemoryConfig { + base_dir: sandbox.join("mem"), + ..Default::default() + }; + let memory = MemoryStore::open_with_embedder( + config.clone(), + Box::new(MockEmbedder::new(config.embedding.dimensions)), + ) + .unwrap(); + let found = memory + .find_similar_tool_observations(TOOL_NAME, NAMESPACE, 10) + .await + .unwrap() + .observations; + assert_eq!(found.len(), 1); + assert_eq!(found[0].receipt_id.as_deref(), Some(receipt_id.as_str())); + assert_eq!(found[0].tool_name, TOOL_NAME); + assert_eq!(found[0].scope, NAMESPACE); + assert_eq!(found[0].status, "succeeded"); + assert_eq!(found[0].summary, format!("Tool {TOOL_NAME} succeeded")); + assert!(!found[0].summary.contains("available_parallelism\":")); + assert!(memory + .find_similar_tool_observations(TOOL_NAME, "other", 10) + .await + .unwrap() + .observations + .is_empty()); +} + +#[test] +fn retry_on_existing_directory_never_re_executes() { + let tmp = TempDir::new().unwrap(); + let sandbox = tmp.path().join("sandbox"); + + let first = run_enabled(NAMESPACE, &sandbox); + assert!(first.status.success()); + let first_json = stdout_json(&first); + let receipt_id = first_json["receipt_id"].as_str().unwrap().to_owned(); + + // Snapshot every file under the sandbox (path + bytes) after the first run. + fn snapshot(root: &Path) -> Vec<(String, Vec)> { + let mut entries = Vec::new(); + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + stack.push(path); + } else { + let rel = path.strip_prefix(root).unwrap().display().to_string(); + entries.push((rel, std::fs::read(&path).unwrap())); + } + } + } + entries.sort(); + entries + } + let before = snapshot(&sandbox); + assert!(!before.is_empty()); + + for _ in 0..2 { + let retry = run_enabled(NAMESPACE, &sandbox); + assert_not_executed(&retry, "denied"); + let text = String::from_utf8(retry.stdout).unwrap(); + assert!(!text.contains(&receipt_id)); + } + + // Byte-for-byte unchanged: no second receipt, no rewritten store. + assert_eq!(snapshot(&sandbox), before); + let forge = ForgeStore::open(&sandbox.join("forge.db")).unwrap(); + let row = forge.get_tool_receipt(&receipt_id).unwrap().unwrap(); + assert_eq!(row.receipt_id, receipt_id); +} diff --git a/living-memory/living-memory/tests/migration_tests.rs b/living-memory/living-memory/tests/migration_tests.rs index 80aee18c..bc420c84 100755 --- a/living-memory/living-memory/tests/migration_tests.rs +++ b/living-memory/living-memory/tests/migration_tests.rs @@ -114,7 +114,7 @@ fn v1_db_upgraded_to_latest() { /// User version gets bumped to the latest additive migration after open. #[test] -fn user_version_is_v4_after_open() { +fn user_version_is_current_after_open() { let dir = TempDir::new().unwrap(); let db_path = dir.path().join("forge.db"); @@ -124,7 +124,7 @@ fn user_version_is_v4_after_open() { let version: u32 = conn .pragma_query_value(None, "user_version", |row| row.get(0)) .unwrap(); - assert_eq!(version, schema::FORGE_V5_USER_VERSION); + assert_eq!(version, schema::FORGE_CURRENT_USER_VERSION); } // ── Evidence bundle CRUD ── diff --git a/living-memory/living-memory/tests/tool_receipt_sink_tests.rs b/living-memory/living-memory/tests/tool_receipt_sink_tests.rs index 45e045e7..2f946b00 100755 --- a/living-memory/living-memory/tests/tool_receipt_sink_tests.rs +++ b/living-memory/living-memory/tests/tool_receipt_sink_tests.rs @@ -1,8 +1,10 @@ use forge_engine::{ForgeStore, ForgeToolReceiptSink}; +use llm_tool_runtime::semantic_memory::ToolObservationMemory; use llm_tool_runtime::{ ToolApprovalState, ToolBackendKind, ToolBudgetContext, ToolPlannerStage, ToolReceipt, ToolReceiptSink, ToolRetryOwner, }; +use semantic_memory::{MemoryConfig, MemoryStore, MockEmbedder}; use semantic_memory_forge::ForgeToolReceiptV2; use stack_ids::{AttemptId, ContentDigest, TraceCtx, TrialId}; use std::sync::Arc; @@ -79,3 +81,117 @@ async fn forge_tool_receipt_sink_persists_raw_receipt() { assert_eq!(raw.replay_parent_receipt_id.as_deref(), Some("retry-0")); assert_eq!(raw.planner_stage, "Execution"); } + +#[tokio::test] +async fn receipt_retries_preserve_first_write_and_reject_conflicts() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("forge.db"); + let store = Arc::new(ForgeStore::open(&path).unwrap()); + let retry_store = ForgeStore::open(&path).unwrap(); + let sink = ForgeToolReceiptSink::new(store.clone()); + let mut receipt = sample_receipt(); + sink.persist(&receipt).await.unwrap(); + + let first = store.get_tool_receipt("receipt-1").unwrap().unwrap(); + let mut replay = store.get_tool_receipt("receipt-1").unwrap().unwrap(); + replay.recorded_at = "2030-01-01T00:00:00Z".into(); + assert!(!retry_store.insert_tool_receipt(&replay).unwrap()); + sink.persist(&receipt).await.unwrap(); + + replay.error_class = Some(String::new()); + let error = retry_store.insert_tool_receipt(&replay).unwrap_err(); + assert!(matches!( + error, + forge_engine::ForgeError::ToolReceiptConflict { .. } + )); + + receipt.input_digest = ContentDigest::compute_str("conflicting input"); + let error = sink.persist(&receipt).await.unwrap_err(); + assert_eq!( + error.class, + llm_tool_runtime::ToolErrorClass::ReceiptPersistence + ); + let stored = store.get_tool_receipt("receipt-1").unwrap().unwrap(); + assert_eq!(stored, first); +} + +#[tokio::test] +async fn projection_reopens_only_committed_scoped_receipts() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("forge.db"); + let memory_config = MemoryConfig { + base_dir: dir.path().join("mem"), + ..Default::default() + }; + let open_memory = || { + MemoryStore::open_with_embedder( + memory_config.clone(), + Box::new(MockEmbedder::new(memory_config.embedding.dimensions)), + ) + .unwrap() + }; + let memory = open_memory(); + let store = Arc::new(ForgeStore::open(&path).unwrap()); + let sink = + ForgeToolReceiptSink::with_observation_scope(store.clone(), "run_verification", "pilot") + .unwrap(); + let wrong_scope = + ForgeToolReceiptSink::with_observation_scope(store.clone(), "run_verification", "other") + .unwrap(); + let mut receipt = sample_receipt(); + assert!(sink + .project_observation(&memory, &receipt.receipt_id) + .await + .is_err()); + sink.persist(&receipt).await.unwrap(); + let first = store + .get_tool_receipt(&receipt.receipt_id) + .unwrap() + .unwrap(); + assert!(wrong_scope + .project_observation(&memory, &receipt.receipt_id) + .await + .is_err()); + assert!(wrong_scope.persist(&receipt).await.is_err()); + receipt.receipt_id = "legacy-receipt".into(); + ForgeToolReceiptSink::new(store.clone()) + .persist(&receipt) + .await + .unwrap(); + assert!(sink + .project_observation(&memory, &receipt.receipt_id) + .await + .is_err()); + receipt.receipt_id = "failed-receipt".into(); + receipt.error_class = Some(llm_tool_runtime::ToolErrorClass::Execution); + sink.persist(&receipt).await.unwrap(); + drop(wrong_scope); + drop(sink); + drop(store); + let reopened = Arc::new(ForgeStore::open(&path).unwrap()); + let projector = + ForgeToolReceiptSink::with_observation_scope(reopened.clone(), "run_verification", "pilot") + .unwrap(); + for id in ["receipt-1", "receipt-1", "failed-receipt"] { + projector.project_observation(&memory, id).await.unwrap(); + } + assert_eq!(reopened.get_tool_receipt("receipt-1").unwrap(), Some(first)); + drop(memory); + let memory = open_memory(); + let mut results = memory + .find_similar_tool_observations("run_verification", "pilot", 10) + .await + .unwrap() + .observations; + results.sort_by(|a, b| a.receipt_id.cmp(&b.receipt_id)); + assert_eq!(results.len(), 2); + assert_eq!(results[0].summary, "Tool run_verification failed"); + assert_eq!(results[1].summary, "Tool run_verification succeeded"); + assert_eq!(results[1].receipt_id.as_deref(), Some("receipt-1")); + assert!(memory + .find_similar_tool_observations("run_verification", "other", 10) + .await + .unwrap() + .observations + .is_empty()); +} diff --git a/llm-tool-runtime/src/tool_observation_store.rs b/llm-tool-runtime/src/tool_observation_store.rs index c8ac041b..e0a0bf61 100644 --- a/llm-tool-runtime/src/tool_observation_store.rs +++ b/llm-tool-runtime/src/tool_observation_store.rs @@ -4,6 +4,8 @@ //! 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. +//! Similarity search can also collapse identical summaries; it is not a receipt +//! enumeration API. The underlying projection preserves distinct receipt IDs. use crate::semantic_memory::{ ToolObservationDerivedCandidateTraceV1, ToolObservationMemory, ToolObservationMemoryRecordV1, @@ -47,15 +49,26 @@ impl ToolObservationMemory for MemoryStore { "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| { + let result = if let Some(key) = record.receipt_id.as_deref() { + self.insert_derived_fact_once( + &record.scope, + OBSERVATION_SOURCE, + key, + &record.summary, + metadata, + ) + .await + } else { + self.add_fact( + &record.scope, + &record.summary, + Some(OBSERVATION_SOURCE), + Some(metadata), + ) + .await + .map(|_| ()) + }; + result.map_err(|e| { ToolError::new( ToolErrorClass::ProviderContract, format!("semantic-memory store failed: {e}"), diff --git a/llm-tool-runtime/tests/tool_observation_store.rs b/llm-tool-runtime/tests/tool_observation_store.rs index 34d1f451..3fe1181c 100644 --- a/llm-tool-runtime/tests/tool_observation_store.rs +++ b/llm-tool-runtime/tests/tool_observation_store.rs @@ -22,6 +22,45 @@ fn record(scope: &str, summary: &str) -> ToolObservationMemoryRecordV1 { } } +#[tokio::test] +async fn receipt_identity_not_summary_controls_replays() { + 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 first = record("scope-a", "read-only status succeeded"); + let (a, b) = tokio::join!( + store.store_tool_observation(first.clone()), + store.store_tool_observation(first.clone()), + ); + a.unwrap(); + b.unwrap(); + let mut second = first.clone(); + second.receipt_id = Some("rcpt-2".into()); + store.store_tool_observation(second).await.unwrap(); + let mut conflict = first; + conflict.status = "failed".into(); + assert!(store.store_tool_observation(conflict).await.is_err()); + // Similarity search intentionally collapses repeated text; use the + // namespace's owner rows to check independent persisted identities. + let mut ids: Vec<_> = store + .list_facts("scope-a", 10, 0) + .await + .unwrap() + .into_iter() + .map(|fact| { + let metadata = fact.metadata.unwrap(); + assert_eq!(metadata["status"], "succeeded"); + metadata["receipt_id"].as_str().unwrap().to_owned() + }) + .collect(); + ids.sort(); + assert_eq!(ids, ["rcpt-1", "rcpt-2"]); +} + #[tokio::test] async fn store_and_find_roundtrip_with_scope_isolation() { let dir = tempfile::tempdir().unwrap(); diff --git a/semantic-memory/src/error.rs b/semantic-memory/src/error.rs index 5e3c7af0..4296f163 100644 --- a/semantic-memory/src/error.rs +++ b/semantic-memory/src/error.rs @@ -56,6 +56,10 @@ pub enum MemoryError { receipt_id: String, }, + /// A derived fact was replayed with different content or metadata. + #[error("Derived fact identity already belongs to different material")] + DerivedFactConflict, + /// Canonical content digest computation failed. #[error("Digest error: {0}")] DigestError(String), @@ -339,6 +343,7 @@ impl MemoryError { Self::VectorBlobLengthMismatch { .. } => "vector_blob_length_mismatch", Self::VectorCodecProfileMismatch { .. } => "vector_codec_profile_mismatch", Self::SearchReceiptConflict { .. } => "search_receipt_conflict", + Self::DerivedFactConflict => "derived_fact_conflict", Self::DigestError(_) => "digest_error", Self::SearchReceiptNotFound { .. } => "search_receipt_not_found", Self::AuthoritySnapshotChanged { .. } => "authority_snapshot_changed", diff --git a/semantic-memory/src/knowledge.rs b/semantic-memory/src/knowledge.rs index e64ba2c3..241761b5 100644 --- a/semantic-memory/src/knowledge.rs +++ b/semantic-memory/src/knowledge.rs @@ -1031,6 +1031,117 @@ impl MemoryStore { Ok(fact_id) } + /// Insert a rebuildable, non-authoritative projection with an owner key. + /// The same namespace, source and key may only be replayed with identical + /// content and metadata. This local index is not a replication event. + pub async fn insert_derived_fact_once( + &self, + namespace: &str, + source: &str, + key: &str, + content: &str, + metadata: serde_json::Value, + ) -> Result<(), MemoryError> { + self.validate_content("fact.content", content)?; + let mut identity = blake3::Hasher::new_derive_key("semantic-memory derived fact v1"); + for part in [namespace, source, key] { + identity.update(&(part.len() as u64).to_be_bytes()); + identity.update(part.as_bytes()); + } + let hash = identity.finalize(); + let mut uuid_bytes = [0; 16]; + uuid_bytes.copy_from_slice(&hash.as_bytes()[..16]); + let id = uuid::Builder::from_custom_bytes(uuid_bytes) + .into_uuid() + .to_string(); + if let Some(existing) = self.get_fact(&id).await? { + if existing.namespace == namespace + && existing.source.as_deref() == Some(source) + && existing.content == content + && existing.metadata.as_ref() == Some(&metadata) + { + return Ok(()); + } + return Err(MemoryError::DerivedFactConflict); + } + + let (embedding, sparse, representation) = self + .embed_text_with_sparse_internal(content, crate::EmbeddingPurpose::Document) + .await?; + self.validate_embedding_dimensions(&embedding)?; + let embedding_bytes = db::embedding_to_bytes(&embedding); + let q8 = Quantizer::new(self.inner.config.embedding.dimensions) + .quantize(&embedding) + .map(|qv| quantize::pack_quantized(&qv)) + .ok(); + let max_facts = self.inner.config.limits.max_facts_per_namespace; + let ns = namespace.to_owned(); + let src = source.to_owned(); + let content = content.to_owned(); + self.with_write_conn(move |conn| { + // Acquire write ownership before checking identity and capacity, so + // separate connections cannot race a check followed by an insert. + let tx = rusqlite::Transaction::new_unchecked( + conn, + rusqlite::TransactionBehavior::Immediate, + )?; + let existing: Option = tx + .query_row( + "SELECT namespace = ?2 AND source IS ?3 AND content = ?4 AND metadata IS ?5 + FROM facts WHERE id = ?1", + params![&id, &ns, &src, &content, metadata.to_string()], + |row| row.get(0), + ) + .optional()?; + match existing { + Some(true) => return Ok(()), + Some(false) => return Err(MemoryError::DerivedFactConflict), + None => {} + } + let forgotten: bool = tx.query_row( + "SELECT EXISTS (SELECT 1 FROM forgotten_facts WHERE fact_id = ?1)", + params![&id], + |row| row.get(0), + )?; + if forgotten { + return Err(MemoryError::AuthorityHistoryRetained); + } + let count = tx.query_row( + "SELECT COUNT(*) FROM facts WHERE namespace = ?1", + params![&ns], + |row| row.get::<_, i64>(0), + )? as usize; + if count >= max_facts { + return Err(MemoryError::NamespaceFull { + namespace: ns, + count, + limit: max_facts, + }); + } + insert_fact_in_tx( + &tx, + &id, + &ns, + &content, + &embedding_bytes, + q8.as_deref(), + Some(&src), + Some(&metadata), + )?; + if let Some((weights, basis)) = sparse.as_ref().zip(representation.as_deref()) { + db::store_sparse_vector(&tx, &format!("fact:{id}"), weights, basis)?; + } + tx.commit()?; + Ok(()) + }) + .await?; + self.clear_search_cache(); + #[cfg(feature = "hnsw")] + self.sync_pending_hnsw_ops_best_effort("insert_derived_fact_once") + .await; + Ok(()) + } + /// Store a fact with a pre-computed embedding. pub async fn add_fact_with_embedding( &self,