klieo_core/memory.rs
1//! Memory traits — short-term, long-term, episodic.
2
3use crate::error::MemoryError;
4use crate::ids::{FactId, RunId, ThreadId};
5use crate::llm::Message;
6use async_trait::async_trait;
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9
10/// Outcome of a tool invocation as recorded in the episodic event stream.
11#[derive(Debug, Clone, Serialize, Deserialize)]
12#[serde(tag = "outcome", rename_all = "snake_case")]
13pub enum ToolResult {
14 /// Tool returned a successful JSON result.
15 Ok {
16 /// Result payload.
17 value: serde_json::Value,
18 },
19 /// Tool returned an error message.
20 Err {
21 /// Error string.
22 message: String,
23 },
24}
25
26impl ToolResult {
27 /// Build a successful result. Convenience for the
28 /// `ToolResult::Ok { value }` struct-variant ceremony.
29 pub fn ok(value: serde_json::Value) -> Self {
30 Self::Ok { value }
31 }
32
33 /// Build an error result. Convenience for the
34 /// `ToolResult::Err { message }` struct-variant ceremony.
35 pub fn err(message: impl Into<String>) -> Self {
36 Self::Err {
37 message: message.into(),
38 }
39 }
40}
41
42#[cfg(test)]
43mod tool_result_factories_tests {
44 use super::*;
45
46 #[test]
47 fn ok_factory_builds_ok_variant() {
48 let v = serde_json::json!({"hit": true});
49 let r = ToolResult::ok(v.clone());
50 match r {
51 ToolResult::Ok { value } => assert_eq!(value, v),
52 _ => panic!("expected ToolResult::Ok variant"),
53 }
54 }
55
56 #[test]
57 fn err_factory_builds_err_variant() {
58 let r = ToolResult::err("boom");
59 match r {
60 ToolResult::Err { message } => assert_eq!(message, "boom"),
61 _ => panic!("expected ToolResult::Err variant"),
62 }
63 }
64}
65
66/// Conversation buffer scoped to a single thread.
67///
68/// ```
69/// # tokio_test::block_on(async {
70/// use klieo_core::test_utils::InMemoryShortTerm;
71/// use klieo_core::{ShortTermMemory, Message, Role, ThreadId};
72///
73/// let m = InMemoryShortTerm::default();
74/// let thread = ThreadId::new("t1");
75/// m.append(thread.clone(), Message {
76/// role: Role::User, content: "hi".into(),
77/// tool_calls: vec![], tool_call_id: None,
78/// }).await.unwrap();
79/// let loaded = m.load(thread, 1024).await.unwrap();
80/// assert_eq!(loaded.len(), 1);
81/// # });
82/// ```
83#[async_trait]
84pub trait ShortTermMemory: Send + Sync {
85 /// Append a message to the thread's history.
86 async fn append(&self, thread: ThreadId, msg: Message) -> Result<(), MemoryError>;
87
88 /// Append a batch of messages, oldest first. The default appends each in
89 /// turn; backends with bulk-insert support should override to collapse the
90 /// N writes into one round-trip (the resume path replays a full history).
91 async fn append_batch(
92 &self,
93 thread: ThreadId,
94 messages: Vec<Message>,
95 ) -> Result<(), MemoryError> {
96 for msg in messages {
97 self.append(thread.clone(), msg).await?;
98 }
99 Ok(())
100 }
101
102 /// Load up to `max_tokens` of the most-recent messages, oldest first.
103 /// Implementations approximate token counts (provider-specific).
104 async fn load(&self, thread: ThreadId, max_tokens: usize) -> Result<Vec<Message>, MemoryError>;
105
106 /// Drop all messages for `thread`.
107 async fn clear(&self, thread: ThreadId) -> Result<(), MemoryError>;
108}
109
110/// Namespacing for long-term memory facts.
111#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
112pub enum Scope {
113 /// Workspace-scoped (multi-agent shared).
114 Workspace(String),
115 /// Per-agent scoped.
116 Agent(String),
117 /// Process-global (use sparingly).
118 Global,
119}
120
121/// One stored fact in long-term memory.
122#[derive(Debug, Clone, Serialize, Deserialize)]
123#[non_exhaustive]
124pub struct Fact {
125 /// Plain-text body, embedded for retrieval.
126 pub text: String,
127 /// Caller-supplied metadata, opaque to the store.
128 #[serde(default)]
129 pub metadata: serde_json::Value,
130}
131
132impl Fact {
133 /// Prefer this over struct literals outside `klieo-core` (`#[non_exhaustive]`);
134 /// metadata defaults to JSON null — attach it with [`Fact::with_metadata`].
135 pub fn new(text: impl Into<String>) -> Self {
136 Self {
137 text: text.into(),
138 metadata: serde_json::Value::Null,
139 }
140 }
141
142 /// Override the default JSON-null metadata with an opaque caller value.
143 pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self {
144 self.metadata = metadata;
145 self
146 }
147}
148
149/// Long-term semantic memory.
150///
151/// ```
152/// # tokio_test::block_on(async {
153/// use klieo_core::test_utils::InMemoryLongTerm;
154/// use klieo_core::{Fact, LongTermMemory, Scope};
155///
156/// let m = InMemoryLongTerm::default();
157/// let scope = Scope::Workspace("ws".into());
158/// m.remember(scope.clone(), Fact::new("the sky is blue")).await.unwrap();
159/// let hits = m.recall(scope, "sky", 1).await.unwrap();
160/// assert_eq!(hits.len(), 1);
161/// # });
162/// ```
163#[async_trait]
164pub trait LongTermMemory: Send + Sync {
165 /// Store a fact under `scope`. Returns a stable id.
166 async fn remember(&self, scope: Scope, fact: Fact) -> Result<FactId, MemoryError>;
167
168 /// Top-`k` semantic recall under `scope` for the supplied query.
169 async fn recall(&self, scope: Scope, query: &str, k: usize) -> Result<Vec<Fact>, MemoryError>;
170
171 /// Remove a stored fact.
172 async fn forget(&self, id: FactId) -> Result<(), MemoryError>;
173}
174
175/// One event in the episodic event stream of a single agent run.
176///
177/// Marked `#[non_exhaustive]` so additive variants (e.g.
178/// [`Self::SummaryCheckpoint`]) can be introduced without forcing a
179/// SemVer-major bump. Match arms in downstream crates must include a
180/// fallback `_ => …`.
181#[derive(Debug, Clone, Serialize, Deserialize)]
182#[non_exhaustive]
183pub enum Episode {
184 /// Run started.
185 Started {
186 /// Agent name.
187 agent: String,
188 },
189 /// LLM call completed.
190 ///
191 /// `provider`/`model`/`prompt_tokens`/`completion_tokens` are
192 /// `Option` so legacy emit sites can leave them `None`; downstream
193 /// projectors fall back to the `LlmIo` sidecar in `klieo-runlog`
194 /// when the structured fields are absent.
195 LlmCall {
196 /// Total tokens reported by the provider (prompt + completion).
197 tokens: u32,
198 /// Wall-clock latency in milliseconds.
199 latency_ms: u32,
200 /// Provider identifier — e.g. `"ollama"`, `"openai"`,
201 /// `"anthropic"`, `"gemini"`. `None` for older records or
202 /// providers that don't expose a stable name.
203 ///
204 /// `#[serde(default)]` so legacy episodes serialised under
205 /// klieo 0.6.x deserialise as `None`.
206 #[serde(default)]
207 provider: Option<String>,
208 /// Model identifier — e.g. `"qwen2.5:14b"`, `"gpt-4o-mini"`.
209 #[serde(default)]
210 model: Option<String>,
211 /// Prompt-side token count when the provider splits the
212 /// breakdown; `None` falls back to `tokens` for total-only
213 /// reports.
214 #[serde(default)]
215 prompt_tokens: Option<u32>,
216 /// Completion-side token count when the provider splits the
217 /// breakdown.
218 #[serde(default)]
219 completion_tokens: Option<u32>,
220 },
221 /// Tool call completed.
222 ToolCall {
223 /// Tool name.
224 name: String,
225 /// JSON arguments.
226 args: serde_json::Value,
227 /// Tool outcome.
228 result: ToolResult,
229 },
230 /// Agent published a bus message.
231 BusPublish {
232 /// Subject.
233 subject: String,
234 },
235 /// Agent received a bus message.
236 BusReceive {
237 /// Subject.
238 subject: String,
239 },
240 /// Run completed successfully.
241 Completed,
242 /// Run failed.
243 Failed {
244 /// Error message.
245 error: String,
246 },
247 /// Summarizer checkpoint completed.
248 ///
249 /// Emitted by [`crate::summarize::summarize_history`] in lieu of
250 /// [`Self::LlmCall`] so the audit trail can distinguish summarizer
251 /// overhead from substantive agent reasoning. Downstream
252 /// observability (e.g. `klieo-runlog`) typically projects this as
253 /// a separate step kind so cost / latency attribution stays
254 /// faithful.
255 SummaryCheckpoint {
256 /// Number of older messages folded into the summary call.
257 input_message_count: u32,
258 /// Length of the resulting summary, in Unicode scalar values.
259 summary_chars: u32,
260 /// Wall-clock latency of the summarizer call.
261 latency_ms: u32,
262 /// Total tokens reported by the summarizer LLM (prompt +
263 /// completion).
264 tokens: u32,
265 },
266 /// Operational-layer event (klieo-ops). Body is an opaque
267 /// `serde_json::Value` to keep klieo-core free of an ops dependency.
268 /// klieo-ops provides typed serde conversion helpers via `OpsEvent`.
269 Ops(serde_json::Value),
270}
271
272impl Episode {
273 /// Construct an [`Episode::LlmCall`] with the legacy two-field shape
274 /// (`tokens` + `latency_ms`), leaving the 0.7-added
275 /// `provider`/`model`/`prompt_tokens`/`completion_tokens` fields as
276 /// `None`.
277 ///
278 /// Use this when the emit site does not have the enriched fields to
279 /// hand — e.g. test fixtures, providers that only report total
280 /// tokens, or call sites being migrated incrementally. For full
281 /// 0.7 emit semantics, construct the struct variant directly.
282 ///
283 /// ```
284 /// use klieo_core::Episode;
285 /// let ep = Episode::llm_call(42, 17);
286 /// match ep {
287 /// Episode::LlmCall { tokens, latency_ms, provider, .. } => {
288 /// assert_eq!(tokens, 42);
289 /// assert_eq!(latency_ms, 17);
290 /// assert!(provider.is_none());
291 /// }
292 /// _ => unreachable!(),
293 /// }
294 /// ```
295 pub fn llm_call(tokens: u32, latency_ms: u32) -> Self {
296 Episode::LlmCall {
297 tokens,
298 latency_ms,
299 provider: None,
300 model: None,
301 prompt_tokens: None,
302 completion_tokens: None,
303 }
304 }
305}
306
307/// Filter passed to `EpisodicMemory::list_runs`.
308#[derive(Debug, Clone, Default)]
309pub struct RunFilter {
310 /// Filter by agent name (substring match).
311 pub agent: Option<String>,
312 /// Inclusive lower bound on `started_at`.
313 pub since: Option<DateTime<Utc>>,
314 /// Inclusive upper bound on `started_at`.
315 pub until: Option<DateTime<Utc>>,
316 /// Maximum rows returned.
317 pub limit: Option<usize>,
318}
319
320/// Index-row summary returned by `list_runs`.
321#[derive(Debug, Clone, Serialize, Deserialize)]
322pub struct RunSummary {
323 /// Run id.
324 pub run_id: RunId,
325 /// Agent name.
326 pub agent: String,
327 /// First-event timestamp.
328 pub started_at: DateTime<Utc>,
329 /// Last-event timestamp, if completed/failed.
330 pub finished_at: Option<DateTime<Utc>>,
331 /// Number of episodes.
332 pub episode_count: u32,
333}
334
335/// Append-only event log of agent runs.
336///
337/// ```
338/// # tokio_test::block_on(async {
339/// use klieo_core::test_utils::InMemoryEpisodic;
340/// use klieo_core::{Episode, EpisodicMemory, RunId};
341///
342/// let m = InMemoryEpisodic::default();
343/// let run = RunId::new();
344/// m.record(run, Episode::Started { agent: "a".into() }).await.unwrap();
345/// let events = m.replay(run).await.unwrap();
346/// assert_eq!(events.len(), 1);
347/// # });
348/// ```
349#[async_trait]
350pub trait EpisodicMemory: Send + Sync {
351 /// Record an episode for `run`.
352 async fn record(&self, run: RunId, event: Episode) -> Result<(), MemoryError>;
353
354 /// Replay all episodes for `run` in order.
355 async fn replay(&self, run: RunId) -> Result<Vec<Episode>, MemoryError>;
356
357 /// List run summaries matching `filter`.
358 async fn list_runs(&self, filter: RunFilter) -> Result<Vec<RunSummary>, MemoryError>;
359}
360
361/// Resolved trio of memory handles ready to drop into an
362/// [`crate::agent::AgentContext`] or an `App`.
363///
364/// Impl crates (`klieo-memory-sqlite`, `klieo-memory-neo4j`,
365/// `klieo-memory-qdrant`) provide `From` conversions where they cover
366/// the full trio. Crates that only carry a subset (Neo4j covers
367/// short + episodic; Qdrant covers long) compose via the `App` builder's
368/// per-trait setters rather than a direct `From`.
369#[derive(Clone)]
370pub struct MemoryHandles {
371 /// Short-term conversation memory.
372 pub short_term: std::sync::Arc<dyn ShortTermMemory>,
373 /// Long-term semantic memory.
374 pub long_term: std::sync::Arc<dyn LongTermMemory>,
375 /// Episodic event log.
376 pub episodic: std::sync::Arc<dyn EpisodicMemory>,
377}
378
379impl MemoryHandles {
380 /// Build directly from three already-`Arc`-wrapped handles.
381 /// Most callers go through an impl crate's `From` instead.
382 pub fn new(
383 short_term: std::sync::Arc<dyn ShortTermMemory>,
384 long_term: std::sync::Arc<dyn LongTermMemory>,
385 episodic: std::sync::Arc<dyn EpisodicMemory>,
386 ) -> Self {
387 Self {
388 short_term,
389 long_term,
390 episodic,
391 }
392 }
393}
394
395#[cfg(test)]
396mod fact_ctor_tests {
397 use super::*;
398
399 #[test]
400 fn fact_new_defaults_metadata_null() {
401 let f = Fact::new("alice likes tea");
402 assert_eq!(f.text, "alice likes tea");
403 assert_eq!(f.metadata, serde_json::Value::Null);
404 let f2 = Fact::new("x").with_metadata(serde_json::json!({"k":"v"}));
405 assert_eq!(f2.metadata, serde_json::json!({"k":"v"}));
406 }
407}
408
409#[cfg(test)]
410mod tests {
411 use super::*;
412
413 #[allow(dead_code)]
414 fn _assert_dyn_short(_: &dyn ShortTermMemory) {}
415 #[allow(dead_code)]
416 fn _assert_dyn_long(_: &dyn LongTermMemory) {}
417 #[allow(dead_code)]
418 fn _assert_dyn_episodic(_: &dyn EpisodicMemory) {}
419
420 /// Maps each variant to its published snake_case wire discriminant.
421 ///
422 /// The exhaustive match is the drift guard: a new `Episode` variant
423 /// fails to compile here until its discriminant is added, which is the
424 /// signal to also publish a payload schema under `docs/schemas/runlog/`
425 /// and a fixture in `tests/schema_drift.rs`. `#[non_exhaustive]` does not
426 /// force a wildcard inside the defining crate, so this stays exhaustive.
427 fn kind_discriminant(episode: &Episode) -> &'static str {
428 match episode {
429 Episode::Started { .. } => "started",
430 Episode::LlmCall { .. } => "llm_call",
431 Episode::ToolCall { .. } => "tool_call",
432 Episode::BusPublish { .. } => "bus_publish",
433 Episode::BusReceive { .. } => "bus_receive",
434 Episode::Completed => "completed",
435 Episode::Failed { .. } => "failed",
436 Episode::SummaryCheckpoint { .. } => "summary_checkpoint",
437 Episode::Ops(_) => "ops",
438 }
439 }
440
441 fn one_sample_per_variant() -> Vec<Episode> {
442 vec![
443 Episode::Started {
444 agent: String::new(),
445 },
446 Episode::LlmCall {
447 tokens: 0,
448 latency_ms: 0,
449 provider: None,
450 model: None,
451 prompt_tokens: None,
452 completion_tokens: None,
453 },
454 Episode::ToolCall {
455 name: String::new(),
456 args: serde_json::Value::Null,
457 result: ToolResult::Ok {
458 value: serde_json::Value::Null,
459 },
460 },
461 Episode::BusPublish {
462 subject: String::new(),
463 },
464 Episode::BusReceive {
465 subject: String::new(),
466 },
467 Episode::Completed,
468 Episode::Failed {
469 error: String::new(),
470 },
471 Episode::SummaryCheckpoint {
472 input_message_count: 0,
473 summary_chars: 0,
474 latency_ms: 0,
475 tokens: 0,
476 },
477 Episode::Ops(serde_json::Value::Null),
478 ]
479 }
480
481 /// The set of Rust `Episode` discriminants must equal the `kind` enum
482 /// published in the envelope schema. Compile-time exhaustiveness of
483 /// [`kind_discriminant`] plus this runtime equality close the drift loop
484 /// from the type side; `tests/schema_drift.rs` validates payload shapes.
485 #[test]
486 fn episode_discriminants_match_published_envelope_schema() {
487 let mut discriminants: Vec<&str> = one_sample_per_variant()
488 .iter()
489 .map(kind_discriminant)
490 .collect();
491 discriminants.sort_unstable();
492
493 let schema_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
494 .join("../../docs/schemas/runlog/episode.schema.json");
495 let text = std::fs::read_to_string(&schema_path)
496 .unwrap_or_else(|err| panic!("read {}: {err}", schema_path.display()));
497 let schema: serde_json::Value =
498 serde_json::from_str(&text).expect("envelope schema parses");
499 let mut published: Vec<&str> = schema["properties"]["kind"]["enum"]
500 .as_array()
501 .expect("envelope schema declares a kind enum")
502 .iter()
503 .map(|value| value.as_str().expect("kind enum is strings"))
504 .collect();
505 published.sort_unstable();
506
507 assert_eq!(
508 discriminants, published,
509 "Episode variants have drifted from the published envelope kind enum",
510 );
511 }
512
513 /// Episodes serialised under klieo 0.6.x carry only `tokens` and
514 /// `latency_ms`. The four 0.7 fields must decode as `None` via
515 /// `#[serde(default)]`. Without that attribute, every persisted
516 /// 0.6 row breaks replay on upgrade.
517 #[test]
518 fn legacy_llm_call_json_deserialises_with_none_for_new_fields() {
519 let legacy = serde_json::json!({
520 "LlmCall": {
521 "tokens": 42,
522 "latency_ms": 17
523 }
524 });
525 let ep: Episode = serde_json::from_value(legacy).expect("legacy LlmCall decodes");
526 match ep {
527 Episode::LlmCall {
528 tokens,
529 latency_ms,
530 provider,
531 model,
532 prompt_tokens,
533 completion_tokens,
534 } => {
535 assert_eq!(tokens, 42);
536 assert_eq!(latency_ms, 17);
537 assert!(provider.is_none());
538 assert!(model.is_none());
539 assert!(prompt_tokens.is_none());
540 assert!(completion_tokens.is_none());
541 }
542 other => panic!("expected LlmCall, got {other:?}"),
543 }
544 }
545
546 /// [`Episode::llm_call`] returns the struct variant with all four
547 /// 0.7-added enrichment fields as `None`, preserving the legacy
548 /// emit shape for callers that don't have provider/model split.
549 #[test]
550 fn llm_call_ctor_leaves_enrichment_fields_none() {
551 match Episode::llm_call(42, 17) {
552 Episode::LlmCall {
553 tokens,
554 latency_ms,
555 provider,
556 model,
557 prompt_tokens,
558 completion_tokens,
559 } => {
560 assert_eq!(tokens, 42);
561 assert_eq!(latency_ms, 17);
562 assert!(provider.is_none());
563 assert!(model.is_none());
564 assert!(prompt_tokens.is_none());
565 assert!(completion_tokens.is_none());
566 }
567 other => panic!("expected LlmCall, got {other:?}"),
568 }
569 }
570
571 /// 0.7 emit sites with the full field set round-trip through serde
572 /// unchanged.
573 #[test]
574 fn enriched_llm_call_round_trips() {
575 let original = Episode::LlmCall {
576 tokens: 60,
577 latency_ms: 17,
578 provider: Some("ollama".into()),
579 model: Some("qwen2.5:14b".into()),
580 prompt_tokens: Some(40),
581 completion_tokens: Some(20),
582 };
583 let json = serde_json::to_value(&original).expect("serialises");
584 let back: Episode = serde_json::from_value(json).expect("deserialises");
585 match back {
586 Episode::LlmCall {
587 provider, model, ..
588 } => {
589 assert_eq!(provider.as_deref(), Some("ollama"));
590 assert_eq!(model.as_deref(), Some("qwen2.5:14b"));
591 }
592 other => panic!("expected LlmCall, got {other:?}"),
593 }
594 }
595}