opencrabs 0.3.34

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
//! Channel Search & Message Capture Tests
//!
//! Tests for ChannelMessageRepository CRUD, multi-chat/multi-channel queries,
//! and the ChannelSearchTool agent operations.

// --- Repository Tests ---

mod repository {
    use crate::db::Database;
    use crate::db::models::ChannelMessage;
    use crate::db::repository::channel_message::ChannelMessageRepository;

    async fn setup() -> (Database, ChannelMessageRepository) {
        let db = Database::connect_in_memory()
            .await
            .expect("Failed to create database");
        db.run_migrations().await.expect("Failed to run migrations");
        let repo = ChannelMessageRepository::new(db.pool().clone());
        (db, repo)
    }

    fn msg(
        channel: &str,
        chat_id: &str,
        chat_name: &str,
        sender: &str,
        content: &str,
    ) -> ChannelMessage {
        ChannelMessage::new(
            channel.into(),
            chat_id.into(),
            Some(chat_name.into()),
            "user1".into(),
            sender.into(),
            content.into(),
            "text".into(),
            None,
        )
    }

    #[tokio::test]
    async fn test_insert_and_recent() {
        let (_db, repo) = setup().await;
        let m = msg("telegram", "-100111", "Group A", "Alice", "Hello world");
        repo.insert(&m).await.unwrap();

        let recent = repo.recent(Some("telegram"), "-100111", 10).await.unwrap();
        assert_eq!(recent.len(), 1);
        assert_eq!(recent[0].content, "Hello world");
        assert_eq!(recent[0].sender_name, "Alice");
        assert_eq!(recent[0].channel, "telegram");
    }

    #[tokio::test]
    async fn test_recent_respects_limit() {
        let (_db, repo) = setup().await;
        for i in 0..10 {
            let m = msg(
                "telegram",
                "-100111",
                "Group A",
                "Alice",
                &format!("msg {i}"),
            );
            repo.insert(&m).await.unwrap();
        }

        let recent = repo.recent(Some("telegram"), "-100111", 3).await.unwrap();
        assert_eq!(recent.len(), 3);
    }

    #[tokio::test]
    async fn test_recent_without_channel_filter() {
        let (_db, repo) = setup().await;
        repo.insert(&msg(
            "telegram",
            "-100111",
            "TG Group",
            "Alice",
            "from telegram",
        ))
        .await
        .unwrap();
        repo.insert(&msg(
            "discord",
            "-100111",
            "DC Group",
            "Bob",
            "from discord",
        ))
        .await
        .unwrap();

        // Same chat_id, no channel filter — both returned
        let recent = repo.recent(None, "-100111", 10).await.unwrap();
        assert_eq!(recent.len(), 2);
    }

    #[tokio::test]
    async fn test_recent_filters_by_channel() {
        let (_db, repo) = setup().await;
        repo.insert(&msg("telegram", "-100111", "TG Group", "Alice", "tg msg"))
            .await
            .unwrap();
        repo.insert(&msg("discord", "-100222", "DC Chan", "Bob", "dc msg"))
            .await
            .unwrap();

        let tg = repo.recent(Some("telegram"), "-100111", 10).await.unwrap();
        assert_eq!(tg.len(), 1);
        assert_eq!(tg[0].content, "tg msg");

        let dc = repo.recent(Some("discord"), "-100111", 10).await.unwrap();
        assert_eq!(dc.len(), 0);
    }

