pulsehive-db 0.5.0

Embedded database for agentic AI systems — collective memory for multi-agent coordination
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
//! Integration tests for SubstrateProvider trait and PulseDBSubstrate.
//!
//! Tests the async wrapper layer: PulseDBSubstrate → spawn_blocking → PulseDB.
//! Uses External embedding provider (default), so all experiences must provide
//! pre-computed embeddings of the correct dimension (384 for D384).

use futures::StreamExt;

use pulsedb::{
    CollectiveId, Config, ContextRequest, InsightType, NewActivity, NewDerivedInsight,
    NewExperience, NewExperienceRelation, PulseDB, PulseDBSubstrate, RelationType, SearchFilter,
    SubstrateProvider,
};
use tempfile::tempdir;

/// Default embedding dimension for tests (D384).
const DIM: usize = 384;

/// Creates a dummy embedding of the correct dimension.
fn dummy_embedding() -> Vec<f32> {
    vec![0.1; DIM]
}

/// Creates a distinct embedding seeded by a value (for search ordering tests).
///
/// Uses two components so that different seeds produce genuinely different
/// directions after normalization (a single-component vector always normalizes
/// to the same unit vector regardless of seed).
fn seeded_embedding(seed: f32) -> Vec<f32> {
    let mut emb = vec![0.0; DIM];
    emb[0] = seed;
    emb[1] = 1.0 - seed; // second component ensures distinct direction
                         // Normalize to unit length for cosine similarity
    let norm = emb.iter().map(|x| x * x).sum::<f32>().sqrt();
    if norm > 0.0 {
        emb.iter_mut().for_each(|x| *x /= norm);
    }
    emb
}

/// Helper: open DB, create a collective, return substrate + collective ID.
fn setup() -> (PulseDBSubstrate, CollectiveId, tempfile::TempDir) {
    let dir = tempdir().unwrap();
    let path = dir.path().join("test.db");
    let db = PulseDB::open(&path, Config::default()).unwrap();
    let cid = db.create_collective("test-collective").unwrap();
    let substrate = PulseDBSubstrate::from_db(db);
    (substrate, cid, dir)
}

/// Helper to build a minimal valid NewExperience for a given collective.
fn minimal_experience(collective_id: CollectiveId) -> NewExperience {
    NewExperience {
        collective_id,
        content: "Always validate user input before processing".to_string(),
        embedding: Some(dummy_embedding()),
        ..Default::default()
    }
}

// ============================================================================
// Experience operations
// ============================================================================

#[tokio::test]
async fn test_store_and_get_experience() {
    let (substrate, cid, _dir) = setup();

    let exp_id = substrate
        .store_experience(minimal_experience(cid))
        .await
        .unwrap();

    let retrieved = substrate.get_experience(exp_id).await.unwrap();
    assert!(retrieved.is_some());
    let exp = retrieved.unwrap();
    assert_eq!(exp.id, exp_id);
    assert_eq!(exp.content, "Always validate user input before processing");
    assert_eq!(exp.collective_id, cid);
}

#[tokio::test]
async fn test_get_experience_not_found() {
    let (substrate, _cid, _dir) = setup();

    let fake_id = pulsedb::ExperienceId::new();
    let result = substrate.get_experience(fake_id).await.unwrap();
    assert!(result.is_none());
}

// ============================================================================
// Search operations
// ============================================================================

#[tokio::test]
async fn test_search_similar_returns_tuples() {
    let (substrate, cid, _dir) = setup();

    let emb_a = seeded_embedding(1.0);
    let emb_b = seeded_embedding(2.0);

    substrate
        .store_experience(NewExperience {
            collective_id: cid,
            content: "Experience A".to_string(),
            embedding: Some(emb_a.clone()),
            ..Default::default()
        })
        .await
        .unwrap();

    substrate
        .store_experience(NewExperience {
            collective_id: cid,
            content: "Experience B".to_string(),
            embedding: Some(emb_b),
            ..Default::default()
        })
        .await
        .unwrap();

    // Search with emb_a — Experience A should be most similar
    let results = substrate.search_similar(cid, &emb_a, 10).await.unwrap();
    assert_eq!(results.len(), 2);

    // Verify tuple shape: (Experience, f32)
    let (exp, score) = &results[0];
    assert_eq!(exp.content, "Experience A");
    assert!(*score > 0.0 && *score <= 1.0);

    // Results should be ordered by similarity descending
    assert!(results[0].1 >= results[1].1);
}

