harness_core/memory.rs
1//! Long-term, cross-session memory.
2//!
3//! Short-term context lives in [`crate::Context`]; the [`crate::Compactor`]
4//! keeps it within budget *within a single run*. Long-term memory is what
5//! survives across runs — the dataset that turns a generic assistant into a
6//! personalised one. Per Harrison Chase / Sarah Wooders: **memory is the
7//! harness**. To keep the framework's "open harness" promise the memory layer
8//! must be:
9//!
10//! - **owned by the operator** (no provider-side stateful APIs),
11//! - **transferable** (a swap to a different model must not lose memory),
12//! - **inspectable** (plain on-disk format, no opaque tokens).
13//!
14//! This module ships the trait + types. Concrete backends live in
15//! [`harness_context::FileMemory`] (JSONL) and downstream crates.
16//!
17//! ## Wiring
18//!
19//! - A `MemoryGuide` from `harness-rs-loop` calls [`Memory::recall`] at the
20//! start of every session and injects the top-K matches into the system
21//! prompt.
22//! - A `MemoryWriter` hook captures the final assistant text on
23//! `Event::TaskCompleted` and calls [`Memory::write`].
24//! - Tools may use the same `Arc<dyn Memory>` to commit explicit facts mid-run.
25
26use serde::{Deserialize, Serialize};
27
28/// One persisted memory record.
29///
30/// Owned (no borrows) so it round-trips through serde and across .await
31/// boundaries cleanly. Fields are intentionally minimal — apps that need
32/// richer schemas can wrap this with their own struct and store JSON in
33/// `content`.
34#[derive(Debug, Clone, Serialize, Deserialize)]
35#[non_exhaustive]
36pub struct MemoryEntry {
37 /// Stable id assigned by the backend. Empty if the caller has not yet
38 /// committed the entry.
39 #[serde(default)]
40 pub id: String,
41 /// Free-form fact / summary text. This is what recall returns and what
42 /// gets injected into a future system prompt.
43 pub content: String,
44 /// Optional keywords for cheap retrieval. Backends without semantic
45 /// indexing fall back to keyword match across `content` + `tags`.
46 #[serde(default)]
47 pub tags: Vec<String>,
48 /// Where the entry came from (session id, user, app name, …). Useful
49 /// for debugging and for multi-tenant filtering.
50 #[serde(default)]
51 pub source: Option<String>,
52 /// Milliseconds since unix epoch.
53 pub created_ms: i64,
54}
55
56impl MemoryEntry {
57 /// Convenience constructor. The backend assigns `id` on write.
58 pub fn new(content: impl Into<String>) -> Self {
59 Self {
60 id: String::new(),
61 content: content.into(),
62 tags: Vec::new(),
63 source: None,
64 created_ms: 0,
65 }
66 }
67
68 pub fn with_tags(mut self, tags: impl IntoIterator<Item = impl Into<String>>) -> Self {
69 self.tags = tags.into_iter().map(Into::into).collect();
70 self
71 }
72
73 pub fn with_source(mut self, source: impl Into<String>) -> Self {
74 self.source = Some(source.into());
75 self
76 }
77}
78
79/// The open-memory primitive.
80///
81/// Implementations:
82/// - **File-backed JSONL** ([`harness_context::FileMemory`]) — append-only,
83/// keyword recall, no extra deps. Default for the bundled examples.
84/// - Future: SQLite, sled, Postgres, vector-DB-backed semantic recall. Plug
85/// in by implementing this trait; nothing else in the framework changes.
86#[async_trait::async_trait]
87pub trait Memory: Send + Sync {
88 /// Return up to `k` entries most relevant to `query`, ordered by
89 /// descending relevance. The query is typically the current task
90 /// description; backends choose how to score (keyword, embedding, BM25…).
91 /// Returning an empty `Vec` is fine and must not be treated as an error.
92 async fn recall(&self, query: &str, k: usize) -> Result<Vec<MemoryEntry>, MemoryError>;
93
94 /// Persist `entry`. The backend assigns the `id` field; callers may
95 /// leave it empty. Implementations must be safe to call concurrently
96 /// from multiple tasks.
97 async fn write(&self, entry: MemoryEntry) -> Result<(), MemoryError>;
98}
99
100#[derive(Debug, thiserror::Error)]
101#[non_exhaustive]
102pub enum MemoryError {
103 #[error("memory io: {0}")]
104 Io(String),
105 #[error("memory backend: {0}")]
106 Backend(String),
107 #[error("memory serde: {0}")]
108 Serde(String),
109}