    #[tokio::test]
    async fn test_search_by_content() {
        let (_db, repo) = setup().await;
        repo.insert(&msg(
            "telegram",
            "-100111",
            "Group",
            "Alice",
            "the quick brown fox",
        ))
        .await
        .unwrap();
        repo.insert(&msg(
            "telegram",
            "-100111",
            "Group",
            "Bob",
            "lazy dog jumps",
        ))
        .await
        .unwrap();
        repo.insert(&msg("telegram", "-100111", "Group", "Carol", "hello world"))
            .await
            .unwrap();

        let results = repo
            .search(Some("telegram"), Some("-100111"), "fox", 10, None)
            .await
            .unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].sender_name, "Alice");
    }

    #[tokio::test]
    async fn test_search_across_chats() {
        let (_db, repo) = setup().await;
        repo.insert(&msg(
            "telegram",
            "-100111",
            "Group A",
            "Alice",
            "deploy failed",
        ))
        .await
        .unwrap();
        repo.insert(&msg(
            "telegram",
            "-100222",
            "Group B",
            "Bob",
            "deploy succeeded",
        ))
        .await
        .unwrap();
        repo.insert(&msg(
            "slack",
            "C999",
            "General",
            "Carol",
            "deploy in progress",
        ))
        .await
        .unwrap();

        // Search all channels, all chats
        let results = repo.search(None, None, "deploy", 10, None).await.unwrap();
        assert_eq!(results.len(), 3);

        // Search telegram only, all chats
        let results = repo
            .search(Some("telegram"), None, "deploy", 10, None)
            .await
            .unwrap();
        assert_eq!(results.len(), 2);

        // Search specific chat only
        let results = repo
            .search(None, Some("-100111"), "deploy", 10, None)
            .await
            .unwrap();
        assert_eq!(results.len(), 1);
    }

    #[tokio::test]
    async fn test_search_no_match() {
        let (_db, repo) = setup().await;
        repo.insert(&msg("telegram", "-100111", "Group", "Alice", "hello"))
            .await
            .unwrap();

        let results = repo
            .search(Some("telegram"), Some("-100111"), "nonexistent", 10, None)
            .await
            .unwrap();
        assert!(results.is_empty());
    }

    #[tokio::test]
    async fn test_list_chats() {
        let (_db, repo) = setup().await;
        repo.insert(&msg("telegram", "-100111", "Group A", "Alice", "msg 1"))
            .await
            .unwrap();
        repo.insert(&msg("telegram", "-100111", "Group A", "Bob", "msg 2"))
            .await
            .unwrap();
        repo.insert(&msg("telegram", "-100222", "Group B", "Carol", "msg 3"))
            .await
            .unwrap();
        repo.insert(&msg("discord", "DC001", "Server Chan", "Dave", "msg 4"))
            .await
            .unwrap();

        // All channels
        let chats = repo.list_chats(None).await.unwrap();
        assert_eq!(chats.len(), 3);

        // Telegram only
        let chats = repo.list_chats(Some("telegram")).await.unwrap();
        assert_eq!(chats.len(), 2);

        // Find Group A — should have 2 messages
        let group_a = chats
            .iter()
            .find(|c| c.channel_chat_id == "-100111")
            .unwrap();
        assert_eq!(group_a.message_count, 2);
        assert_eq!(group_a.channel_chat_name.as_deref(), Some("Group A"));

        // Discord only
        let chats = repo.list_chats(Some("discord")).await.unwrap();
        assert_eq!(chats.len(), 1);
        assert_eq!(chats[0].message_count, 1);
    }

    #[tokio::test]
    async fn test_list_chats_empty() {
        let (_db, repo) = setup().await;
        let chats = repo.list_chats(None).await.unwrap();
        assert!(chats.is_empty());
    }

    #[tokio::test]
    async fn test_duplicate_insert_ignored() {
        let (_db, repo) = setup().await;
        let m = msg("telegram", "-100111", "Group", "Alice", "hello");
        repo.insert(&m).await.unwrap();
        // Same ID again — INSERT OR IGNORE
        repo.insert(&m).await.unwrap();

        let recent = repo.recent(Some("telegram"), "-100111", 10).await.unwrap();
        assert_eq!(recent.len(), 1);
    }

    #[tokio::test]
    async fn test_message_fields_roundtrip() {
        let (_db, repo) = setup().await;
        let m = ChannelMessage::new(
            "slack".into(),
            "C123".into(),
            Some("general".into()),
            "U456".into(),
            "Bob".into(),
            "test content".into(),
            "text".into(),
            Some("ts_789".into()),
        );
        let id = m.id;
        repo.insert(&m).await.unwrap();

        let recent = repo.recent(Some("slack"), "C123", 1).await.unwrap();
        assert_eq!(recent.len(), 1);
        let r = &recent[0];
        assert_eq!(r.id, id);
        assert_eq!(r.channel, "slack");
        assert_eq!(r.channel_chat_id, "C123");
        assert_eq!(r.channel_chat_name.as_deref(), Some("general"));
        assert_eq!(r.sender_id, "U456");
        assert_eq!(r.sender_name, "Bob");
        assert_eq!(r.content, "test content");
        assert_eq!(r.message_type, "text");
        assert_eq!(r.platform_message_id.as_deref(), Some("ts_789"));
    }
}