#[tokio::test]
async fn test_search_similar_empty_collective() {
    let (substrate, cid, _dir) = setup();
    let results = substrate
        .search_similar(cid, &dummy_embedding(), 10)
        .await
        .unwrap();
    assert!(results.is_empty());
}

#[tokio::test]
async fn test_get_recent() {
    let (substrate, cid, _dir) = setup();

    for i in 0..3 {
        substrate
            .store_experience(NewExperience {
                collective_id: cid,
                content: format!("Experience {i}"),
                embedding: Some(dummy_embedding()),
                ..Default::default()
            })
            .await
            .unwrap();
    }

    let recent = substrate.get_recent(cid, 2).await.unwrap();
    assert_eq!(recent.len(), 2);
    // Most recent first
    assert_eq!(recent[0].content, "Experience 2");
    assert_eq!(recent[1].content, "Experience 1");
}

// ============================================================================
// Relation operations
// ============================================================================

#[tokio::test]
async fn test_store_and_get_relation() {
    let (substrate, cid, _dir) = setup();

    let exp_a = substrate
        .store_experience(NewExperience {
            collective_id: cid,
            content: "Source experience".to_string(),
            embedding: Some(dummy_embedding()),
            ..Default::default()
        })
        .await
        .unwrap();

    let exp_b = substrate
        .store_experience(NewExperience {
            collective_id: cid,
            content: "Target experience".to_string(),
            embedding: Some(dummy_embedding()),
            ..Default::default()
        })
        .await
        .unwrap();

    let _rel_id = substrate
        .store_relation(NewExperienceRelation {
            source_id: exp_a,
            target_id: exp_b,
            relation_type: RelationType::Supports,
            strength: 0.9,
            metadata: None,
        })
        .await
        .unwrap();

    // get_related from source should find target
    let related = substrate.get_related(exp_a).await.unwrap();
    assert_eq!(related.len(), 1);
    assert_eq!(related[0].0.id, exp_b);
    assert_eq!(related[0].1.relation_type, RelationType::Supports);
}

#[tokio::test]
async fn test_get_related_returns_both_directions() {
    let (substrate, cid, _dir) = setup();

    let exp_a = substrate
        .store_experience(NewExperience {
            collective_id: cid,
            content: "A".to_string(),
            embedding: Some(dummy_embedding()),
            ..Default::default()
        })
        .await
        .unwrap();

    let exp_b = substrate
        .store_experience(NewExperience {
            collective_id: cid,
            content: "B".to_string(),
            embedding: Some(dummy_embedding()),
            ..Default::default()
        })
        .await
        .unwrap();

    // A → B (Supports)
    substrate
        .store_relation(NewExperienceRelation {
            source_id: exp_a,
            target_id: exp_b,
            relation_type: RelationType::Supports,
            strength: 0.8,
            metadata: None,
        })
        .await
        .unwrap();

    // Query from B — should find A via incoming relation
    let related = substrate.get_related(exp_b).await.unwrap();
    assert_eq!(related.len(), 1);
    assert_eq!(related[0].0.id, exp_a);
}

// ============================================================================
// Insight operations
// ============================================================================

#[tokio::test]
async fn test_store_and_search_insights() {
    let (substrate, cid, _dir) = setup();

    // Need source experiences for insight validation
    let exp_id = substrate
        .store_experience(NewExperience {
            collective_id: cid,
            content: "Source experience".to_string(),
            embedding: Some(dummy_embedding()),
            ..Default::default()
        })
        .await
        .unwrap();

    let emb = seeded_embedding(1.0);

    substrate
        .store_insight(NewDerivedInsight {
            collective_id: cid,
            content: "Derived pattern insight".to_string(),
            embedding: Some(emb.clone()),
            source_experience_ids: vec![exp_id],
            insight_type: InsightType::Pattern,
            confidence: 0.8,
            domain: vec![],
        })
        .await
        .unwrap();

    // Search with same embedding
    let results = substrate.get_insights(cid, &emb, 5).await.unwrap();
    assert_eq!(results.len(), 1);

    let (insight, score) = &results[0];
    assert_eq!(insight.content, "Derived pattern insight");
    assert!(*score > 0.0 && *score <= 1.0);
}

