tinycortex 0.1.1

Rust core for the TinyCortex memory system
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
//! Tests for the channel-persistence subscriber and its workspace-identity
//! guard, ported from OpenHuman's `bus` tests onto the decoupled
//! [`ChannelEvent`] contract.

use tempfile::TempDir;

use super::*;

#[test]
fn subscriber_reads_rebound_workspace_from_shared_handle() {
    let tmp = TempDir::new().unwrap();
    let first = tmp.path().join("first");
    let second = tmp.path().join("second");
    let shared = Arc::new(RwLock::new(first.clone()));
    let subscriber = ConversationPersistenceSubscriber::new_shared(Arc::clone(&shared));

    assert_eq!(subscriber.workspace_dir_snapshot().unwrap(), first);
    *shared.write().unwrap() = second.clone();
    assert_eq!(subscriber.workspace_dir_snapshot().unwrap(), second);
}

#[tokio::test]
async fn persists_inbound_and_processed_turns_into_workspace_thread() {
    let temp = TempDir::new().expect("tempdir");
    let subscriber = ConversationPersistenceSubscriber::new(temp.path().to_path_buf());

    subscriber
        .handle(&ChannelEvent::Received {
            channel: "slack".into(),
            message_id: "m1".into(),
            sender: "alice".into(),
            reply_target: "general".into(),
            content: "hello".into(),
            thread_ts: Some("thread-1".into()),
            workspace_dir: temp.path().to_path_buf(),
        })
        .await;
    subscriber
        .handle(&ChannelEvent::Processed {
            channel: "slack".into(),
            message_id: "m1".into(),
            sender: "alice".into(),
            reply_target: "general".into(),
            thread_ts: Some("thread-1".into()),
            response: "hi there".into(),
            elapsed_ms: 42,
            success: true,
            workspace_dir: temp.path().to_path_buf(),
        })
        .await;

    let threads = super::super::list_threads(temp.path().to_path_buf()).expect("threads");
    assert_eq!(threads.len(), 1);
    assert_eq!(threads[0].id, "channel:slack_alice_general_thread:thread-1");

    let messages =
        super::super::get_messages(temp.path().to_path_buf(), &threads[0].id).expect("messages");
    assert_eq!(messages.len(), 2);
    assert_eq!(messages[0].id, "user:m1");
    assert_eq!(messages[0].sender, "user");
    assert_eq!(messages[1].id, "assistant:m1");
    assert_eq!(messages[1].sender, "assistant");
    assert_eq!(messages[1].extra_metadata["elapsedMs"], 42);
    assert_eq!(messages[1].extra_metadata["success"], true);
}

#[tokio::test]
async fn telegram_thread_ts_does_not_split_persisted_thread() {
    let temp = TempDir::new().expect("tempdir");
    let subscriber = ConversationPersistenceSubscriber::new(temp.path().to_path_buf());

    subscriber
        .handle(&ChannelEvent::Received {
            channel: "telegram".into(),
            message_id: "m1".into(),
            sender: "alice".into(),
            reply_target: "chat-1".into(),
            content: "hello".into(),
            thread_ts: Some("100".into()),
            workspace_dir: temp.path().to_path_buf(),
        })
        .await;
    subscriber
        .handle(&ChannelEvent::Received {
            channel: "telegram".into(),
            message_id: "m2".into(),
            sender: "alice".into(),
            reply_target: "chat-1".into(),
            content: "follow-up".into(),
            thread_ts: Some("200".into()),
            workspace_dir: temp.path().to_path_buf(),
        })
        .await;

    let threads = super::super::list_threads(temp.path().to_path_buf()).expect("threads");
    assert_eq!(threads.len(), 1);
    assert_eq!(threads[0].id, "channel:telegram_alice_chat-1");
}

#[tokio::test]
async fn duplicate_events_do_not_append_duplicate_messages() {
    let temp = TempDir::new().expect("tempdir");
    let subscriber = ConversationPersistenceSubscriber::new(temp.path().to_path_buf());

    let event = ChannelEvent::Received {
        channel: "discord".into(),
        message_id: "m1".into(),
        sender: "alice".into(),
        reply_target: "room-1".into(),
        content: "hello".into(),
        thread_ts: None,
        workspace_dir: temp.path().to_path_buf(),
    };

    subscriber.handle(&event).await;
    subscriber.handle(&event).await;

    let messages =
        super::super::get_messages(temp.path().to_path_buf(), "channel:discord_alice_room-1")
            .expect("messages");
    assert_eq!(messages.len(), 1);
    assert_eq!(messages[0].id, "user:m1");
}

#[test]
fn persisted_channel_thread_id_ignores_blank_thread_ts() {
    let without = persisted_channel_thread_id("slack", "alice", "general", None);
    let with_blank = persisted_channel_thread_id("slack", "alice", "general", Some("   "));
    assert_eq!(without, with_blank);
}