// --- ChannelSearchTool Tests ---

mod tool {
    use crate::brain::tools::channel_search::ChannelSearchTool;
    use crate::brain::tools::{Tool, ToolExecutionContext};
    use crate::db::Database;
    use crate::db::models::ChannelMessage;
    use crate::db::repository::channel_message::ChannelMessageRepository;

    async fn setup() -> (Database, ChannelMessageRepository, ChannelSearchTool) {
        let db = Database::connect_in_memory()
            .await
            .expect("Failed to create database");
        db.run_migrations().await.expect("Failed to run migrations");
        let repo = ChannelMessageRepository::new(db.pool().clone());
        let tool = ChannelSearchTool::new(repo.clone());
        (db, repo, tool)
    }

    fn ctx() -> ToolExecutionContext {
        ToolExecutionContext::new(uuid::Uuid::new_v4())
    }

    fn insert_msg(
        channel: &str,
        chat_id: &str,
        chat_name: &str,
        sender: &str,
        content: &str,
    ) -> ChannelMessage {
        ChannelMessage::new(
            channel.into(),
            chat_id.into(),
            Some(chat_name.into()),
            "u1".into(),
            sender.into(),
            content.into(),
            "text".into(),
            None,
        )
    }

    #[test]
    fn test_tool_name_and_schema() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let (_db, _repo, tool) = setup().await;
            assert_eq!(tool.name(), "channel_search");
            let schema = tool.input_schema();
            let props = schema["properties"].as_object().unwrap();
            assert!(props.contains_key("operation"));
            assert!(props.contains_key("channel"));
            assert!(props.contains_key("chat_id"));
            assert!(props.contains_key("query"));
            assert!(props.contains_key("n"));
            assert!(!tool.requires_approval());
        });
    }

    #[tokio::test]
    async fn test_list_chats_empty() {
        let (_db, _repo, tool) = setup().await;
        let input = serde_json::json!({"operation": "list_chats"});
        let result = tool.execute(input, &ctx()).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("No channel messages captured"));
    }

    #[tokio::test]
    async fn test_list_chats_with_data() {
        let (_db, repo, tool) = setup().await;
        let m1 = insert_msg("telegram", "-100111", "Dev Group", "Alice", "hello");
        let m2 = insert_msg("telegram", "-100222", "Ops Group", "Bob", "world");
        repo.insert(&m1).await.unwrap();
        repo.insert(&m2).await.unwrap();

        let input = serde_json::json!({"operation": "list_chats"});
        let result = tool.execute(input, &ctx()).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("Known chats (2)"));
        assert!(result.output.contains("Dev Group"));
        assert!(result.output.contains("Ops Group"));
    }

    #[tokio::test]
    async fn test_list_chats_filtered_by_channel() {
        let (_db, repo, tool) = setup().await;
        let m1 = insert_msg("telegram", "-100111", "TG Group", "Alice", "tg");
        let m2 = insert_msg("discord", "DC001", "DC Chan", "Bob", "dc");
        repo.insert(&m1).await.unwrap();
        repo.insert(&m2).await.unwrap();

        let input = serde_json::json!({"operation": "list_chats", "channel": "telegram"});
        let result = tool.execute(input, &ctx()).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("Known chats (1)"));
        assert!(result.output.contains("TG Group"));
        assert!(!result.output.contains("DC Chan"));
    }

    #[tokio::test]
    async fn test_recent_requires_chat_id() {
        let (_db, _repo, tool) = setup().await;
        let input = serde_json::json!({"operation": "recent"});
        let result = tool.execute(input, &ctx()).await.unwrap();
        assert!(!result.success);
        let msg = result.error.as_deref().unwrap_or(&result.output);
        assert!(msg.contains("chat_id"));
    }

    #[tokio::test]
    async fn test_recent_returns_messages() {
        let (_db, repo, tool) = setup().await;
        let m1 = insert_msg("telegram", "-100111", "Group", "Alice", "first message");
        let m2 = insert_msg("telegram", "-100111", "Group", "Bob", "second message");
        repo.insert(&m1).await.unwrap();
        repo.insert(&m2).await.unwrap();

        let input = serde_json::json!({"operation": "recent", "chat_id": "-100111"});
        let result = tool.execute(input, &ctx()).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("first message"));
        assert!(result.output.contains("second message"));
        assert!(result.output.contains("Alice"));
        assert!(result.output.contains("Bob"));
    }

    #[tokio::test]
    async fn test_recent_empty_chat() {
        let (_db, _repo, tool) = setup().await;
        let input = serde_json::json!({"operation": "recent", "chat_id": "-999"});
        let result = tool.execute(input, &ctx()).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("No messages found"));
    }

    #[tokio::test]
    async fn test_recent_with_n_limit() {
        let (_db, repo, tool) = setup().await;
        for i in 0..10 {
            let m = insert_msg("telegram", "-100111", "Group", "Alice", &format!("msg {i}"));
            repo.insert(&m).await.unwrap();
        }

        let input = serde_json::json!({"operation": "recent", "chat_id": "-100111", "n": 3});
        let result = tool.execute(input, &ctx()).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("(3)"));
    }

    #[tokio::test]
    async fn test_search_requires_query() {
        let (_db, _repo, tool) = setup().await;
        let input = serde_json::json!({"operation": "search"});
        let result = tool.execute(input, &ctx()).await.unwrap();
        assert!(!result.success);
        let msg = result.error.as_deref().unwrap_or(&result.output);
        assert!(msg.contains("query"));
    }

    #[tokio::test]
    async fn test_search_finds_messages() {
        let (_db, repo, tool) = setup().await;
        let m1 = insert_msg(
            "telegram",
            "-100111",
            "Group",
            "Alice",
            "deploy failed on prod",
        );
        let m2 = insert_msg("telegram", "-100111", "Group", "Bob", "checking logs now");
        let m3 = insert_msg(
            "slack",
            "C999",
            "General",
            "Carol",
            "deploy succeeded on staging",
        );
        repo.insert(&m1).await.unwrap();
        repo.insert(&m2).await.unwrap();
        repo.insert(&m3).await.unwrap();

        let input = serde_json::json!({"operation": "search", "query": "deploy"});
        let result = tool.execute(input, &ctx()).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("(2)")); // 2 results
        assert!(result.output.contains("Alice"));
        assert!(result.output.contains("Carol"));
    }

    #[tokio::test]
    async fn test_search_with_channel_filter() {
        let (_db, repo, tool) = setup().await;
        let m1 = insert_msg("telegram", "-100111", "Group", "Alice", "error happened");
        let m2 = insert_msg("slack", "C999", "General", "Bob", "error resolved");
        repo.insert(&m1).await.unwrap();
        repo.insert(&m2).await.unwrap();

        let input =
            serde_json::json!({"operation": "search", "query": "error", "channel": "telegram"});
        let result = tool.execute(input, &ctx()).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("(1)"));
        assert!(result.output.contains("Alice"));
        assert!(!result.output.contains("Bob"));
    }

    #[tokio::test]
    async fn test_search_no_match() {
        let (_db, repo, tool) = setup().await;
        let m = insert_msg("telegram", "-100111", "Group", "Alice", "hello");
        repo.insert(&m).await.unwrap();

        let input = serde_json::json!({"operation": "search", "query": "nonexistent"});
        let result = tool.execute(input, &ctx()).await.unwrap();
        assert!(result.success);
        assert!(result.output.contains("No messages matching"));
    }

    #[tokio::test]
    async fn test_unknown_operation() {
        let (_db, _repo, tool) = setup().await;
        let input = serde_json::json!({"operation": "invalid"});
        let result = tool.execute(input, &ctx()).await.unwrap();
        assert!(!result.success);
        let msg = result.error.as_deref().unwrap_or(&result.output);
        assert!(msg.contains("Unknown operation"));
    }
}