// ============================================================================
// Activity operations
// ============================================================================

#[tokio::test]
async fn test_get_activities() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("test.db");
    let db = PulseDB::open(&path, Config::default()).unwrap();
    let cid = db.create_collective("test-collective").unwrap();

    // Register activity via sync API (SubstrateProvider doesn't expose register)
    db.register_activity(NewActivity {
        agent_id: "claude-opus".to_string(),
        collective_id: cid,
        current_task: Some("Testing".to_string()),
        context_summary: None,
    })
    .unwrap();

    let substrate = PulseDBSubstrate::from_db(db);
    let activities = substrate.get_activities(cid).await.unwrap();
    assert_eq!(activities.len(), 1);
    assert_eq!(activities[0].agent_id, "claude-opus");
}

// ============================================================================
// Context candidates
// ============================================================================

#[tokio::test]
async fn test_get_context_candidates() {
    let (substrate, cid, _dir) = setup();

    let emb = dummy_embedding();

    substrate
        .store_experience(NewExperience {
            collective_id: cid,
            content: "Test experience for context".to_string(),
            embedding: Some(emb.clone()),
            importance: 0.8,
            ..Default::default()
        })
        .await
        .unwrap();

    let candidates = substrate
        .get_context_candidates(ContextRequest {
            collective_id: cid,
            query_embedding: emb,
            max_similar: 10,
            max_recent: 5,
            include_insights: false,
            include_relations: false,
            include_active_agents: false,
            filter: SearchFilter::default(),
            recall_weights: None,
        })
        .await
        .unwrap();

    assert!(!candidates.similar_experiences.is_empty());
    assert!(!candidates.recent_experiences.is_empty());
}

// ============================================================================
// Watch
// ============================================================================

#[tokio::test]
async fn test_watch_delivers_events() {
    let (substrate, cid, _dir) = setup();

    let mut stream = substrate.watch(cid).await.unwrap();

    // Store an experience — should trigger a Created event
    let exp_id = substrate
        .store_experience(minimal_experience(cid))
        .await
        .unwrap();

    let event = tokio::time::timeout(std::time::Duration::from_secs(1), stream.as_mut().next())
        .await
        .expect("timed out waiting for watch event")
        .expect("stream ended unexpectedly");

    assert_eq!(event.experience_id, exp_id);
    assert_eq!(event.collective_id, cid);
    assert_eq!(event.event_type, pulsedb::WatchEventType::Created);
}

// ============================================================================
// Trait object safety
// ============================================================================

#[tokio::test]
async fn test_trait_object_safety() {
    let (substrate, cid, _dir) = setup();

    // This must compile — consumers hold Box<dyn SubstrateProvider>
    let provider: Box<dyn SubstrateProvider> = Box::new(substrate);

    let exp_id = provider
        .store_experience(minimal_experience(cid))
        .await
        .unwrap();

    let retrieved = provider.get_experience(exp_id).await.unwrap();
    assert!(retrieved.is_some());
}

#[tokio::test]
async fn test_reinforce_and_energy_through_trait_object() {
    let (substrate, cid, _dir) = setup();
    let provider: Box<dyn SubstrateProvider> = Box::new(substrate);

    let exp_id = provider
        .store_experience(minimal_experience(cid))
        .await
        .unwrap();

    let before = provider.energy(exp_id).await.unwrap();
    let count = provider.reinforce_experience(exp_id).await.unwrap();
    let after = provider.energy(exp_id).await.unwrap();

    let exp = provider.get_experience(exp_id).await.unwrap().unwrap();
    assert_eq!(count, 1);
    assert_eq!(exp.applications(), 1);
    assert!((0.0..=1.0).contains(&after));
    assert!(after >= before);
}

// ============================================================================
// Clone & concurrency
// ============================================================================

#[tokio::test]
async fn test_clone_and_concurrent_operations() {
    let (substrate, cid, _dir) = setup();

    let mut handles = Vec::new();

    for i in 0..5 {
        let s = substrate.clone();
        handles.push(tokio::spawn(async move {
            s.store_experience(NewExperience {
                collective_id: cid,
                content: format!("Concurrent experience {i}"),
                embedding: Some(vec![0.1; DIM]),
                ..Default::default()
            })
            .await
            .unwrap()
        }));
    }

    let mut exp_ids = Vec::new();
    for handle in handles {
        exp_ids.push(handle.await.unwrap());
    }

    // All 5 should be stored successfully with unique IDs
    assert_eq!(exp_ids.len(), 5);
    // Verify uniqueness via HashSet instead of sort (ExperienceId doesn't impl Ord)
    let unique: std::collections::HashSet<_> = exp_ids.iter().collect();
    assert_eq!(unique.len(), 5);
}