#[test]
fn channel_thread_title_uses_thread_suffix_only_for_non_telegram_threads() {
    assert_eq!(
        channel_thread_title("slack", "alice", "general", Some(" 123 ")),
        "slack · alice · general · thread 123"
    );
    assert_eq!(
        channel_thread_title("telegram", "alice", "chat-1", Some("123")),
        "telegram · alice · chat-1"
    );
}

#[test]
fn non_empty_trimmed_rejects_blank_strings() {
    assert_eq!(non_empty_trimmed("  hello  "), Some("hello"));
    assert_eq!(non_empty_trimmed("   "), None);
    assert_eq!(non_empty_trimmed(""), None);
}

// ── Workspace-identity guard tests ───────────────────────────────────────

/// Positive control: a `Received` event whose workspace matches the
/// subscriber's workspace IS persisted.
#[tokio::test]
async fn received_matching_workspace_is_persisted() {
    let temp = TempDir::new().expect("tempdir");
    let subscriber = ConversationPersistenceSubscriber::new(temp.path().to_path_buf());

    subscriber
        .handle(&ChannelEvent::Received {
            channel: "slack".into(),
            message_id: "m1".into(),
            sender: "bob".into(),
            reply_target: "dev".into(),
            content: "hello".into(),
            thread_ts: None,
            workspace_dir: temp.path().to_path_buf(),
        })
        .await;

    let messages = super::super::get_messages(temp.path().to_path_buf(), "channel:slack_bob_dev")
        .expect("messages");
    assert_eq!(messages.len(), 1);
    assert_eq!(messages[0].id, "user:m1");
}

/// `Received` with a mismatched workspace must be silently dropped — nothing
/// persisted in the subscriber's workspace.
#[tokio::test]
async fn received_stale_workspace_is_dropped() {
    let temp = TempDir::new().expect("tempdir");
    let stale = TempDir::new().expect("stale tempdir");
    let subscriber = ConversationPersistenceSubscriber::new(temp.path().to_path_buf());

    subscriber
        .handle(&ChannelEvent::Received {
            channel: "slack".into(),
            message_id: "m1".into(),
            sender: "alice".into(),
            reply_target: "general".into(),
            content: "should not persist".into(),
            thread_ts: None,
            workspace_dir: stale.path().to_path_buf(),
        })
        .await;

    let threads = super::super::list_threads(temp.path().to_path_buf()).expect("threads");
    assert!(
        threads.is_empty(),
        "stale-workspace event must not create a thread"
    );
}

/// `Processed` with matching workspace is appended correctly (positive control
/// for the processed-event guard).
#[tokio::test]
async fn processed_matching_workspace_is_appended() {
    let temp = TempDir::new().expect("tempdir");
    let subscriber = ConversationPersistenceSubscriber::new(temp.path().to_path_buf());

    // Seed the received event first so a thread exists.
    subscriber
        .handle(&ChannelEvent::Received {
            channel: "slack".into(),
            message_id: "m1".into(),
            sender: "alice".into(),
            reply_target: "general".into(),
            content: "hello".into(),
            thread_ts: None,
            workspace_dir: temp.path().to_path_buf(),
        })
        .await;

    subscriber
        .handle(&ChannelEvent::Processed {
            channel: "slack".into(),
            message_id: "m1".into(),
            sender: "alice".into(),
            reply_target: "general".into(),
            thread_ts: None,
            response: "hi there".into(),
            elapsed_ms: 10,
            success: true,
            workspace_dir: temp.path().to_path_buf(),
        })
        .await;

    let messages =
        super::super::get_messages(temp.path().to_path_buf(), "channel:slack_alice_general")
            .expect("messages");
    assert_eq!(messages.len(), 2);
    assert_eq!(messages[1].id, "assistant:m1");
}

/// `Processed` with a mismatched workspace must not be appended, even if a
/// prior `Received` for the correct workspace was already persisted.
#[tokio::test]
async fn processed_stale_workspace_is_dropped() {
    let temp = TempDir::new().expect("tempdir");
    let stale = TempDir::new().expect("stale tempdir");
    let subscriber = ConversationPersistenceSubscriber::new(temp.path().to_path_buf());

    subscriber
        .handle(&ChannelEvent::Received {
            channel: "slack".into(),
            message_id: "m1".into(),
            sender: "alice".into(),
            reply_target: "general".into(),
            content: "hello".into(),
            thread_ts: None,
            workspace_dir: temp.path().to_path_buf(),
        })
        .await;

    subscriber
        .handle(&ChannelEvent::Processed {
            channel: "slack".into(),
            message_id: "m1".into(),
            sender: "alice".into(),
            reply_target: "general".into(),
            thread_ts: None,
            response: "should not persist".into(),
            elapsed_ms: 10,
            success: true,
            workspace_dir: stale.path().to_path_buf(),
        })
        .await;

    let messages =
        super::super::get_messages(temp.path().to_path_buf(), "channel:slack_alice_general")
            .expect("messages");
    assert_eq!(messages.len(), 1);
    assert_eq!(messages[0].id, "user:m1");
}

