swink-agent-memory 0.12.0

Session persistence and memory management for swink-agent
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! Async adapter over synchronous session stores.
//!
//! This module provides [`BlockingSessionStore`], which wraps any
//! [`SessionStore`](crate::store::SessionStore) and exposes async methods by
//! offloading each call to [`tokio::task::spawn_blocking`].
//!
//! # Why no async trait?
//!
//! A previous version of this module defined `AsyncSessionStore`, a trait that
//! mirrored `SessionStore` with async signatures. That trait was removed because:
//!
//! - It offered no behaviour beyond bridging sync → async via `spawn_blocking`.
//! - Its `load` signature accepted a per-call `registry` argument that
//!   `BlockingSessionStore` could never honour (a `&CustomMessageRegistry`
//!   reference cannot cross a `spawn_blocking` boundary), creating a silent
//!   footgun in the API.
//! - No implementation other than `BlockingSessionStore` existed or was planned.
//!
//! Callers that previously held `Box<dyn AsyncSessionStore>` should use
//! `Arc<BlockingSessionStore<S>>` directly, which is callable from async
//! contexts and has the same method set.

use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::Arc;

use swink_agent::{AgentMessage, CustomMessageRegistry};

use crate::entry::SessionEntry;
use crate::interrupt::InterruptState;
use crate::load_options::LoadOptions;
use crate::meta::SessionMeta;
use crate::search::{SessionHit, SessionSearchOptions};

/// A boxed future returned by [`BlockingSessionStore`] methods.
pub type SessionStoreFuture<'a, T> = Pin<Box<dyn Future<Output = io::Result<T>> + Send + 'a>>;

fn spawn_store_call<T: Send + 'static>(
    f: impl FnOnce() -> io::Result<T> + Send + 'static,
) -> SessionStoreFuture<'static, T> {
    Box::pin(async move {
        tokio::task::spawn_blocking(f)
            .await
            .map_err(io::Error::other)?
    })
}

/// Adapter that wraps a synchronous [`SessionStore`](crate::store::SessionStore)
/// and exposes async methods by running each call via `tokio::task::spawn_blocking`.
///
/// Custom messages are preserved faithfully: `save`/`append` snapshot custom
/// messages to their JSON envelope before crossing the thread boundary, and
/// `load` uses the registry configured at construction time to restore them.
///
/// To restore custom messages on load, provide the registry once at construction
/// via [`BlockingSessionStore::with_registry`].  A `&CustomMessageRegistry`
/// reference cannot cross `spawn_blocking` boundaries, so a per-call registry
/// is not supported.
///
/// Concurrent writes to the same session may corrupt the file.
/// Callers are expected to enforce single-writer access.
pub struct BlockingSessionStore<S: crate::store::SessionStore + 'static> {
    inner: Arc<S>,
    registry: Option<Arc<CustomMessageRegistry>>,
}

impl<S: crate::store::SessionStore + 'static> BlockingSessionStore<S> {
    /// Create a new blocking adapter wrapping the given session store.
    pub fn new(store: S) -> Self {
        Self {
            inner: Arc::new(store),
            registry: None,
        }
    }

    /// Attach a [`CustomMessageRegistry`] for deserializing custom messages on load.
    ///
    /// Because `&CustomMessageRegistry` cannot cross `spawn_blocking` boundaries,
    /// the registry must be provided once at construction rather than per call.
    #[must_use]
    pub fn with_registry(mut self, registry: Arc<CustomMessageRegistry>) -> Self {
        self.registry = Some(registry);
        self
    }
}

/// Clone messages for transfer across `spawn_blocking`.
///
/// Delegates to [`swink_agent::clone_messages_for_send`] which snapshots
/// `Custom` variants into `SerializedCustomMessage` wrappers so they can
/// cross thread boundaries faithfully.
fn clone_messages_for_blocking(messages: &[AgentMessage]) -> Vec<AgentMessage> {
    swink_agent::clone_messages_for_send(messages)
}

