Skip to main content

aidaemon_memory/
history.rs

1//! What memory consolidation reads: a host's conversation history, as a
2//! typed contract. The host implements it over its own event log; memory
3//! never parses the host's storage.
4
5use aidaemon_core::ChannelVisibility;
6use async_trait::async_trait;
7use chrono::{DateTime, Utc};
8
9/// Who produced a turn.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum TurnRole {
12    User,
13    Assistant,
14    /// A tool's result.
15    Tool,
16}
17
18impl TurnRole {
19    pub fn as_str(self) -> &'static str {
20        match self {
21            Self::User => "user",
22            Self::Assistant => "assistant",
23            Self::Tool => "tool",
24        }
25    }
26}
27
28/// One turn of a session's history.
29#[derive(Debug, Clone, PartialEq)]
30pub struct HistoryTurn {
31    /// The host's ordering id: later turns have larger ids.
32    pub id: i64,
33    pub role: TurnRole,
34    pub content: Option<String>,
35    pub created_at: DateTime<Utc>,
36}
37
38/// A host's conversation history, as memory consolidation needs it.
39///
40/// "Memory-isolated" sessions (worker and mandate runs) never teach owner
41/// memory; turns from tasks whose memory policy suppressed access are never
42/// returned.
43#[async_trait]
44pub trait ConversationSource: Send + Sync {
45    /// Sessions with conversation turns before `cutoff`, memory-isolated
46    /// sessions left out.
47    async fn sessions_with_turns_before(
48        &self,
49        cutoff: DateTime<Utc>,
50    ) -> anyhow::Result<Vec<String>>;
51
52    /// Whether the session is a worker or mandate run that must not teach
53    /// owner memory.
54    async fn is_memory_isolated(&self, session_id: &str) -> anyhow::Result<bool>;
55
56    /// Whether every user message after turn `after_id` and before `cutoff`
57    /// came from the owner, and there was at least one. A session that is
58    /// memory-isolated is never owner-only.
59    async fn owner_only_since(
60        &self,
61        session_id: &str,
62        after_id: i64,
63        cutoff: DateTime<Utc>,
64    ) -> anyhow::Result<bool>;
65
66    /// The largest turn id after `after_id` and before `cutoff`.
67    async fn last_turn_id(
68        &self,
69        session_id: &str,
70        after_id: i64,
71        cutoff: DateTime<Utc>,
72    ) -> anyhow::Result<Option<i64>>;
73
74    /// Turns after `after_id` and before `cutoff`, oldest first, at most
75    /// `limit`.
76    async fn turns(
77        &self,
78        session_id: &str,
79        after_id: i64,
80        cutoff: DateTime<Utc>,
81        limit: usize,
82    ) -> anyhow::Result<Vec<HistoryTurn>>;
83
84    /// The session's audience, from its latest user message.
85    async fn visibility(&self, session_id: &str) -> Option<ChannelVisibility>;
86
87    /// The channel facts learned in this session are scoped to.
88    fn channel_id(&self, session_id: &str) -> Option<String>;
89
90    /// The project the session works in, when what is learned from it may
91    /// be kept as that project's memory (see [`crate::project`]). `None` by
92    /// default: everything is learned as personal memory, as before.
93    async fn project(&self, _session_id: &str) -> Option<aidaemon_core::ProjectRef> {
94        None
95    }
96}
97
98/// Per-session progress of a consolidation pass, so history is read once.
99#[async_trait]
100pub trait ConsolidationCursors: Send + Sync {
101    /// The last turn id consolidated for the session (0 when none).
102    async fn cursor(&self, session_id: &str) -> i64;
103
104    async fn set_cursor(&self, session_id: &str, turn_id: i64) -> anyhow::Result<()>;
105}
106
107/// One user message from the host's log, to index as a searchable span.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct LoggedMessage {
110    /// The host's id for the message; spans keep it as their source.
111    pub id: i64,
112    pub session_id: String,
113    pub content: String,
114    /// RFC 3339.
115    pub created_at: String,
116}
117
118/// The host's message log, as the memory store links into it: episodes
119/// record the messages they cover, and indexed messages are dropped once the
120/// host no longer keeps them. Memory never reads the host's tables itself.
121#[async_trait]
122pub trait MessageLog: Send + Sync {
123    /// The first and last user or assistant message of `session_id` from
124    /// `start` to `end`, both inclusive.
125    async fn message_bounds(
126        &self,
127        session_id: &str,
128        start: DateTime<Utc>,
129        end: DateTime<Utc>,
130    ) -> anyhow::Result<(Option<i64>, Option<i64>)>;
131
132    /// Which of `ids` the host still keeps.
133    async fn retained(&self, ids: &[i64]) -> anyhow::Result<std::collections::HashSet<i64>>;
134}
135
136/// One conversation turn from the host's log, as the background jobs read
137/// it. The host leaves out its own internal turns (a run talking to itself)
138/// and turns of tasks whose memory policy suppressed memory.
139#[derive(Debug, Clone, PartialEq)]
140pub struct LoggedTurn {
141    pub role: TurnRole,
142    pub content: Option<String>,
143    /// For an assistant turn: the tools it called, by name, in order.
144    pub tool_calls: Vec<String>,
145    /// For a tool result: the tool's name.
146    pub tool_name: Option<String>,
147    pub created_at: DateTime<Utc>,
148}
149
150/// Which sessions [`ActivityLog::uncaptured_sessions`] returns.
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152pub struct UncapturedSessions {
153    /// At least this many conversation turns since the session's latest
154    /// episode ended.
155    pub min_turns: usize,
156    /// Only turns before this count, and the session's last such turn is
157    /// before it too: the session has gone idle. `None`: any turn counts.
158    pub idle_before: Option<DateTime<Utc>>,
159}
160
161/// The host's conversation log as the full memory system's background jobs
162/// read it: which sessions have turns no episode covers, those turns, and
163/// the recent activity patterns are learned from. Memory never reads the
164/// host's tables itself.
165#[async_trait]
166pub trait ActivityLog: ConversationSource + ConsolidationCursors {
167    /// Sessions whose conversation turns since their latest episode end
168    /// pass `which`. `episode_ends` holds each session's latest episode end
169    /// (RFC 3339); a session missing from it has no episode. Memory-isolated
170    /// sessions may be returned: the jobs check.
171    async fn uncaptured_sessions(
172        &self,
173        episode_ends: &[(String, String)],
174        which: UncapturedSessions,
175    ) -> anyhow::Result<Vec<String>>;
176
177    /// Whether every user message after `since` (the session's latest
178    /// episode; `None`: the whole session) came from the owner, and there
179    /// was at least one. A memory-isolated session never is.
180    async fn owner_only_after(
181        &self,
182        session_id: &str,
183        since: Option<&crate::records::EpisodeBound>,
184    ) -> anyhow::Result<bool>;
185
186    /// The session's conversation turns after `since` (the latest episode;
187    /// `None`: from the start), oldest first, at most `limit` read.
188    async fn turns_after(
189        &self,
190        session_id: &str,
191        since: Option<&crate::records::EpisodeBound>,
192        limit: usize,
193    ) -> anyhow::Result<Vec<LoggedTurn>>;
194
195    /// Conversation turns of sessions that are not memory-isolated, from
196    /// `since` on, newest first, at most `limit` read.
197    async fn recent_turns(
198        &self,
199        since: DateTime<Utc>,
200        limit: usize,
201    ) -> anyhow::Result<Vec<LoggedTurn>>;
202
203    /// The owner's own messages from `since` on, in sessions that are not
204    /// memory-isolated, newest first, at most `limit` read.
205    async fn recent_owner_messages(
206        &self,
207        since: DateTime<Utc>,
208        limit: usize,
209    ) -> anyhow::Result<Vec<LoggedTurn>>;
210}