/// Simulate the exact workspace-switch race:
/// 1. `Received` from workspace A — persisted.
/// 2. `Processed` from workspace B — dropped.
/// 3. `Processed` from workspace A — persisted.
#[tokio::test]
async fn workspace_switch_mid_conversation() {
    let workspace_a = TempDir::new().expect("workspace_a");
    let workspace_b = TempDir::new().expect("workspace_b");

    let subscriber = ConversationPersistenceSubscriber::new(workspace_a.path().to_path_buf());

    subscriber
        .handle(&ChannelEvent::Received {
            channel: "telegram".into(),
            message_id: "m1".into(),
            sender: "alice".into(),
            reply_target: "chat-1".into(),
            content: "hello".into(),
            thread_ts: None,
            workspace_dir: workspace_a.path().to_path_buf(),
        })
        .await;

    subscriber
        .handle(&ChannelEvent::Processed {
            channel: "telegram".into(),
            message_id: "m1".into(),
            sender: "alice".into(),
            reply_target: "chat-1".into(),
            thread_ts: None,
            response: "from workspace B — must be dropped".into(),
            elapsed_ms: 5,
            success: true,
            workspace_dir: workspace_b.path().to_path_buf(),
        })
        .await;

    subscriber
        .handle(&ChannelEvent::Processed {
            channel: "telegram".into(),
            message_id: "m1".into(),
            sender: "alice".into(),
            reply_target: "chat-1".into(),
            thread_ts: None,
            response: "from workspace A — should persist".into(),
            elapsed_ms: 10,
            success: true,
            workspace_dir: workspace_a.path().to_path_buf(),
        })
        .await;

    let messages = super::super::get_messages(
        workspace_a.path().to_path_buf(),
        "channel:telegram_alice_chat-1",
    )
    .expect("messages");

    assert_eq!(messages.len(), 2, "only user + correct assistant turn");
    assert_eq!(messages[0].id, "user:m1");
    assert_eq!(messages[1].id, "assistant:m1");
    assert_eq!(
        messages[1].content, "from workspace A — should persist",
        "workspace B response must not have been written"
    );
}

/// Events from 3 different wrong workspaces all get dropped; nothing persists.
#[tokio::test]
async fn multiple_stale_workspaces_all_dropped() {
    let temp = TempDir::new().expect("tempdir");
    let stale_a = TempDir::new().expect("stale_a");
    let stale_b = TempDir::new().expect("stale_b");
    let stale_c = TempDir::new().expect("stale_c");

    let subscriber = ConversationPersistenceSubscriber::new(temp.path().to_path_buf());

    for (i, stale) in [&stale_a, &stale_b, &stale_c].iter().enumerate() {
        subscriber
            .handle(&ChannelEvent::Received {
                channel: "discord".into(),
                message_id: format!("m{i}"),
                sender: "alice".into(),
                reply_target: "room-1".into(),
                content: format!("msg {i}"),
                thread_ts: None,
                workspace_dir: stale.path().to_path_buf(),
            })
            .await;
    }

    let threads = super::super::list_threads(temp.path().to_path_buf()).expect("threads");
    assert!(
        threads.is_empty(),
        "no events from wrong workspaces should create a thread"
    );
}

/// After a stale event is dropped, a subsequent matching-workspace event is
/// still persisted correctly.
#[tokio::test]
async fn correct_workspace_after_stale_events() {
    let temp = TempDir::new().expect("tempdir");
    let stale = TempDir::new().expect("stale tempdir");
    let subscriber = ConversationPersistenceSubscriber::new(temp.path().to_path_buf());

    subscriber
        .handle(&ChannelEvent::Received {
            channel: "slack".into(),
            message_id: "m0".into(),
            sender: "alice".into(),
            reply_target: "general".into(),
            content: "stale".into(),
            thread_ts: None,
            workspace_dir: stale.path().to_path_buf(),
        })
        .await;

    subscriber
        .handle(&ChannelEvent::Received {
            channel: "slack".into(),
            message_id: "m1".into(),
            sender: "alice".into(),
            reply_target: "general".into(),
            content: "valid".into(),
            thread_ts: None,
            workspace_dir: temp.path().to_path_buf(),
        })
        .await;

    let messages =
        super::super::get_messages(temp.path().to_path_buf(), "channel:slack_alice_general")
            .expect("messages");
    assert_eq!(
        messages.len(),
        1,
        "only the valid event should be persisted"
    );
    assert_eq!(messages[0].id, "user:m1");
    assert_eq!(messages[0].content, "valid");
}