impl<S: crate::store::SessionStore + 'static> BlockingSessionStore<S> {
    /// Persist a session asynchronously, including both LLM and custom messages.
    pub fn save(
        &self,
        id: &str,
        meta: &SessionMeta,
        messages: &[AgentMessage],
    ) -> SessionStoreFuture<'_, ()> {
        let inner = Arc::clone(&self.inner);
        let id = id.to_string();
        let meta = meta.clone();
        let messages = clone_messages_for_blocking(messages);
        spawn_store_call(move || inner.save(&id, &meta, &messages))
    }

    /// Persist a session transcript plus its state snapshot asynchronously.
    pub fn save_full(
        &self,
        id: &str,
        meta: &SessionMeta,
        messages: &[AgentMessage],
        state: &serde_json::Value,
    ) -> SessionStoreFuture<'_, SessionMeta> {
        let inner = Arc::clone(&self.inner);
        let id = id.to_string();
        let meta = meta.clone();
        let messages = clone_messages_for_blocking(messages);
        let state = state.clone();
        spawn_store_call(move || inner.save_full(&id, &meta, &messages, &state))
    }

    /// Append messages to an existing session asynchronously.
    pub fn append(&self, id: &str, messages: &[AgentMessage]) -> SessionStoreFuture<'_, ()> {
        let inner = Arc::clone(&self.inner);
        let id = id.to_string();
        let messages = clone_messages_for_blocking(messages);
        spawn_store_call(move || inner.append(&id, &messages))
    }

    /// Load a session by ID asynchronously.
    ///
    /// Custom messages are restored using the registry supplied to
    /// [`BlockingSessionStore::with_registry`]. Without a registry, custom
    /// messages are discarded on load because the blocking adapter has no
    /// serialized-wrapper fallback.
    pub fn load(&self, id: &str) -> SessionStoreFuture<'_, (SessionMeta, Vec<AgentMessage>)> {
        let inner = Arc::clone(&self.inner);
        let id = id.to_string();
        let registry = self.registry.clone();
        spawn_store_call(move || inner.load(&id, registry.as_deref()))
    }

    /// Load a session transcript plus its state snapshot asynchronously from
    /// one backend-defined read boundary.
    pub fn load_full(
        &self,
        id: &str,
    ) -> SessionStoreFuture<'_, (SessionMeta, Vec<AgentMessage>, Option<serde_json::Value>)> {
        let inner = Arc::clone(&self.inner);
        let id = id.to_string();
        let registry = self.registry.clone();
        spawn_store_call(move || inner.load_full(&id, registry.as_deref()))
    }

    /// List all saved sessions asynchronously.
    pub fn list(&self) -> SessionStoreFuture<'_, Vec<SessionMeta>> {
        let inner = Arc::clone(&self.inner);
        spawn_store_call(move || inner.list())
    }

    /// Delete a session by ID asynchronously.
    pub fn delete(&self, id: &str) -> SessionStoreFuture<'_, ()> {
        let inner = Arc::clone(&self.inner);
        let id = id.to_string();
        spawn_store_call(move || inner.delete(&id))
    }

    /// Save session state snapshot asynchronously.
    pub fn save_state(&self, id: &str, state: &serde_json::Value) -> SessionStoreFuture<'_, ()> {
        let inner = Arc::clone(&self.inner);
        let id = id.to_string();
        let state = state.clone();
        spawn_store_call(move || inner.save_state(&id, &state))
    }

    /// Load session state snapshot asynchronously. Returns `None` if not set.
    pub fn load_state(&self, id: &str) -> SessionStoreFuture<'_, Option<serde_json::Value>> {
        let inner = Arc::clone(&self.inner);
        let id = id.to_string();
        spawn_store_call(move || inner.load_state(&id))
    }

    /// Persist interrupt state for a session asynchronously.
    pub fn save_interrupt(&self, id: &str, state: &InterruptState) -> SessionStoreFuture<'_, ()> {
        let inner = Arc::clone(&self.inner);
        let id = id.to_string();
        let state = state.clone();
        spawn_store_call(move || inner.save_interrupt(&id, &state))
    }

    /// Load interrupt state for a session asynchronously.
    pub fn load_interrupt(&self, id: &str) -> SessionStoreFuture<'_, Option<InterruptState>> {
        let inner = Arc::clone(&self.inner);
        let id = id.to_string();
        spawn_store_call(move || inner.load_interrupt(&id))
    }

    /// Clear interrupt state for a session asynchronously.
    pub fn clear_interrupt(&self, id: &str) -> SessionStoreFuture<'_, ()> {
        let inner = Arc::clone(&self.inner);
        let id = id.to_string();
        spawn_store_call(move || inner.clear_interrupt(&id))
    }

    /// Load a session with filtering options asynchronously.
    pub fn load_with_options(
        &self,
        id: &str,
        options: &LoadOptions,
    ) -> SessionStoreFuture<'_, (SessionMeta, Vec<SessionEntry>)> {
        let inner = Arc::clone(&self.inner);
        let id = id.to_string();
        let options = options.clone();
        spawn_store_call(move || inner.load_with_options(&id, &options))
    }

    /// Search persisted sessions asynchronously.
    pub fn search(
        &self,
        query: &str,
        options: &SessionSearchOptions,
    ) -> SessionStoreFuture<'_, Vec<SessionHit>> {
        let inner = Arc::clone(&self.inner);
        let query = query.to_string();
        let options = options.clone();
        spawn_store_call(move || inner.search(&query, &options))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::jsonl::JsonlSessionStore;
    use crate::time::now_utc;
    use swink_agent::AgentMessage;

    #[tokio::test]
    async fn blocking_session_store_adapter_works() {
        let dir = tempfile::tempdir().unwrap();
        let jsonl_store = JsonlSessionStore::new(dir.path().to_path_buf()).unwrap();

        let async_store = BlockingSessionStore::new(jsonl_store);

        let now = now_utc();
        let meta = SessionMeta {
            id: "test_async".to_string(),
            title: "Async test".to_string(),
            created_at: now,
            updated_at: now,
            version: 1,
            sequence: 0,
        };

        // Save via async adapter.
        let messages: Vec<AgentMessage> = vec![];
        async_store
            .save("test_async", &meta, &messages)
            .await
            .unwrap();

        // List via async adapter.
        let sessions = async_store.list().await.unwrap();
        assert_eq!(sessions.len(), 1);
        assert_eq!(sessions[0].id, "test_async");
        assert_eq!(sessions[0].title, "Async test");

        // Load via async adapter.
        let (loaded_meta, loaded_messages) = async_store.load("test_async").await.unwrap();
        assert_eq!(loaded_meta.id, "test_async");
        assert!(loaded_messages.is_empty());

        // Delete via async adapter.
        async_store.delete("test_async").await.unwrap();
        let sessions = async_store.list().await.unwrap();
        assert!(sessions.is_empty());
    }

    #[tokio::test]
    async fn blocking_adapter_bridges_state_methods() {
        let dir = tempfile::tempdir().unwrap();
        let jsonl_store = JsonlSessionStore::new(dir.path().to_path_buf()).unwrap();
        let async_store = BlockingSessionStore::new(jsonl_store);

        let now = now_utc();
        let meta = SessionMeta {
            id: "state_async".to_string(),
            title: "State test".to_string(),
            created_at: now,
            updated_at: now,
            version: 1,
            sequence: 0,
        };

        async_store.save("state_async", &meta, &[]).await.unwrap();
        async_store
            .save_state("state_async", &serde_json::json!({"scroll": 42}))
            .await
            .unwrap();

        let state = async_store.load_state("state_async").await.unwrap();
        assert_eq!(state, Some(serde_json::json!({"scroll": 42})));
    }

    #[tokio::test]
    async fn blocking_adapter_bridges_save_full() {
        let dir = tempfile::tempdir().unwrap();
        let jsonl_store = JsonlSessionStore::new(dir.path().to_path_buf()).unwrap();
        let async_store = BlockingSessionStore::new(jsonl_store);

        let meta = test_meta("full_async");
        let persisted_meta = async_store
            .save_full(
                "full_async",
                &meta,
                &[AgentMessage::Llm(swink_agent::LlmMessage::User(
                    swink_agent::UserMessage::new(vec![swink_agent::ContentBlock::Text {
                        text: "hello".to_string(),
                    }])
                    .with_timestamp(1),
                ))],
                &serde_json::json!({"scroll": 7}),
            )
            .await
            .unwrap();

        assert_eq!(persisted_meta.sequence, 1);
        let (_, loaded_messages) = async_store.load("full_async").await.unwrap();
        assert_eq!(loaded_messages.len(), 1);
        let state = async_store.load_state("full_async").await.unwrap();
        assert_eq!(state, Some(serde_json::json!({"scroll": 7})));
    }

    #[tokio::test]
    async fn blocking_adapter_bridges_load_full() {
        let dir = tempfile::tempdir().unwrap();
        let jsonl_store = JsonlSessionStore::new(dir.path().to_path_buf()).unwrap();
        let async_store = BlockingSessionStore::new(jsonl_store);

        async_store
            .save_full(
                "full_async_load",
                &test_meta("full_async_load"),
                &[AgentMessage::Llm(swink_agent::LlmMessage::User(
                    swink_agent::UserMessage::new(vec![swink_agent::ContentBlock::Text {
                        text: "hello".to_string(),
                    }])
                    .with_timestamp(1),
                ))],
                &serde_json::json!({"scroll": 11}),
            )
            .await
            .unwrap();

        let (meta, messages, state) = async_store.load_full("full_async_load").await.unwrap();
        assert_eq!(meta.id, "full_async_load");
        assert_eq!(messages.len(), 1);
        assert_eq!(state, Some(serde_json::json!({"scroll": 11})));
    }

    // ── Helper for custom-message regression tests ──────────────────────

    #[derive(Debug)]
    struct TestCustomMsg {
        data: String,
    }

    impl swink_agent::CustomMessage for TestCustomMsg {
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }
        fn type_name(&self) -> Option<&str> {
            Some("TestCustomMsg")
        }
        fn to_json(&self) -> Option<serde_json::Value> {
            Some(serde_json::json!({ "data": self.data }))
        }
    }

    fn test_registry() -> CustomMessageRegistry {
        let mut registry = CustomMessageRegistry::new();
        registry.register(
            "TestCustomMsg",
            Box::new(|val: serde_json::Value| {
                let data = val
                    .get("data")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| "missing data".to_string())?;
                Ok(Box::new(TestCustomMsg {
                    data: data.to_string(),
                }) as Box<dyn swink_agent::CustomMessage>)
            }),
        );
        registry
    }

    fn test_meta(id: &str) -> SessionMeta {
        let now = now_utc();
        SessionMeta {
            id: id.to_string(),
            title: "Test".to_string(),
            created_at: now,
            updated_at: now,
            version: 1,
            sequence: 0,
        }
    }

    // ── Regression tests for #104 ───────────────────────────────────────

    #[tokio::test]
    async fn blocking_adapter_preserves_custom_messages() {
        let dir = tempfile::tempdir().unwrap();
        let jsonl_store = JsonlSessionStore::new(dir.path().to_path_buf()).unwrap();
        let registry = Arc::new(test_registry());

        let async_store =
            BlockingSessionStore::new(jsonl_store).with_registry(Arc::clone(&registry));

        let messages: Vec<AgentMessage> = vec![
            AgentMessage::Llm(swink_agent::LlmMessage::User(
                swink_agent::UserMessage::new(vec![swink_agent::ContentBlock::Text {
                    text: "hello".to_string(),
                }])
                .with_timestamp(1),
            )),
            AgentMessage::Custom(Box::new(TestCustomMsg {
                data: "preserved".to_string(),
            })),
            AgentMessage::Llm(swink_agent::LlmMessage::User(
                swink_agent::UserMessage::new(vec![swink_agent::ContentBlock::Text {
                    text: "world".to_string(),
                }])
                .with_timestamp(2),
            )),
        ];

        let meta = test_meta("custom_save");
        async_store
            .save("custom_save", &meta, &messages)
            .await
            .unwrap();

        // Load back through the blocking adapter — custom messages must survive.
        let (_, loaded) = async_store.load("custom_save").await.unwrap();
        assert_eq!(loaded.len(), 3, "all three messages must be loaded");
        assert!(matches!(loaded[0], AgentMessage::Llm(_)));
        assert!(matches!(loaded[1], AgentMessage::Custom(_)));
        assert!(matches!(loaded[2], AgentMessage::Llm(_)));

        let custom = loaded[1].downcast_ref::<TestCustomMsg>().unwrap();
        assert_eq!(custom.data, "preserved");
    }

    #[tokio::test]
    async fn blocking_adapter_passes_registry_on_load() {
        let dir = tempfile::tempdir().unwrap();
        let registry = Arc::new(test_registry());

        // Save directly via the sync store so we know the data is correct.
        {
            let sync_store = JsonlSessionStore::new(dir.path().to_path_buf()).unwrap();
            let meta = test_meta("reg_load");
            let messages: Vec<AgentMessage> = vec![AgentMessage::Custom(Box::new(TestCustomMsg {
                data: "via-registry".to_string(),
            }))];
            crate::store::SessionStore::save(&sync_store, "reg_load", &meta, &messages).unwrap();
        }

        // Load through the blocking adapter with a registry — must restore the custom message.
        let jsonl_store = JsonlSessionStore::new(dir.path().to_path_buf()).unwrap();
        let async_store = BlockingSessionStore::new(jsonl_store).with_registry(registry);
        let (_, loaded) = async_store.load("reg_load").await.unwrap();
        assert_eq!(loaded.len(), 1);
        assert!(matches!(loaded[0], AgentMessage::Custom(_)));
        let custom = loaded[0].downcast_ref::<TestCustomMsg>().unwrap();
        assert_eq!(custom.data, "via-registry");
    }

    #[tokio::test]
    async fn blocking_adapter_without_registry_drops_custom_messages_on_load() {
        let dir = tempfile::tempdir().unwrap();

        {
            let sync_store = JsonlSessionStore::new(dir.path().to_path_buf()).unwrap();
            let meta = test_meta("drop_custom");
            let messages: Vec<AgentMessage> = vec![
                AgentMessage::Llm(swink_agent::LlmMessage::User(
                    swink_agent::UserMessage::new(vec![swink_agent::ContentBlock::Text {
                        text: "before".to_string(),
                    }])
                    .with_timestamp(1),
                )),
                AgentMessage::Custom(Box::new(TestCustomMsg {
                    data: "not-restored".to_string(),
                })),
                AgentMessage::Llm(swink_agent::LlmMessage::User(
                    swink_agent::UserMessage::new(vec![swink_agent::ContentBlock::Text {
                        text: "after".to_string(),
                    }])
                    .with_timestamp(2),
                )),
            ];
            crate::store::SessionStore::save(&sync_store, "drop_custom", &meta, &messages).unwrap();
        }

        let jsonl_store = JsonlSessionStore::new(dir.path().to_path_buf()).unwrap();
        let async_store = BlockingSessionStore::new(jsonl_store);
        let (_, loaded) = async_store.load("drop_custom").await.unwrap();

        assert_eq!(
            loaded.len(),
            2,
            "custom messages should be skipped without a registry"
        );
        assert!(matches!(loaded[0], AgentMessage::Llm(_)));
        assert!(matches!(loaded[1], AgentMessage::Llm(_)));
    }

    #[tokio::test]
    async fn blocking_adapter_append_preserves_custom_messages() {
        let dir = tempfile::tempdir().unwrap();
        let jsonl_store = JsonlSessionStore::new(dir.path().to_path_buf()).unwrap();
        let registry = Arc::new(test_registry());

        let async_store =
            BlockingSessionStore::new(jsonl_store).with_registry(Arc::clone(&registry));

        // Create session with an LLM message.
        let meta = test_meta("custom_append");
        let initial: Vec<AgentMessage> = vec![AgentMessage::Llm(swink_agent::LlmMessage::User(
            swink_agent::UserMessage::new(vec![swink_agent::ContentBlock::Text {
                text: "start".to_string(),
            }])
            .with_timestamp(1),
        ))];
        async_store
            .save("custom_append", &meta, &initial)
            .await
            .unwrap();

        // Append a custom message via the blocking adapter.
        let appended: Vec<AgentMessage> = vec![AgentMessage::Custom(Box::new(TestCustomMsg {
            data: "appended".to_string(),
        }))];
        async_store
            .append("custom_append", &appended)
            .await
            .unwrap();

        // Reload and verify the custom message survived.
        let (_, loaded) = async_store.load("custom_append").await.unwrap();
        assert_eq!(loaded.len(), 2);
        assert!(matches!(loaded[0], AgentMessage::Llm(_)));
        assert!(matches!(loaded[1], AgentMessage::Custom(_)));
        let custom = loaded[1].downcast_ref::<TestCustomMsg>().unwrap();
        assert_eq!(custom.data, "appended");
    }

    /// Verify the store is usable via `Arc` for concurrent async tasks (the
    /// typical caller pattern after the `AsyncSessionStore` trait was removed).
    #[tokio::test]
    async fn arc_blocking_store_usable_concurrently() {
        let dir = tempfile::tempdir().unwrap();
        let jsonl_store = JsonlSessionStore::new(dir.path().to_path_buf()).unwrap();
        let store = Arc::new(BlockingSessionStore::new(jsonl_store));

        let mut handles = Vec::new();
        for i in 0..3u8 {
            let store = Arc::clone(&store);
            handles.push(tokio::spawn(async move {
                let id = format!("concurrent_{i}");
                let now = now_utc();
                let meta = SessionMeta {
                    id: id.clone(),
                    title: format!("Session {i}"),
                    created_at: now,
                    updated_at: now,
                    version: 1,
                    sequence: 0,
                };
                store.save(&id, &meta, &[]).await.unwrap();
                let (loaded, _) = store.load(&id).await.unwrap();
                assert_eq!(loaded.id, id);
            }));
        }
        for h in handles {
            h.await.unwrap();
        }
    }
}