allsource-core 0.19.1

High-performance event store core built in Rust
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! Recall API — `index()` and `context()` methods for the Prime facade.
//!
//! Provides the user-facing agent memory API that combines compressed index,
//! vector search results, and graph context into a single retrieval call.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

use super::{
    compressor::IndexCompressor,
    index_builder::{build_heuristic_index, build_raw_summary},
    types::{CompressedIndex, ContextTier, IndexConfig, LlmBackend, RankedMemory, RecallContext},
};
use crate::{
    application::services::projection::Projection,
    prime::{
        projections::{
            AdjacencyListProjection, CrossDomainProjection, DomainIndexProjection,
            GraphStatsProjection, NodeStateProjection,
        },
        types::{Node, PrimeStats},
    },
};

// =============================================================================
// Query types
// =============================================================================

/// Query parameters for `recall.context()`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecallContextQuery {
    /// Natural language query string.
    pub query: String,
    /// Agent ID for scoping.
    pub agent_id: Option<String>,
    /// Max number of vector results (default: 5).
    pub top_k: usize,
    /// Time-travel: only consider knowledge that existed at this timestamp.
    pub as_of: Option<DateTime<Utc>>,
    /// Whether to include the compressed index excerpt in the response.
    pub include_index: bool,
    /// Max total tokens in the response (truncate if exceeded).
    pub max_tokens: Option<usize>,
    /// Retrieval tier (default: L2 — full hybrid recall).
    pub tier: ContextTier,
    /// Conversation ID for L1 scoping. Ignored for L0/L2.
    pub conversation_id: Option<String>,
}

impl Default for RecallContextQuery {
    fn default() -> Self {
        Self {
            query: String::new(),
            agent_id: None,
            top_k: 5,
            as_of: None,
            include_index: true,
            max_tokens: None,
            tier: ContextTier::default(),
            conversation_id: None,
        }
    }
}

// =============================================================================
// Recall Dependencies
// =============================================================================

/// Bundled projection dependencies for the recall engine.
///
/// Groups the projections needed for tiered context retrieval into a single
/// struct, keeping the `RecallEngine` constructor clean as dependencies grow.
pub struct RecallDeps {
    pub domain_index: Arc<DomainIndexProjection>,
    pub cross_domain: Arc<CrossDomainProjection>,
    pub node_state: Option<Arc<NodeStateProjection>>,
    pub adjacency: Option<Arc<AdjacencyListProjection>>,
    pub graph_stats: Option<Arc<GraphStatsProjection>>,
}

// =============================================================================
// Recall Engine
// =============================================================================

/// Agent memory engine that wraps Prime's projections to provide
/// `index()` and `context()` retrieval methods.
///
/// Supports tiered retrieval via [`ContextTier`]:
/// - **L0**: stats only (~100–200 tokens)
/// - **L1**: recent conversation nodes + 1-hop edges (~500–1500 tokens)
/// - **L2**: full hybrid recall with compressed index (~2000–5000 tokens)
pub struct RecallEngine {
    domain_index: Arc<DomainIndexProjection>,
    cross_domain: Arc<CrossDomainProjection>,
    node_state: Option<Arc<NodeStateProjection>>,
    adjacency: Option<Arc<AdjacencyListProjection>>,
    graph_stats: Option<Arc<GraphStatsProjection>>,
    compressor: IndexCompressor,
}

impl RecallEngine {
    /// Create a new Recall engine with the given index configuration.
    ///
    /// Convenience constructor that creates default projections and an
    /// `IndexCompressor` configured from `IndexConfig`. If `IndexConfig`
    /// has an `llm_endpoint`, an `OllamaBackend` is created automatically.
    ///
    /// Note: This constructor creates standalone projections. For L0/L1 tier
    /// support with shared projections from Prime, use [`RecallEngine::with_deps`].
    pub fn new(config: &IndexConfig) -> Self {
        let llm_backend: Option<Box<dyn LlmBackend>> =
            if let Some(ref endpoint) = config.llm_endpoint {
                let model = config
                    .llm_model
                    .clone()
                    .unwrap_or_else(|| "mistral".to_string());
                Some(Box::new(super::ollama::OllamaBackend::new(
                    endpoint.clone(),
                    model,
                )))
            } else {
                None
            };

        Self {
            domain_index: Arc::new(DomainIndexProjection::new()),
            cross_domain: Arc::new(CrossDomainProjection::new()),
            node_state: None,
            adjacency: None,
            graph_stats: None,
            compressor: IndexCompressor::new(
                llm_backend,
                config.refresh_interval_events,
                config.refresh_interval_seconds,
            ),
        }
    }

