agix-base 0.5.0

Agix — foundation types, traits, and context
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! Where memories live, how they are found, and who decides what to keep.
//!
//! Memory was one concrete struct with a fixed directory layout, one search
//! that was a substring scan, and one retriever that was an LLM call written
//! inline. Every part of that is a reasonable default and none of it was a
//! choice: a host with memories in a database, a deployment that wants a
//! vector index, a project whose recall should be deterministic in tests —
//! none had anywhere to plug in.
//!
//! The seams, matching the things that are actually separable:
//!
//! * [`MemoryStorage`] — where the memories are.
//! * [`DurableStore`] — the session's memory as the turn uses it: recall
//!   bookkeeping, what extraction may add, the prompt and the index.
//! * [`MemoryRetriever`] — which ones this turn should see.
//! * [`RetrievalHook`] — a look at the question before, and the answer after.
//!
//! # The defaults
//!
//! A session given no store has [`NoMemory`]. The `memory` crate's
//! `MemoryStore` implements both store traits over the session's memory
//! directories, and its retriever is an LLM selection call; the assembly
//! injects it when the `memory` unit is built.

use std::collections::HashSet;
use std::sync::Arc;

use async_trait::async_trait;

use crate::memory::{DurableMemory, MemoryError};

/// Where durable memories are kept.
///
/// Deliberately narrow: the operations the engine performs, not the ones the
/// file-backed implementation happens to expose. A backend that is not a
/// directory should not have to grow a concept of an index file to satisfy
/// this.
pub trait MemoryStorage: Send + Sync {
    /// Every memory, most recently seen first.
    fn load_all(&self) -> Vec<DurableMemory>;

    /// Memories matching `query`, however this backend matches. The shipped
    /// implementation is a substring scan; a backend with an index is
    /// expected to do better, and nothing depends on the ranking.
    fn search(&self, query: &str) -> Vec<DurableMemory>;

    /// Write these, returning how many landed.
    fn persist_batch(&self, memories: Vec<DurableMemory>) -> Result<usize, MemoryError>;

    /// Forget one by name; `false` if it was not there.
    fn remove(&self, name: &str) -> Result<bool, MemoryError>;
}

/// A session's durable memory as the turn recalls from it and adds to it.
pub trait DurableStore: MemoryStorage {
    /// `false`: recall, extraction, the memory prompt and the index are off
    /// whatever the settings say.
    fn keeps(&self) -> bool {
        true
    }

    fn record_recalled(&self, names: &[String]) -> Result<(), MemoryError>;

    /// How many more an extraction may add; 0 skips extraction before any
    /// model call.
    fn room(&self) -> usize;

    /// Keep what extraction found: secrets refused, `MemoryType::Project`
    /// with the project, the rest globally, no more than there is room for.
    /// How many were written.
    fn save_extracted(&self, found: Vec<DurableMemory>) -> Result<u32, MemoryError>;

    fn system_prompt(&self) -> Option<String>;

    fn index_for_prompt(&self) -> Option<String>;

    /// The retriever a session uses when the host gave none.
    fn retriever(&self) -> Arc<dyn MemoryRetriever> {
        Arc::new(SubstringRetriever)
    }
}

/// No durable memory: nothing recalled, nothing kept, nothing in the prompt.
pub struct NoMemory;

impl MemoryStorage for NoMemory {
    fn load_all(&self) -> Vec<DurableMemory> {
        Vec::new()
    }

    fn search(&self, _query: &str) -> Vec<DurableMemory> {
        Vec::new()
    }

    fn persist_batch(&self, _memories: Vec<DurableMemory>) -> Result<usize, MemoryError> {
        Ok(0)
    }

    fn remove(&self, _name: &str) -> Result<bool, MemoryError> {
        Ok(false)
    }
}

impl DurableStore for NoMemory {
    fn keeps(&self) -> bool {
        false
    }

    fn record_recalled(&self, _names: &[String]) -> Result<(), MemoryError> {
        Ok(())
    }

    fn room(&self) -> usize {
        0
    }

    fn save_extracted(&self, _found: Vec<DurableMemory>) -> Result<u32, MemoryError> {
        Ok(0)
    }

    fn system_prompt(&self) -> Option<String> {
        None
    }

    fn index_for_prompt(&self) -> Option<String> {
        None
    }
}

/// Memories held in memory. The second implementation, and what a test that
/// is about recall rather than about files should use.
#[derive(Default)]
pub struct InMemoryStorage {
    memories: std::sync::Mutex<Vec<DurableMemory>>,
}

impl InMemoryStorage {
    pub fn new(memories: Vec<DurableMemory>) -> Self {
        Self {
            memories: std::sync::Mutex::new(memories),
        }
    }
}

