aidaemon 0.9.33

A personal AI agent that runs as a background daemon, accessible via Telegram, Slack, or Discord, with tool use, MCP integration, and persistent memory
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
// ==========================================================================
// Minimal context system prompt tests
//
// Memory data (facts, goals, expertise, procedures, episodes, patterns) is
// retrieved on demand via tools, NOT bulk-injected into the system prompt.
// These tests verify the system prompt contains capability descriptions
// instead of raw data.
// ==========================================================================

/// System prompt contains memory capabilities summary instead of bulk data.
#[tokio::test]
async fn test_memory_episodes_injected_into_prompt() {
    let harness = setup_test_agent(MockProvider::new()).await.unwrap();

    harness
        .agent
        .handle_message(
            "ep_session",
            "I have a Rust error",
            None,
            UserRole::Owner,
            ChannelContext::private("test"),
            None,
        )
        .await
        .unwrap();

    let call_log = harness.provider.call_log.lock().await;
    let sys = call_log[0]
        .messages
        .iter()
        .find(|m| m["role"] == "system")
        .unwrap();
    let content = sys["content"].as_str().unwrap();
    // Episodes are no longer injected — memory is on-demand
    assert!(
        !content.contains("Past Sessions"),
        "System prompt should NOT contain bulk episode data"
    );
    assert!(
        content.contains("Your Memory"),
        "System prompt should contain memory capabilities summary"
    );
}

/// Goals are NOT bulk-injected — accessed on demand via scheduled_goals tool.
#[tokio::test]
async fn test_memory_goals_injected_into_prompt() {
    let harness = setup_test_agent(MockProvider::new()).await.unwrap();

    let mut goal = Goal::new_finite(
        "Migrate the database from PostgreSQL to SQLite",
        "goal_session",
    );
    goal.domain = "personal".to_string();
    goal.priority = "high".to_string();
    harness.state.create_goal(&goal).await.unwrap();

    harness
        .agent
        .handle_message(
            "goal_session",
            "what should I work on?",
            None,
            UserRole::Owner,
            ChannelContext::private("test"),
            None,
        )
        .await
        .unwrap();

    let call_log = harness.provider.call_log.lock().await;
    let sys = call_log[0]
        .messages
        .iter()
        .find(|m| m["role"] == "system")
        .unwrap();
    let content = sys["content"].as_str().unwrap();
    assert!(
        !content.contains("PostgreSQL"),
        "Goal descriptions should NOT be bulk-injected into prompt"
    );
    assert!(
        content.contains("scheduled_goals"),
        "System prompt should reference scheduled_goals tool for on-demand access"
    );
}

/// Procedures are NOT bulk-injected — model learns from tool descriptions.
#[tokio::test]
async fn test_memory_procedures_injected_into_prompt() {
    let harness = setup_test_agent(MockProvider::new()).await.unwrap();

    harness
        .agent
        .handle_message(
            "proc_session",
            "deploy release",
            None,
            UserRole::Owner,
            ChannelContext::private("test"),
            None,
        )
        .await
        .unwrap();

    let call_log = harness.provider.call_log.lock().await;
    assert!(!call_log.is_empty(), "Expected at least 1 LLM call");
    let sys = call_log[0]
        .messages
        .iter()
        .find(|m| m.get("role").and_then(|r| r.as_str()) == Some("system"))
        .expect("No system message found");
    let content = sys["content"].as_str().unwrap();
    assert!(
        !content.contains("Known Procedures"),
        "Procedures should NOT be bulk-injected into prompt"
    );
}

/// Error solutions are NOT bulk-injected — model uses tool error messages directly.
#[tokio::test]
async fn test_memory_error_solutions_injected_into_prompt() {
    let harness = setup_test_agent(MockProvider::new()).await.unwrap();

    harness
        .agent
        .handle_message(
            "err_session",
            "connection refused port 5432",
            None,
            UserRole::Owner,
            ChannelContext::private("test"),
            None,
        )
        .await
        .unwrap();

    let call_log = harness.provider.call_log.lock().await;
    let sys = call_log[0]
        .messages
        .iter()
        .find(|m| m["role"] == "system")
        .unwrap();
    let content = sys["content"].as_str().unwrap();
    assert!(
        !content.contains("Error Solutions"),
        "Error solutions should NOT be bulk-injected into prompt"
    );
}