    /// Create a Recall engine with shared projection dependencies from Prime.
    ///
    /// This is the preferred constructor when Prime owns the projections.
    /// Enables L0 (stats) and L1 (conversation context) tiers.
    pub fn with_deps(deps: RecallDeps, config: &IndexConfig) -> Self {
        let llm_backend: Option<Box<dyn LlmBackend>> =
            if let Some(ref endpoint) = config.llm_endpoint {
                let model = config
                    .llm_model
                    .clone()
                    .unwrap_or_else(|| "mistral".to_string());
                Some(Box::new(super::ollama::OllamaBackend::new(
                    endpoint.clone(),
                    model,
                )))
            } else {
                None
            };

        Self {
            domain_index: deps.domain_index,
            cross_domain: deps.cross_domain,
            node_state: deps.node_state,
            adjacency: deps.adjacency,
            graph_stats: deps.graph_stats,
            compressor: IndexCompressor::new(
                llm_backend,
                config.refresh_interval_events,
                config.refresh_interval_seconds,
            ),
        }
    }

    /// Create with injected dependencies (for testing and flexibility).
    pub fn with_dependencies(
        domain_index: Arc<DomainIndexProjection>,
        cross_domain: Arc<CrossDomainProjection>,
        compressor: IndexCompressor,
    ) -> Self {
        Self {
            domain_index,
            cross_domain,
            node_state: None,
            adjacency: None,
            graph_stats: None,
            compressor,
        }
    }

    /// Get the current compressed index.
    ///
    /// Generates on first call, cached thereafter (respecting refresh thresholds).
    pub async fn index(&self) -> CompressedIndex {
        let summary = build_raw_summary(&self.domain_index, &self.cross_domain);
        let heuristic = build_heuristic_index(&summary);
        let event_count = summary.total_nodes as u64 + summary.total_edges as u64;

        self.compressor
            .compress(&summary, event_count, &heuristic)
            .await
    }

    /// Combined retrieval dispatched by tier.
    ///
    /// - `L0`: stats only — no index generation, no vector search.
    /// - `L1`: stats + recent conversation nodes + 1-hop edges.
    /// - `L2`: full hybrid recall (compressed index + vectors + graph expansion).
    pub async fn context(&self, query: RecallContextQuery) -> RecallContext {
        match query.tier {
            ContextTier::L0 => self.context_l0(&query),
            ContextTier::L1 => self.context_l1(&query),
            ContextTier::L2 => self.context_l2(&query).await,
        }
    }

    /// L0: stats-only retrieval. No I/O, no compression.
    fn context_l0(&self, _query: &RecallContextQuery) -> RecallContext {
        let stats = self.build_stats();
        let stats_json = serde_json::to_string(&stats).unwrap_or_default();
        let token_count = super::types::estimate_tokens(&stats_json);

        RecallContext {
            index: String::new(),
            vectors: Vec::new(),
            nodes: Vec::new(),
            edges: Vec::new(),
            stats: Some(stats),
            tier: ContextTier::L0,
            token_count,
        }
    }

