terraphim_middleware 1.16.34

Terraphim middleware for searching haystacks
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
use serial_test::serial;
use tempfile::TempDir;
use tokio::fs;

use terraphim_middleware::thesaurus::{Logseq, ThesaurusBuilder};
use terraphim_rolegraph::RoleGraph;
use terraphim_types::{Document, RoleName};

/// Test for knowledge graph ranking expansion that validates:
/// 1. KG construction from docs/src/kg
/// 2. Node and edge counting
/// 3. Adding new records with defined synonyms
/// 4. Verifying nodes/edges changed
/// 5. Validating "terraphim-graph" rank changed using Terraphim Engineer role
#[tokio::test]
#[serial]
async fn test_knowledge_graph_ranking_expansion() {
    env_logger::init();

    // 1. Setup test environment with correct paths
    let current_dir = std::env::current_dir().unwrap();
    let project_root = current_dir.parent().unwrap().parent().unwrap();
    let docs_src_path = project_root.join("docs/src");
    let original_kg_path = docs_src_path.join("kg");

    // Verify that the test files exist
    assert!(
        original_kg_path.exists(),
        "Knowledge graph directory should exist: {:?}",
        original_kg_path
    );
    assert!(
        original_kg_path.join("terraphim-graph.md").exists(),
        "terraphim-graph.md should exist"
    );

    // 2. Create temporary directory and copy existing KG files
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let temp_kg_path = temp_dir.path().join("kg");
    fs::create_dir_all(&temp_kg_path)
        .await
        .expect("Failed to create temp kg dir");

    // Copy existing KG files to temp directory
    let mut original_files = Vec::new();
    let mut entries = fs::read_dir(&original_kg_path)
        .await
        .expect("Failed to read kg directory");
    while let Some(entry) = entries.next_entry().await.expect("Failed to read entry") {
        if entry.path().extension().is_some_and(|ext| ext == "md") {
            let file_name = entry.file_name();
            let source_path = entry.path();
            let dest_path = temp_kg_path.join(&file_name);
            fs::copy(&source_path, &dest_path)
                .await
                .expect("Failed to copy file");
            original_files.push(file_name.to_string_lossy().to_string());
        }
    }

    println!(
        "📁 Copied {} original KG files to temp directory",
        original_files.len()
    );
    println!("   Original files: {:?}", original_files);

    // 3. Build initial knowledge graph and count nodes/edges
    println!("\n🔧 Building initial knowledge graph...");
    let logseq_builder = Logseq::default();
    let initial_thesaurus = logseq_builder
        .build("Terraphim Engineer".to_string(), &temp_kg_path)
        .await
        .expect("Failed to build initial thesaurus");

    let initial_thesaurus_size = initial_thesaurus.len();
    println!(
        "📊 Initial thesaurus contains {} terms",
        initial_thesaurus_size
    );

    // Print initial thesaurus contents for debugging
    println!("📋 Initial thesaurus terms:");
    for (term, normalized_term) in &initial_thesaurus {
        println!(
            "   '{}' -> '{}' (ID: {})",
            term.as_str(),
            normalized_term.value.as_str(),
            normalized_term.id
        );
    }

    // 4. Create initial RoleGraph and count nodes/edges
    let role_name = RoleName::new("Terraphim Engineer");
    let mut initial_rolegraph = RoleGraph::new(role_name.clone(), initial_thesaurus.clone())
        .await
        .expect("Failed to create initial RoleGraph");

    // Index initial documents into the rolegraph
    let mut initial_documents = Vec::new();
    let mut entries = fs::read_dir(&temp_kg_path)
        .await
        .expect("Failed to read temp kg directory");
    while let Some(entry) = entries.next_entry().await.expect("Failed to read entry") {
        if entry.path().extension().is_some_and(|ext| ext == "md") {
            let content = fs::read_to_string(&entry.path())
                .await
                .expect("Failed to read file");
            let file_stem = entry
                .path()
                .file_stem()
                .unwrap()
                .to_string_lossy()
                .to_string();

            let document = Document {
                id: file_stem.clone(),
                url: entry.path().to_string_lossy().to_string(),
                title: file_stem.clone(),
                body: content,
                description: None,
                summarization: None,
                stub: None,
                tags: None,
                rank: None,
                source_haystack: None,
                doc_type: terraphim_types::DocumentType::KgEntry,
                synonyms: None,
                route: None,
                priority: None,
            };

            initial_rolegraph.insert_document(&document.id, document.clone());
            initial_documents.push(document);
        }
    }

    let initial_nodes_count = initial_rolegraph.nodes_map().len();
    let initial_edges_count = initial_rolegraph.edges_map().len();

    println!("📊 Initial RoleGraph stats:");
    println!("   Nodes: {}", initial_nodes_count);
    println!("   Edges: {}", initial_edges_count);
    println!("   Documents: {}", initial_documents.len());

    // 5. Test initial ranking for "terraphim-graph"
    println!("\n🔍 Testing initial ranking for 'terraphim-graph'...");
    let initial_results = initial_rolegraph
        .query_graph("terraphim-graph", Some(0), Some(10))
        .expect("Initial query should succeed");

    let initial_rank = if let Some((_, indexed_doc)) = initial_results.first() {
        indexed_doc.rank
    } else {
        0 // No results found
    };

    println!("📈 Initial rank for 'terraphim-graph': {}", initial_rank);

    // 6. Add new record with defined synonyms to knowledge graph
    println!("\n➕ Adding new knowledge graph record with synonyms...");
    let new_kg_file_path = temp_kg_path.join("graph-analysis.md");
    let new_kg_content = r#"# Graph Analysis

## Advanced Graph Processing

Graph Analysis is a comprehensive approach to understanding complex data relationships and structures within knowledge graphs.

synonyms:: data analysis, network analysis, graph processing, relationship mapping, connectivity analysis, terraphim-graph, graph embeddings

This concept extends the capabilities of graph-based systems by providing deeper insights into data relationships and semantic connections.

## Key Features

- Advanced relationship detection
- Semantic connectivity mapping
- Dynamic graph structure analysis
- Knowledge pattern recognition

The Graph Analysis component works closely with existing graph processing systems to enhance overall system capabilities.
"#;

    fs::write(&new_kg_file_path, new_kg_content)
        .await
        .expect("Failed to write new KG file");

    println!("📝 Created new KG file: graph-analysis.md");
    println!(
        "🔗 New synonyms: data analysis, network analysis, graph processing, relationship mapping, connectivity analysis, terraphim-graph, graph embeddings"
    );

    // 7. Rebuild knowledge graph with new content
    println!("\n🔧 Rebuilding knowledge graph with new content...");
    let expanded_thesaurus = logseq_builder
        .build("Terraphim Engineer".to_string(), &temp_kg_path)
        .await
        .expect("Failed to build expanded thesaurus");

    let expanded_thesaurus_size = expanded_thesaurus.len();
    println!(
        "📊 Expanded thesaurus contains {} terms",
        expanded_thesaurus_size
    );

    // Print new thesaurus contents for comparison
    println!("📋 Expanded thesaurus terms:");
    for (term, normalized_term) in &expanded_thesaurus {
        println!(
            "   '{}' -> '{}' (ID: {})",
            term.as_str(),
            normalized_term.value.as_str(),
            normalized_term.id
        );
    }

    // 8. Create expanded RoleGraph and count nodes/edges
    let mut expanded_rolegraph = RoleGraph::new(role_name.clone(), expanded_thesaurus.clone())
        .await
        .expect("Failed to create expanded RoleGraph");

    // Index all documents (including new one) into the expanded rolegraph
    let mut expanded_documents = Vec::new();
    let mut entries = fs::read_dir(&temp_kg_path)
        .await
        .expect("Failed to read temp kg directory");
    while let Some(entry) = entries.next_entry().await.expect("Failed to read entry") {
        if entry.path().extension().is_some_and(|ext| ext == "md") {
            let content = fs::read_to_string(&entry.path())
                .await
                .expect("Failed to read file");
            let file_stem = entry
                .path()
                .file_stem()
                .unwrap()
                .to_string_lossy()
                .to_string();

            let document = Document {
                id: file_stem.clone(),
                url: entry.path().to_string_lossy().to_string(),
                title: file_stem.clone(),
                body: content,
                description: None,
                summarization: None,
                stub: None,
                tags: None,
                rank: None,
                source_haystack: None,
                doc_type: terraphim_types::DocumentType::KgEntry,
                synonyms: None,
                route: None,
                priority: None,
            };

            expanded_rolegraph.insert_document(&document.id, document.clone());
            expanded_documents.push(document);
        }
    }

    let expanded_nodes_count = expanded_rolegraph.nodes_map().len();
    let expanded_edges_count = expanded_rolegraph.edges_map().len();

    println!("📊 Expanded RoleGraph stats:");
    println!("   Nodes: {}", expanded_nodes_count);
    println!("   Edges: {}", expanded_edges_count);
    println!("   Documents: {}", expanded_documents.len());

    // 9. Test expanded ranking for "terraphim-graph"
    println!("\n🔍 Testing expanded ranking for 'terraphim-graph'...");
    let expanded_results = expanded_rolegraph
        .query_graph("terraphim-graph", Some(0), Some(10))
        .expect("Expanded query should succeed");

    let expanded_rank = if let Some((_, indexed_doc)) = expanded_results.first() {
        indexed_doc.rank
    } else {
        0 // No results found
    };

    println!("📈 Expanded rank for 'terraphim-graph': {}", expanded_rank);

    // 10. Validation assertions
    println!("\n✅ Validating knowledge graph expansion results...");

    // Verify thesaurus grew
    assert!(
        expanded_thesaurus_size > initial_thesaurus_size,
        "Thesaurus should have grown from {} to {} terms",
        initial_thesaurus_size,
        expanded_thesaurus_size
    );
    println!(
        "✅ Thesaurus grew: {} -> {} terms (+{})",
        initial_thesaurus_size,
        expanded_thesaurus_size,
        expanded_thesaurus_size - initial_thesaurus_size
    );

    // Verify nodes increased
    assert!(
        expanded_nodes_count > initial_nodes_count,
        "Nodes should have increased from {} to {}",
        initial_nodes_count,
        expanded_nodes_count
    );
    println!(
        "✅ Nodes increased: {} -> {} (+{})",
        initial_nodes_count,
        expanded_nodes_count,
        expanded_nodes_count - initial_nodes_count
    );

    // Verify edges did not significantly drop
    let min_expected_edges = (initial_edges_count * 9) / 10;
    assert!(
        expanded_edges_count >= min_expected_edges,
        "Edges should not drop more than 10% from {} to {}",
        initial_edges_count,
        expanded_edges_count
    );
    println!(
        "✅ Edges within tolerance: {} -> {} (delta {})",
        initial_edges_count,
        expanded_edges_count,
        (expanded_edges_count as isize) - (initial_edges_count as isize)
    );

    // Verify documents increased
    assert!(
        expanded_documents.len() > initial_documents.len(),
        "Documents should have increased from {} to {}",
        initial_documents.len(),
        expanded_documents.len()
    );
    println!(
        "✅ Documents increased: {} -> {} (+{})",
        initial_documents.len(),
        expanded_documents.len(),
        expanded_documents.len() - initial_documents.len()
    );

    // Verify rank changed (should increase due to more connections)
    assert_ne!(
        expanded_rank, initial_rank,
        "Rank should have changed from {} to {}",
        initial_rank, expanded_rank
    );
    println!(
        "✅ Rank changed: {} -> {} ({}{})",
        initial_rank,
        expanded_rank,
        if expanded_rank > initial_rank {
            "+"
        } else {
            ""
        },
        (expanded_rank as i64) - (initial_rank as i64)
    );

    // 11. Test that new synonyms are searchable
    println!("\n🔍 Testing new synonyms are searchable...");
    let new_synonym_tests = vec![
        "data analysis",
        "network analysis",
        "graph processing",
        "relationship mapping",
        "connectivity analysis",
        "graph embeddings",
    ];

    for synonym in &new_synonym_tests {
        let results = expanded_rolegraph
            .query_graph(synonym, Some(0), Some(5))
            .expect("New synonym query should succeed");

        assert!(
            !results.is_empty(),
            "Should find results for new synonym: '{}'",
            synonym
        );
        println!(
            "✅ Found {} results for synonym: '{}'",
            results.len(),
            synonym
        );
    }

    // 12. Verify Terraphim Engineer role configuration is used correctly
    assert_eq!(
        role_name.original.as_str(),
        "Terraphim Engineer",
        "Should be using Terraphim Engineer role"
    );
    println!("✅ Using correct role: {}", role_name.original.as_str());

    // 13. Final summary
    println!("\n🎉 Knowledge Graph Ranking Expansion Test Complete!");
    println!(
        "   📊 Initial State: {} terms, {} nodes, {} edges, rank {}",
        initial_thesaurus_size, initial_nodes_count, initial_edges_count, initial_rank
    );
    println!(
        "   📈 Expanded State: {} terms, {} nodes, {} edges, rank {}",
        expanded_thesaurus_size, expanded_nodes_count, expanded_edges_count, expanded_rank
    );
    println!(
        "   🚀 Growth: +{} terms, +{} nodes, {} edges, rank change: {}",
        expanded_thesaurus_size.saturating_sub(initial_thesaurus_size),
        expanded_nodes_count.saturating_sub(initial_nodes_count),
        expanded_edges_count as i64 - initial_edges_count as i64,
        (expanded_rank as i64) - (initial_rank as i64)
    );

    println!("✅ All validations passed!");
}