impl MemoryStorage for InMemoryStorage {
    fn load_all(&self) -> Vec<DurableMemory> {
        self.memories
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }

    fn search(&self, query: &str) -> Vec<DurableMemory> {
        self.load_all()
            .into_iter()
            .filter(|m| {
                m.name.contains(query) || m.description.contains(query) || m.content.contains(query)
            })
            .collect()
    }

    fn persist_batch(&self, memories: Vec<DurableMemory>) -> Result<usize, MemoryError> {
        let mut held = self.memories.lock().unwrap_or_else(|e| e.into_inner());
        let n = memories.len();
        for m in memories {
            match held.iter_mut().find(|h| h.name == m.name) {
                Some(existing) => *existing = m,
                None => held.push(m),
            }
        }
        Ok(n)
    }

    fn remove(&self, name: &str) -> Result<bool, MemoryError> {
        let mut held = self.memories.lock().unwrap_or_else(|e| e.into_inner());
        let before = held.len();
        held.retain(|m| m.name != name);
        Ok(held.len() != before)
    }
}

/// What a turn is asking for.
#[derive(Debug, Clone)]
pub struct RetrievalRequest {
    /// What the user said, which is what recall is about.
    pub query: String,
    pub limit: usize,
    /// Already shown this session. Surfacing one twice spends context to tell
    /// the model something it was told.
    pub already_surfaced: HashSet<String>,
    /// Tool names in play, so a memory whose name collides with a tool is not
    /// pulled in by the ambiguity.
    pub recent_tools: Vec<String>,
    pub model_name: String,
    pub session_id: Option<String>,
}

/// Which memories this turn should see.
#[async_trait]
pub trait MemoryRetriever: Send + Sync {
    /// Returns memory *names*, best first. Names rather than whole memories
    /// because the caller re-reads them from storage anyway, and a retriever
    /// backed by an index has no reason to carry the bodies around.
    async fn retrieve(
        &self,
        storage: &dyn MemoryStorage,
        model: &dyn crate::interface::model::Model,
        request: &RetrievalRequest,
    ) -> Vec<String>;
}

/// Matches on substrings and spends nothing.
///
/// The second implementation, and the one a test wants: recall that is a pure
/// function of the store is recall a test can assert on, where the model-based
/// default is a judgement that may reasonably differ between runs.
pub struct SubstringRetriever;

#[async_trait]
impl MemoryRetriever for SubstringRetriever {
    async fn retrieve(
        &self,
        storage: &dyn MemoryStorage,
        _model: &dyn crate::interface::model::Model,
        request: &RetrievalRequest,
    ) -> Vec<String> {
        storage
            .search(&request.query)
            .into_iter()
            .map(|m| m.name)
            .filter(|name| !request.already_surfaced.contains(name))
            .filter(|name| {
                !request
                    .recent_tools
                    .iter()
                    .any(|t| name.eq_ignore_ascii_case(t))
            })
            .take(request.limit)
            .collect()
    }
}

/// A look at the question before it is asked, and the answer before it is used.
///
/// Both halves are useful for the same reason and in opposite directions: a
/// deployment knows things about its own vocabulary that the retriever does
/// not (expand an acronym, add the current file's name), and knows things
/// about its own policy that the retriever should not have to (drop anything
/// from a scope this session must not see).
pub trait RetrievalHook: Send + Sync {
    /// Change the question. The default does nothing.
    fn before_retrieve(&self, _request: &mut RetrievalRequest) {}

    /// Change the answer — filter, reorder, truncate. The default does
    /// nothing.
    fn after_retrieve(&self, _request: &RetrievalRequest, _names: &mut Vec<String>) {}
}

/// Run a retrieval with its hooks around it.
pub async fn retrieve_with_hooks(
    retriever: &dyn MemoryRetriever,
    hooks: &[std::sync::Arc<dyn RetrievalHook>],
    storage: &dyn MemoryStorage,
    model: &dyn crate::interface::model::Model,
    mut request: RetrievalRequest,
) -> Vec<String> {
    for hook in hooks {
        hook.before_retrieve(&mut request);
    }
    let mut names = retriever.retrieve(storage, model, &request).await;
    for hook in hooks {
        hook.after_retrieve(&request, &mut names);
    }
    names
}

#[cfg(test)]
mod tests {
    use super::*;

    fn memory(name: &str, content: &str) -> DurableMemory {
        DurableMemory {
            name: name.to_string(),
            description: String::new(),
            memory_type: crate::memory::MemoryType::default(),
            content: content.to_string(),
            source_session_id: String::new(),
            confidence: 0.8,
            last_seen: String::new(),
            recall_count: 0,
        }
    }