    /// L1: conversation-scoped recent context.
    ///
    /// Returns L0 stats + recent nodes + their 1-hop edges.
    /// If `conversation_id` is set, filters to nodes from that conversation.
    /// Without `conversation_id`, returns the most recent nodes across all data.
    fn context_l1(&self, query: &RecallContextQuery) -> RecallContext {
        let stats = self.build_stats();
        let mut nodes: Vec<Node> = Vec::new();
        let mut edges: Vec<crate::prime::types::Edge> = Vec::new();
        let mut token_count = 0usize;

        // Get recent nodes from node_state projection
        if let Some(ref node_state) = self.node_state {
            let all_nodes = node_state.all_nodes();

            // If conversation_id is provided, filter nodes that have matching
            // conversation metadata. Otherwise, take the most recent N nodes.
            let mut candidate_nodes: Vec<Node> = if let Some(ref conv_id) = query.conversation_id {
                all_nodes
                    .into_iter()
                    .filter(|n| {
                        n.properties
                            .get("conversation_id")
                            .and_then(|v| v.as_str())
                            .is_some_and(|id| id == conv_id)
                    })
                    .collect()
            } else {
                all_nodes
            };

            // Sort by updated_at descending, take most recent 20
            candidate_nodes.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
            candidate_nodes.truncate(20);

            // Expand 1-hop outgoing edges from these nodes
            if let Some(ref adjacency) = self.adjacency {
                for node in &candidate_nodes {
                    // entity_id format is "node:{type}:{id}", but adjacency
                    // keys use the raw source/target from edge events (node IDs).
                    let adj_entries = adjacency.outgoing(node.id.as_str());
                    for adj in &adj_entries {
                        // Resolve peer node if available
                        // Try both raw id and entity_id formats
                        let peer_node = node_state.get_node(&adj.peer);
                        if let Some(target) = peer_node
                            && !nodes.iter().any(|n| n.id == target.id)
                            && !candidate_nodes.iter().any(|n| n.id == target.id)
                        {
                            nodes.push(target);
                        }
                        edges.push(crate::prime::types::Edge {
                            id: crate::prime::types::EdgeId::new(&adj.edge_id),
                            source: node.id.clone(),
                            target: crate::prime::types::NodeId::new(&adj.peer),
                            relation: adj.relation.clone(),
                            properties: None,
                            weight: adj.weight,
                            deleted: false,
                            created_at: Utc::now(),
                        });
                    }
                }
            }

            // Add the candidate nodes themselves
            nodes.splice(0..0, candidate_nodes);
        }

        // Estimate token count
        let stats_json = serde_json::to_string(&stats).unwrap_or_default();
        token_count += super::types::estimate_tokens(&stats_json);
        for node in &nodes {
            let node_json = serde_json::to_string(&node).unwrap_or_default();
            token_count += super::types::estimate_tokens(&node_json);
        }

        // Enforce max_tokens: drop oldest nodes first
        if let Some(max) = query.max_tokens {
            while token_count > max && nodes.len() > 1 {
                nodes.pop(); // remove oldest (they're sorted recent-first)
                token_count = super::types::estimate_tokens(&stats_json);
                for node in &nodes {
                    let nj = serde_json::to_string(&node).unwrap_or_default();
                    token_count += super::types::estimate_tokens(&nj);
                }
            }
        }

        RecallContext {
            index: String::new(),
            vectors: Vec::new(),
            nodes,
            edges,
            stats: Some(stats),
            tier: ContextTier::L1,
            token_count,
        }
    }

    /// L2: full hybrid recall (existing behavior).
    async fn context_l2(&self, query: &RecallContextQuery) -> RecallContext {
        let mut index_text = String::new();
        let mut token_count = 0usize;

        // Include compressed index if requested
        if query.include_index {
            let idx = self.index().await;
            index_text = idx.markdown;
            token_count += idx.token_count;
        }

        // Truncate if max_tokens is set and exceeded
        if let Some(max) = query.max_tokens
            && token_count > max
        {
            let target_words = max * 10 / 13; // inverse of words * 1.3
            let truncated: String = index_text
                .split_whitespace()
                .take(target_words)
                .collect::<Vec<_>>()
                .join(" ");
            index_text = truncated + "\n...(truncated)";
            token_count = max;
        }

        // TODO: vector search integration (requires prime-vectors feature)
        let vectors: Vec<RankedMemory> = Vec::new();
        let nodes: Vec<Node> = Vec::new();

        RecallContext {
            index: index_text,
            vectors,
            nodes,
            edges: Vec::new(),
            stats: None,
            tier: ContextTier::L2,
            token_count,
        }
    }