// ============================================================================
// Collective lifecycle (SubstrateProvider methods)
// ============================================================================

#[tokio::test]
async fn test_substrate_create_collective() {
    let dir = tempdir().unwrap();
    let db = PulseDB::open(dir.path().join("test.db"), Config::default()).unwrap();
    let substrate = PulseDBSubstrate::from_db(db);
    let provider: Box<dyn SubstrateProvider> = Box::new(substrate);

    let cid = provider.create_collective("test-project").await.unwrap();

    // Verify collective exists by listing
    let collectives = provider.list_collectives().await.unwrap();
    assert_eq!(collectives.len(), 1);
    assert_eq!(collectives[0].id, cid);
    assert_eq!(collectives[0].name, "test-project");
}

#[tokio::test]
async fn test_substrate_get_or_create_collective_new() {
    let dir = tempdir().unwrap();
    let db = PulseDB::open(dir.path().join("test.db"), Config::default()).unwrap();
    let substrate = PulseDBSubstrate::from_db(db);
    let provider: Box<dyn SubstrateProvider> = Box::new(substrate);

    // First call creates
    let cid = provider
        .get_or_create_collective("my-project")
        .await
        .unwrap();

    let collectives = provider.list_collectives().await.unwrap();
    assert_eq!(collectives.len(), 1);
    assert_eq!(collectives[0].id, cid);
}

#[tokio::test]
async fn test_substrate_get_or_create_collective_idempotent() {
    let dir = tempdir().unwrap();
    let db = PulseDB::open(dir.path().join("test.db"), Config::default()).unwrap();
    let substrate = PulseDBSubstrate::from_db(db);
    let provider: Box<dyn SubstrateProvider> = Box::new(substrate);

    // Call twice with same name
    let cid1 = provider
        .get_or_create_collective("my-project")
        .await
        .unwrap();
    let cid2 = provider
        .get_or_create_collective("my-project")
        .await
        .unwrap();

    // Same ID returned
    assert_eq!(cid1, cid2);

    // Only one collective exists
    let collectives = provider.list_collectives().await.unwrap();
    assert_eq!(collectives.len(), 1);
}

#[tokio::test]
async fn test_substrate_list_collectives_multiple() {
    let dir = tempdir().unwrap();
    let db = PulseDB::open(dir.path().join("test.db"), Config::default()).unwrap();
    let substrate = PulseDBSubstrate::from_db(db);
    let provider: Box<dyn SubstrateProvider> = Box::new(substrate);

    provider.create_collective("alpha").await.unwrap();
    provider.create_collective("beta").await.unwrap();
    provider.create_collective("gamma").await.unwrap();

    let collectives = provider.list_collectives().await.unwrap();
    assert_eq!(collectives.len(), 3);

    let names: Vec<&str> = collectives.iter().map(|c| c.name.as_str()).collect();
    assert!(names.contains(&"alpha"));
    assert!(names.contains(&"beta"));
    assert!(names.contains(&"gamma"));
}

#[tokio::test]
async fn test_substrate_get_or_create_then_store_experience() {
    let dir = tempdir().unwrap();
    let db = PulseDB::open(dir.path().join("test.db"), Config::default()).unwrap();
    let substrate = PulseDBSubstrate::from_db(db);
    let provider: Box<dyn SubstrateProvider> = Box::new(substrate);

    // Create collective through trait, then store experience
    let cid = provider
        .get_or_create_collective("my-project")
        .await
        .unwrap();

    let exp_id = provider
        .store_experience(NewExperience {
            collective_id: cid,
            content: "Test experience through substrate".to_string(),
            embedding: Some(dummy_embedding()),
            ..Default::default()
        })
        .await
        .unwrap();

    let exp = provider.get_experience(exp_id).await.unwrap().unwrap();
    assert_eq!(exp.collective_id, cid);
    assert_eq!(exp.content, "Test experience through substrate");
}