/// Expertise levels are NOT bulk-injected — model adapts from conversation.
#[tokio::test]
async fn test_memory_expertise_injected_into_prompt() {
    let harness = setup_test_agent(MockProvider::new()).await.unwrap();

    harness
        .agent
        .handle_message(
            "exp_session",
            "help me with code",
            None,
            UserRole::Owner,
            ChannelContext::private("test"),
            None,
        )
        .await
        .unwrap();

    let call_log = harness.provider.call_log.lock().await;
    let sys = call_log[0]
        .messages
        .iter()
        .find(|m| m["role"] == "system")
        .unwrap();
    let content = sys["content"].as_str().unwrap();
    assert!(
        !content.contains("Expertise Levels"),
        "Expertise levels should NOT be bulk-injected into prompt"
    );
}

/// Behavior patterns are NOT bulk-injected.
#[tokio::test]
async fn test_memory_behavior_patterns_injected_into_prompt() {
    let harness = setup_test_agent(MockProvider::new()).await.unwrap();

    harness
        .agent
        .handle_message(
            "pat_session",
            "I want to commit",
            None,
            UserRole::Owner,
            ChannelContext::private("test"),
            None,
        )
        .await
        .unwrap();

    let call_log = harness.provider.call_log.lock().await;
    let sys = call_log[0]
        .messages
        .iter()
        .find(|m| m["role"] == "system")
        .unwrap();
    let content = sys["content"].as_str().unwrap();
    assert!(
        !content.contains("Observed Patterns"),
        "Behavior patterns should NOT be bulk-injected into prompt"
    );
}

/// Failure patterns are NOT bulk-injected.
#[tokio::test]
async fn test_memory_failure_patterns_injected_into_prompt() {
    let harness = setup_test_agent(MockProvider::new()).await.unwrap();

    harness
        .agent
        .handle_message(
            "failure_pattern_session",
            "help me debug this command issue",
            None,
            UserRole::Owner,
            ChannelContext::private("test"),
            None,
        )
        .await
        .unwrap();

    let call_log = harness.provider.call_log.lock().await;
    let sys = call_log[0]
        .messages
        .iter()
        .find(|m| m["role"] == "system")
        .unwrap();
    let content = sys["content"].as_str().unwrap();
    assert!(
        !content.contains("Failure Patterns To Avoid"),
        "Failure patterns should NOT be bulk-injected into prompt"
    );
}

/// Failure patterns are also not injected in public channels.
#[tokio::test]
async fn test_memory_failure_patterns_injected_into_public_prompt() {
    let harness = setup_test_agent(MockProvider::new()).await.unwrap();

    harness
        .agent
        .handle_message(
            "public_failure_pattern_session",
            "help me debug this search workflow",
            None,
            UserRole::Owner,
            ChannelContext {
                visibility: ChannelVisibility::Public,
                platform: "test".to_string(),
                channel_name: Some("#eng".to_string()),
                channel_id: Some("test:eng".to_string()),
                sender_name: Some("Alice".to_string()),
                sender_id: None,
                channel_member_names: vec![],
                user_id_map: std::collections::HashMap::new(),
                trusted: false,
            },
            None,
        )
        .await
        .unwrap();

    let call_log = harness.provider.call_log.lock().await;
    let sys = call_log[0]
        .messages
        .iter()
        .find(|m| m["role"] == "system")
        .unwrap();
    let content = sys["content"].as_str().unwrap();
    assert!(
        !content.contains("Failure Patterns To Avoid"),
        "Failure patterns should NOT be bulk-injected into public prompt"
    );
}