    /// Build stats from graph_stats projection or fall back to domain counts.
    fn build_stats(&self) -> PrimeStats {
        if let Some(ref gs) = self.graph_stats {
            gs.stats()
        } else {
            // Fallback: derive minimal stats from domain_index
            let domain_counts = self.domain_index.domain_counts();
            let total_nodes: usize = domain_counts.iter().map(|(_, c)| c).sum();
            PrimeStats {
                total_nodes,
                total_edges: 0,
                nodes_by_type: std::collections::HashMap::new(),
                edges_by_relation: std::collections::HashMap::new(),
                deleted_nodes: 0,
                deleted_edges: 0,
                event_count: 0,
            }
        }
    }

    /// Get all known domains.
    pub fn domains(&self) -> Vec<String> {
        self.domain_index.domains()
    }

    /// Get cross-domain links.
    pub fn cross_domain_links(
        &self,
    ) -> Vec<crate::prime::projections::cross_domain::CrossDomainLink> {
        self.cross_domain.cross_domain_links()
    }

    /// Force regeneration of the compressed index.
    pub async fn refresh_index(&self) -> CompressedIndex {
        self.compressor.invalidate_cache();
        self.index().await
    }

    /// Return all projections as trait objects for registration with a Prime/Core instance.
    pub fn projections(&self) -> Vec<Arc<dyn Projection>> {
        vec![
            Arc::clone(&self.domain_index) as Arc<dyn Projection>,
            Arc::clone(&self.cross_domain) as Arc<dyn Projection>,
        ]
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        application::services::projection::Projection,
        domain::entities::Event,
        prime::{projections::GraphStatsProjection, types::event_types},
    };
    use uuid::Uuid;

    fn make_node(node_id: &str, node_type: &str, domain: &str, name: &str) -> Event {
        Event::reconstruct_from_strings(
            Uuid::new_v4(),
            event_types::NODE_CREATED.to_string(),
            format!("node:{node_type}:{node_id}"),
            "default".to_string(),
            serde_json::json!({
                "node_id": node_id,
                "node_type": node_type,
                "domain": domain,
                "properties": {"name": name}
            }),
            Utc::now(),
            None,
            1,
        )
    }

    fn make_edge(edge_id: &str, source: &str, target: &str, relation: &str) -> Event {
        Event::reconstruct_from_strings(
            Uuid::new_v4(),
            event_types::EDGE_CREATED.to_string(),
            format!("edge:{edge_id}"),
            "default".to_string(),
            serde_json::json!({
                "edge_id": edge_id,
                "source": source,
                "target": target,
                "relation": relation,
            }),
            Utc::now(),
            None,
            1,
        )
    }

    fn seed_engine() -> RecallEngine {
        let engine = RecallEngine::new(&IndexConfig::default());

        let events = vec![
            make_node("n1", "metric", "revenue", "Q3 Revenue"),
            make_node("n2", "metric", "revenue", "Churn Rate"),
            make_node("n3", "service", "engineering", "Core API"),
            make_node("n4", "feature", "product", "Dark Mode"),
            make_edge("e1", "n1", "n3", "impacts"),
            make_edge("e2", "n4", "n3", "depends_on"),
        ];

        // Process events through the Arc'd projections
        let projections = engine.projections();
        for event in &events {
            for proj in &projections {
                proj.process(event).unwrap();
            }
        }

        engine
    }

    #[tokio::test]
    async fn test_index_returns_compressed_index() {
        let engine = seed_engine();
        let index = engine.index().await;

        assert!(index.markdown.contains("revenue"));
        assert!(index.markdown.contains("engineering"));
        assert!(index.token_count > 0);
        assert!(!index.domains.is_empty());
    }