    struct NeverCalledModel;

    #[async_trait]
    impl crate::interface::model::Model for NeverCalledModel {
        fn api_type(&self) -> crate::provider::ApiType {
            crate::provider::ApiType::Anthropic
        }
        async fn stream(
            &self,
            _p: Vec<crate::prompt::PromptBlock>,
            _t: Vec<crate::interface::model::ToolDef>,
            _m: Vec<crate::interface::model::ModelMessage>,
            _s: crate::interface::model::StreamParams,
            _c: tokio_util::sync::CancellationToken,
        ) -> Result<crate::interface::model::ModelStream, crate::interface::model::ModelError>
        {
            panic!("a retriever that costs nothing must not call the model")
        }
    }

    fn store() -> InMemoryStorage {
        InMemoryStorage::new(vec![
            memory("deploy-process", "we deploy on fridays"),
            memory("Bash", "a memory whose name collides with a tool"),
            memory("unrelated", "nothing to do with anything"),
        ])
    }

    #[tokio::test]
    async fn a_retriever_that_costs_nothing_can_replace_the_one_that_costs_a_call() {
        let names = SubstringRetriever
            .retrieve(
                &store(),
                &NeverCalledModel,
                &RetrievalRequest {
                    query: "deploy".into(),
                    limit: 5,
                    already_surfaced: HashSet::new(),
                    recent_tools: Vec::new(),
                    model_name: "test".into(),
                    session_id: None,
                },
            )
            .await;
        assert_eq!(names, ["deploy-process"]);
    }

    #[tokio::test]
    async fn recall_never_repeats_itself_or_shadows_a_tool() {
        let names = SubstringRetriever
            .retrieve(
                &store(),
                &NeverCalledModel,
                &RetrievalRequest {
                    query: "a".into(),
                    limit: 5,
                    already_surfaced: HashSet::from(["unrelated".to_string()]),
                    recent_tools: vec!["bash".into()],
                    model_name: "test".into(),
                    session_id: None,
                },
            )
            .await;
        assert!(!names.contains(&"unrelated".to_string()), "{names:?}");
        assert!(
            !names.contains(&"Bash".to_string()),
            "a memory named after a tool in play is an ambiguity, not a recall: {names:?}"
        );
    }

    #[tokio::test]
    async fn hooks_see_the_question_before_and_the_answer_after() {
        struct Expands;
        impl RetrievalHook for Expands {
            fn before_retrieve(&self, request: &mut RetrievalRequest) {
                if request.query == "ship" {
                    request.query = "deploy".into();
                }
            }
            fn after_retrieve(&self, _request: &RetrievalRequest, names: &mut Vec<String>) {
                names.retain(|n| n != "deploy-process");
            }
        }

        let hooks: Vec<Arc<dyn RetrievalHook>> = vec![Arc::new(Expands)];
        let names = retrieve_with_hooks(
            &SubstringRetriever,
            &hooks,
            &store(),
            &NeverCalledModel,
            RetrievalRequest {
                query: "ship".into(),
                limit: 5,
                already_surfaced: HashSet::new(),
                recent_tools: Vec::new(),
                model_name: "test".into(),
                session_id: None,
            },
        )
        .await;
        assert!(
            names.is_empty(),
            "the query rewrite found it and the result filter removed it: {names:?}"
        );

        // Without the filter the rewrite alone would have found it, which is
        // what makes the assertion above about both halves rather than one.
        let no_hooks: Vec<Arc<dyn RetrievalHook>> = Vec::new();
        let names = retrieve_with_hooks(
            &SubstringRetriever,
            &no_hooks,
            &store(),
            &NeverCalledModel,
            RetrievalRequest {
                query: "deploy".into(),
                limit: 5,
                already_surfaced: HashSet::new(),
                recent_tools: Vec::new(),
                model_name: "test".into(),
                session_id: None,
            },
        )
        .await;
        assert_eq!(names, ["deploy-process"]);
    }

    #[test]
    fn an_in_memory_store_round_trips_and_forgets() {
        let s = InMemoryStorage::default();
        assert_eq!(s.persist_batch(vec![memory("a", "x")]).unwrap(), 1);
        assert_eq!(s.load_all().len(), 1);
        assert_eq!(s.persist_batch(vec![memory("a", "y")]).unwrap(), 1);
        assert_eq!(s.load_all().len(), 1, "a rewrite is not a second memory");
        assert_eq!(s.load_all()[0].content, "y");
        assert!(s.remove("a").unwrap());
        assert!(!s.remove("a").unwrap(), "forgetting twice is not an error");
    }
}