/// User profile: communication preferences affect the system prompt.
#[tokio::test]
async fn test_memory_user_profile_affects_prompt() {
    let harness = setup_test_agent(MockProvider::new()).await.unwrap();

    let profile = UserProfile {
        id: 1,
        verbosity_preference: "brief".to_string(),
        explanation_depth: "minimal".to_string(),
        tone_preference: "casual".to_string(),
        emoji_preference: "none".to_string(),
        typical_session_length: Some(10),
        active_hours: None,
        common_workflows: Some(vec!["code review".to_string()]),
        asks_before_acting: true,
        prefers_explanations: false,
        likes_suggestions: true,
        updated_at: Utc::now(),
    };
    harness.state.update_user_profile(&profile).await.unwrap();

    harness
        .agent
        .handle_message(
            "profile_session",
            "hello",
            None,
            UserRole::Owner,
            ChannelContext::private("test"),
            None,
        )
        .await
        .unwrap();

    let call_log = harness.provider.call_log.lock().await;
    let sys = call_log[0]
        .messages
        .iter()
        .find(|m| m["role"] == "system")
        .unwrap();
    let content = sys["content"].as_str().unwrap();
    assert!(
        content.contains("Communication Preferences") && content.contains("brief"),
        "System prompt should include user profile preferences. Tail: ...{}",
        &content[content.len().saturating_sub(800)..]
    );
}

/// Minimal context: system prompt has capability summary + profile, NOT bulk data.
#[tokio::test]
async fn test_full_memory_stack_in_system_prompt() {
    let harness = setup_test_agent(MockProvider::new()).await.unwrap();

    // Seed user profile (this SHOULD still appear)
    let profile = UserProfile {
        id: 1,
        verbosity_preference: "detailed".to_string(),
        explanation_depth: "thorough".to_string(),
        tone_preference: "casual".to_string(),
        emoji_preference: "none".to_string(),
        typical_session_length: Some(30),
        active_hours: None,
        common_workflows: Some(vec!["deployment".to_string()]),
        asks_before_acting: false,
        prefers_explanations: true,
        likes_suggestions: true,
        updated_at: Utc::now(),
    };
    harness.state.update_user_profile(&profile).await.unwrap();

    harness
        .agent
        .handle_message(
            "full_memory",
            "deploy and release",
            None,
            UserRole::Owner,
            ChannelContext::private("test"),
            None,
        )
        .await
        .unwrap();

    let call_log = harness.provider.call_log.lock().await;
    let sys = call_log[0]
        .messages
        .iter()
        .find(|m| m["role"] == "system")
        .unwrap();
    let content = sys["content"].as_str().unwrap();

    // Profile SHOULD be present (stays in every prompt)
    assert!(
        content.contains("Communication Preferences"),
        "User profile should still be injected"
    );

    // Memory capabilities summary SHOULD be present
    assert!(
        content.contains("Your Memory"),
        "Memory capabilities summary should be present"
    );
    assert!(
        content.contains("manage_memories"),
        "Should reference manage_memories tool"
    );

    // Bulk data should NOT be present
    let should_not_contain = vec![
        "Known Procedures",
        "Error Solutions",
        "Expertise Levels",
        "Active Goals",
        "Known Facts",
        "Observed Patterns",
        "Failure Patterns",
        "Trusted Command Patterns",
        "Contextual Suggestions",
        "Relevant Past Sessions",
    ];
    for marker in &should_not_contain {
        assert!(
            !content.contains(marker),
            "System prompt should NOT contain '{}' — memory is on-demand now",
            marker
        );
    }
}