    #[tokio::test]
    async fn test_context_with_include_index() {
        let engine = seed_engine();
        let query = RecallContextQuery {
            query: "How does revenue relate to engineering?".to_string(),
            include_index: true,
            ..Default::default()
        };

        let ctx = engine.context(query).await;

        assert!(!ctx.index.is_empty());
        assert!(ctx.token_count > 0);
        assert_eq!(ctx.tier, ContextTier::L2);
    }

    #[tokio::test]
    async fn test_context_without_index() {
        let engine = seed_engine();
        let query = RecallContextQuery {
            query: "test".to_string(),
            include_index: false,
            ..Default::default()
        };

        let ctx = engine.context(query).await;

        assert!(ctx.index.is_empty());
        assert_eq!(ctx.token_count, 0);
        assert_eq!(ctx.tier, ContextTier::L2);
    }

    #[tokio::test]
    async fn test_context_with_max_tokens_truncates() {
        let engine = seed_engine();
        let query = RecallContextQuery {
            query: "test".to_string(),
            include_index: true,
            max_tokens: Some(10),
            ..Default::default()
        };

        let ctx = engine.context(query).await;

        assert!(ctx.token_count <= 10);
        assert!(ctx.index.contains("truncated"));
    }

    // ─── Tier-specific tests ────────────────────────────────────────

    #[tokio::test]
    async fn test_l0_returns_stats_only() {
        let engine = seed_engine();
        let query = RecallContextQuery {
            query: String::new(),
            tier: ContextTier::L0,
            ..Default::default()
        };

        let ctx = engine.context(query).await;

        assert_eq!(ctx.tier, ContextTier::L0);
        assert!(ctx.index.is_empty(), "L0 should not generate index");
        assert!(ctx.vectors.is_empty(), "L0 should not run vector search");
        assert!(ctx.nodes.is_empty(), "L0 should not return graph nodes");
        assert!(ctx.stats.is_some(), "L0 should return stats");
        assert!(ctx.token_count > 0, "L0 should have non-zero token count");
        assert!(ctx.token_count < 300, "L0 should be under 300 tokens");
    }

    #[tokio::test]
    async fn test_l1_returns_recent_nodes() {
        // Build engine with full deps for L1 support
        let node_state = Arc::new(NodeStateProjection::new("prime.node_state"));
        let adjacency = Arc::new(AdjacencyListProjection::forward("prime.adjacency"));
        let graph_stats = Arc::new(GraphStatsProjection::new("prime.graph_stats"));
        let domain_index = Arc::new(DomainIndexProjection::new());
        let cross_domain = Arc::new(CrossDomainProjection::new());
        let compressor = IndexCompressor::new(None, 100, 300);

        let engine = RecallEngine {
            domain_index: domain_index.clone(),
            cross_domain: cross_domain.clone(),
            node_state: Some(node_state.clone()),
            adjacency: Some(adjacency.clone()),
            graph_stats: Some(graph_stats.clone()),
            compressor,
        };

        // Seed data through all projections
        let events = vec![
            make_node("n1", "metric", "revenue", "Q3 Revenue"),
            make_node("n2", "metric", "revenue", "Churn Rate"),
            make_node("n3", "service", "engineering", "Core API"),
        ];
        let all_projections: Vec<Arc<dyn Projection>> = vec![
            node_state.clone(),
            adjacency.clone(),
            graph_stats.clone(),
            domain_index.clone(),
            cross_domain.clone(),
        ];
        for event in &events {
            for proj in &all_projections {
                proj.process(event).unwrap();
            }
        }

        let query = RecallContextQuery {
            query: "test".to_string(),
            tier: ContextTier::L1,
            ..Default::default()
        };

        let ctx = engine.context(query).await;

        assert_eq!(ctx.tier, ContextTier::L1);
        assert!(ctx.index.is_empty(), "L1 should not generate index");
        assert!(ctx.vectors.is_empty(), "L1 should not run vector search");
        assert!(ctx.stats.is_some(), "L1 should return stats");
        assert!(!ctx.nodes.is_empty(), "L1 should return recent nodes");
    }

    #[tokio::test]
    async fn test_l0_cheaper_than_l2() {
        let engine = seed_engine();

        let l0_ctx = engine
            .context(RecallContextQuery {
                tier: ContextTier::L0,
                ..Default::default()
            })
            .await;
        let l2_ctx = engine
            .context(RecallContextQuery {
                include_index: true,
                ..Default::default()
            })
            .await;

        assert!(
            l0_ctx.token_count < l2_ctx.token_count,
            "L0 ({}) should cost fewer tokens than L2 ({})",
            l0_ctx.token_count,
            l2_ctx.token_count
        );
    }

    #[tokio::test]
    async fn test_refresh_index_regenerates() {
        let engine = seed_engine();

        let idx1 = engine.index().await;
        let idx2 = engine.index().await;
        // Should be cached (same event count)
        assert_eq!(idx1.markdown, idx2.markdown);

        // Force refresh
        let idx3 = engine.refresh_index().await;
        // Should have been regenerated (content may be same but last_updated differs)
        assert!(idx3.last_updated >= idx1.last_updated);
    }

    #[tokio::test]
    async fn test_domains_returns_known_domains() {
        let engine = seed_engine();
        let domains = engine.domains();

        assert!(domains.contains(&"revenue".to_string()));
        assert!(domains.contains(&"engineering".to_string()));
        assert!(domains.contains(&"product".to_string()));
    }

    #[tokio::test]
    async fn test_cross_domain_links_detected() {
        let engine = seed_engine();
        let links = engine.cross_domain_links();

        // revenue->engineering and product->engineering
        assert_eq!(links.len(), 2);
    }

    #[tokio::test]
    async fn test_projections_returns_arc_projections() {
        let engine = RecallEngine::new(&IndexConfig::default());
        let projections = engine.projections();

        assert_eq!(projections.len(), 2);
        // Verify they implement Projection (names should be set)
        let names: Vec<&str> = projections.iter().map(|p| p.name()).collect();
        assert!(names.contains(&"prime.domain_index"));
        assert!(names.contains(&"prime.cross_domain"));
    }

    #[tokio::test]
    async fn test_with_dependencies_constructor() {
        let domain_index = Arc::new(DomainIndexProjection::new());
        let cross_domain = Arc::new(CrossDomainProjection::new());
        let compressor = IndexCompressor::new(None, 100, 300);

        let engine =
            RecallEngine::with_dependencies(domain_index.clone(), cross_domain.clone(), compressor);

        // Process an event through the shared Arc
        let event = make_node("n1", "metric", "revenue", "Q3 Revenue");
        domain_index.process(&event).unwrap();
        cross_domain.process(&event).unwrap();

        let domains = engine.domains();
        assert!(domains.contains(&"revenue".to_string()));
    }

    #[tokio::test]
    async fn test_with_dependencies_custom_llm_backend() {
        use std::{future::Future, pin::Pin};

        struct MockBackend;

        impl LlmBackend for MockBackend {
            fn generate(
                &self,
                _prompt: &str,
            ) -> Pin<Box<dyn Future<Output = std::result::Result<String, String>> + Send + '_>>
            {
                Box::pin(async { Ok("# Mock Index".to_string()) })
            }
        }

        let domain_index = Arc::new(DomainIndexProjection::new());
        let cross_domain = Arc::new(CrossDomainProjection::new());

        // Inject a custom LLM backend via the compressor
        let compressor = IndexCompressor::new(Some(Box::new(MockBackend)), 100, 300);
        let engine =
            RecallEngine::with_dependencies(domain_index.clone(), cross_domain.clone(), compressor);

        // Seed some data
        let event = make_node("n1", "metric", "revenue", "Q3 Revenue");
        domain_index.process(&event).unwrap();
        cross_domain.process(&event).unwrap();

        let index = engine.index().await;
        assert_eq!(index.markdown, "# Mock Index");
    }
}