/// Public channels: Global facts are accessible, Private facts are not.
/// Goals, patterns, and profile are DM-only and should NOT appear.
#[tokio::test]
async fn test_public_channel_hides_personal_memory() {
    let harness = setup_test_agent(MockProvider::new()).await.unwrap();

    // Global fact — should appear in public channels (accessible everywhere)
    harness
        .state
        .upsert_fact(
            "personal",
            "name",
            "Alice",
            "user",
            None,
            crate::types::FactPrivacy::Global,
        )
        .await
        .unwrap();

    // Private fact — should NOT appear in public channels
    harness
        .state
        .upsert_fact(
            "preference",
            "hobby",
            "Enjoys photography",
            "user",
            None,
            crate::types::FactPrivacy::Private,
        )
        .await
        .unwrap();

    // Personal goal — DM-only, should NOT appear in public channels
    let mut goal = Goal::new_finite("Learn Japanese", "public_chan");
    goal.domain = "personal".to_string();
    harness.state.create_goal(&goal).await.unwrap();

    // Seed operational memory
    let proc = Procedure {
        id: 0,
        name: "Debug crash".to_string(),
        trigger_pattern: "crash debug segfault".to_string(),
        steps: vec![
            "Check logs".to_string(),
            "Run with RUST_BACKTRACE=1".to_string(),
        ],
        success_count: 5,
        failure_count: 0,
        avg_duration_secs: None,
        last_used_at: None,
        created_at: Utc::now(),
        updated_at: Utc::now(),
    };
    harness.state.upsert_procedure(&proc).await.unwrap();

    // Send in a PUBLIC channel context
    harness
        .agent
        .handle_message(
            "public_chan",
            "my app crashed",
            None,
            UserRole::Owner,
            ChannelContext {
                visibility: ChannelVisibility::Public,
                platform: "slack".to_string(),
                channel_name: Some("general".to_string()),
                channel_id: Some("slack:C_TEST".to_string()),
                sender_name: None,
                sender_id: None,
                channel_member_names: vec![],
                user_id_map: std::collections::HashMap::new(),
                trusted: false,
            },
            None,
        )
        .await
        .unwrap();

    let call_log = harness.provider.call_log.lock().await;
    let sys = call_log[0]
        .messages
        .iter()
        .find(|m| m["role"] == "system")
        .unwrap();
    let content = sys["content"].as_str().unwrap();

    // Private facts should NOT appear in public channels
    assert!(
        !content.contains("Enjoys photography"),
        "Private facts should NOT appear in public channel prompt"
    );
    // Goals are DM-only — should NOT appear in public channels
    assert!(
        !content.contains("Learn Japanese"),
        "Personal goals should NOT appear in public channel prompt"
    );
}

/// Verify that all tool schemas the agent sends to the LLM are compatible
/// with the Google Gemini API. Gemini rejects `$schema` fields anywhere in
/// function declaration parameters. This test catches any tool (built-in or
/// MCP) that introduces `$schema` before it causes a 400 error in production.
#[tokio::test]
async fn test_tool_schemas_gemini_compatible() {
    use serde_json::json;

    let harness = setup_test_agent(MockProvider::new()).await.unwrap();

    // Trigger a normal message so the agent builds tool definitions
    let _response = harness
        .agent
        .handle_message(
            "schema_check",
            "hello",
            None,
            UserRole::Owner,
            ChannelContext::private("test"),
            None,
        )
        .await
        .unwrap();

    // Grab the actual tools sent to the LLM
    let call_log = harness.provider.call_log.lock().await;
    assert!(!call_log.is_empty(), "Expected at least 1 LLM call");
    let tools = &call_log[0].tools;
    assert!(!tools.is_empty(), "Expected tools in the LLM call");

    // Run them through the Gemini convert_tools pipeline
    let gemini = crate::providers::GoogleGenAiProvider::new("fake-key");
    let converted = gemini.convert_tools_for_test(tools, false);
    assert!(converted.is_some(), "convert_tools should return Some");

    // Recursively check no $schema anywhere in the output
    fn assert_no_schema(value: &serde_json::Value, path: &str) {
        match value {
            serde_json::Value::Object(map) => {
                assert!(
                    !map.contains_key("$schema"),
                    "Gemini-incompatible '$schema' found at: {}",
                    path
                );
                for (k, v) in map {
                    assert_no_schema(v, &format!("{}.{}", path, k));
                }
            }
            serde_json::Value::Array(arr) => {
                for (i, v) in arr.iter().enumerate() {
                    assert_no_schema(v, &format!("{}[{}]", path, i));
                }
            }
            _ => {}
        }
    }

    assert_no_schema(&json!(converted.unwrap()), "gemini_tools");
}