maproom 0.1.0

Semantic code search powered by embeddings and SQLite
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
//! Relationship-specific query functions.
//!
//! This module provides high-level functions for common relationship queries:
//! - Finding test files for implementation chunks
//! - Finding callers (what calls this)
//! - Finding callees (what this calls)
//! - Finding imports (dependencies)
//!
//! These functions build on the core graph traversal in graph.rs but provide
//! semantic meaning and specialized handling for each relationship type.

use super::graph::RelatedChunk;
use crate::db::sqlite::graph::ImportDirection;
use crate::db::traits::StoreChunks;
use crate::db::traits::StoreGraph;
use crate::db::SqliteStore;
use anyhow::{Context as AnyhowContext, Result};

/// Find test files that test the given chunk.
///
/// This function looks for test_of edges pointing to the target chunk.
///
/// # Arguments
/// * `store` - SqliteStore
/// * `chunk_id` - Implementation chunk to find tests for
///
/// # Returns
/// Vector of test chunks ordered by relevance
///
/// # Example
/// ```ignore
/// let tests = find_test_files(&store, 1234).await?;
/// for test in tests {
///     println!("Test: {} in {}", test.symbol_name.unwrap_or_default(), test.relpath);
/// }
/// ```
pub async fn find_test_files(store: &SqliteStore, chunk_id: i64) -> Result<Vec<RelatedChunk>> {
    // SQLite doesn't have test_links table, so we query chunk_edges directly
    // Look for edges where type='test_of' and dst_chunk_id = chunk_id
    store
        .run(move |conn| {
            let mut stmt = conn.prepare(
                "SELECT DISTINCT
              c.id,
              f.relpath,
              c.symbol_name,
              c.kind,
              c.start_line,
              c.end_line,
              c.preview,
              0 as depth,
              1.0 as relevance
            FROM chunk_edges e
            JOIN chunks c ON c.id = e.src_chunk_id
            JOIN files f ON f.id = c.file_id
            WHERE e.dst_chunk_id = ?1 AND e.type = 'test_of'
            ORDER BY relevance DESC",
            )?;

            let rows = stmt.query_map(rusqlite::params![chunk_id], |row| {
                Ok(RelatedChunk {
                    id: row.get(0)?,
                    relpath: row.get(1)?,
                    symbol_name: row.get(2)?,
                    kind: row.get(3)?,
                    start_line: row.get(4)?,
                    end_line: row.get(5)?,
                    preview: row.get(6)?,
                    depth: row.get(7)?,
                    relevance: row.get(8)?,
                })
            })?;

            let mut tests = Vec::new();
            for test_result in rows {
                tests.push(test_result?);
            }

            Ok(tests)
        })
        .await
        .context("Failed to find test files")
}

/// Find callers of the given chunk (what calls this function/method).
///
/// This follows 'calls' edges backward to find chunks that invoke the target chunk.
///
/// # Arguments
/// * `store` - SqliteStore
/// * `chunk_id` - Chunk to find callers for
/// * `max_depth` - Maximum traversal depth (typically 2-3)
///
/// # Returns
/// Vector of caller chunks ordered by relevance (closest callers first)
///
/// # Example
/// ```ignore
/// let callers = find_callers(&store, 1234, 2).await?;
/// for caller in callers {
///     println!("Called by: {} (depth {})", caller.symbol_name.unwrap_or_default(), caller.depth);
/// }
/// ```
pub async fn find_callers(
    store: &SqliteStore,
    chunk_id: i64,
    max_depth: i32,
) -> Result<Vec<RelatedChunk>> {
    // Use SqliteStore's find_callers method
    let graph_results = store
        .find_callers(chunk_id, Some(max_depth as usize))
        .await?;

    // Convert GraphResult to RelatedChunk
    let mut related_chunks = Vec::new();
    for result in graph_results {
        // Get chunk details for each caller
        if let Some(chunk) = store.get_chunk_by_id(result.chunk_id).await? {
            related_chunks.push(RelatedChunk {
                id: chunk.id,
                relpath: chunk.file_path,
                symbol_name: chunk.symbol_name,
                kind: chunk.kind,
                start_line: chunk.start_line,
                end_line: chunk.end_line,
                preview: chunk.preview,
                depth: result.depth as i32,
                relevance: 0.7_f64.powi(result.depth as i32), // Decay by 0.7 per hop
            });
        }
    }

    Ok(related_chunks)
}

/// Find callees of the given chunk (what this function/method calls).
///
/// This follows 'calls' edges forward to find chunks that are invoked
/// by the target chunk.
///
/// # Arguments
/// * `store` - SqliteStore
/// * `chunk_id` - Chunk to find callees for
/// * `max_depth` - Maximum traversal depth (typically 2-3)
///
/// # Returns
/// Vector of callee chunks ordered by relevance (direct callees first)
///
/// # Example
/// ```ignore
/// let callees = find_callees(&store, 1234, 2).await?;
/// for callee in callees {
///     println!("Calls: {} (depth {})", callee.symbol_name.unwrap_or_default(), callee.depth);
/// }
/// ```
pub async fn find_callees(
    store: &SqliteStore,
    chunk_id: i64,
    max_depth: i32,
) -> Result<Vec<RelatedChunk>> {
    // Use SqliteStore's find_callees method
    let graph_results = store
        .find_callees(chunk_id, Some(max_depth as usize))
        .await?;

    // Convert GraphResult to RelatedChunk
    let mut related_chunks = Vec::new();
    for result in graph_results {
        // Get chunk details for each callee
        if let Some(chunk) = store.get_chunk_by_id(result.chunk_id).await? {
            related_chunks.push(RelatedChunk {
                id: chunk.id,
                relpath: chunk.file_path,
                symbol_name: chunk.symbol_name,
                kind: chunk.kind,
                start_line: chunk.start_line,
                end_line: chunk.end_line,
                preview: chunk.preview,
                depth: result.depth as i32,
                relevance: 0.7_f64.powi(result.depth as i32), // Decay by 0.7 per hop
            });
        }
    }

    Ok(related_chunks)
}

/// Find imports (dependencies) of the given chunk.
///
/// This follows 'imports' edges forward to find modules/files that
/// the target chunk depends on.
///
/// # Arguments
/// * `store` - SqliteStore
/// * `chunk_id` - Chunk to find imports for
///
/// # Returns
/// Vector of imported chunks ordered by relevance
///
/// # Example
/// ```ignore
/// let imports = find_imports(&store, 1234).await?;
/// for import in imports {
///     println!("Imports: {} from {}", import.symbol_name.unwrap_or_default(), import.relpath);
/// }
/// ```
pub async fn find_imports(store: &SqliteStore, chunk_id: i64) -> Result<Vec<RelatedChunk>> {
    // Use SqliteStore's find_imports method (outgoing imports)
    let graph_results = store
        .find_imports(chunk_id, ImportDirection::Outgoing, Some(1))
        .await?;

    // Convert GraphResult to RelatedChunk
    let mut related_chunks = Vec::new();
    for result in graph_results {
        if let Some(chunk) = store.get_chunk_by_id(result.chunk_id).await? {
            related_chunks.push(RelatedChunk {
                id: chunk.id,
                relpath: chunk.file_path,
                symbol_name: chunk.symbol_name,
                kind: chunk.kind,
                start_line: chunk.start_line,
                end_line: chunk.end_line,
                preview: chunk.preview,
                depth: result.depth as i32,
                relevance: 1.0, // Direct imports have full relevance
            });
        }
    }

    Ok(related_chunks)
}

/// Find exports (what exports this chunk).
///
/// This follows 'exports' edges to find modules/files that
/// export the target chunk.
///
/// # Arguments
/// * `store` - SqliteStore
/// * `chunk_id` - Chunk to find exports for
///
/// # Returns
/// Vector of exporting chunks ordered by relevance
///
/// # Example
/// ```ignore
/// let exports = find_exports(&store, 1234).await?;
/// for export in exports {
///     println!("Exported by: {}", export.relpath);
/// }
/// ```
pub async fn find_exports(store: &SqliteStore, chunk_id: i64) -> Result<Vec<RelatedChunk>> {
    // SQLite doesn't have a specific exports edge type in graph module
    // Query chunk_edges directly for 'exports' edges
    store
        .run(move |conn| {
            let mut stmt = conn.prepare(
                "SELECT DISTINCT
              c.id,
              f.relpath,
              c.symbol_name,
              c.kind,
              c.start_line,
              c.end_line,
              c.preview
            FROM chunk_edges e
            JOIN chunks c ON c.id = e.src_chunk_id
            JOIN files f ON f.id = c.file_id
            WHERE e.dst_chunk_id = ?1 AND e.type = 'exports'",
            )?;

            let rows = stmt.query_map(rusqlite::params![chunk_id], |row| {
                Ok(RelatedChunk {
                    id: row.get(0)?,
                    relpath: row.get(1)?,
                    symbol_name: row.get(2)?,
                    kind: row.get(3)?,
                    start_line: row.get(4)?,
                    end_line: row.get(5)?,
                    preview: row.get(6)?,
                    depth: 1,
                    relevance: 1.0,
                })
            })?;

            let mut exports = Vec::new();
            for export_result in rows {
                exports.push(export_result?);
            }

            Ok(exports)
        })
        .await
        .context("Failed to find exports")
}

/// Find route definitions that use the given component chunk.
///
/// This is specific to web frameworks (React, Vue, etc.) where routes
/// reference component chunks.
///
/// # Arguments
/// * `store` - SqliteStore
/// * `chunk_id` - Component chunk to find routes for
///
/// # Returns
/// Vector of route chunks ordered by relevance
///
/// # Example
/// ```ignore
/// let routes = find_routes(&store, 1234).await?;
/// for route in routes {
///     println!("Route: {} in {}", route.symbol_name.unwrap_or_default(), route.relpath);
/// }
/// ```
pub async fn find_routes(store: &SqliteStore, chunk_id: i64) -> Result<Vec<RelatedChunk>> {
    // Query chunk_edges directly for 'route_of' edges
    store
        .run(move |conn| {
            let mut stmt = conn.prepare(
                "SELECT DISTINCT
              c.id,
              f.relpath,
              c.symbol_name,
              c.kind,
              c.start_line,
              c.end_line,
              c.preview
            FROM chunk_edges e
            JOIN chunks c ON c.id = e.src_chunk_id
            JOIN files f ON f.id = c.file_id
            WHERE e.dst_chunk_id = ?1 AND e.type = 'route_of'",
            )?;

            let rows = stmt.query_map(rusqlite::params![chunk_id], |row| {
                Ok(RelatedChunk {
                    id: row.get(0)?,
                    relpath: row.get(1)?,
                    symbol_name: row.get(2)?,
                    kind: row.get(3)?,
                    start_line: row.get(4)?,
                    end_line: row.get(5)?,
                    preview: row.get(6)?,
                    depth: 1,
                    relevance: 1.0,
                })
            })?;

            let mut routes = Vec::new();
            for route_result in rows {
                routes.push(route_result?);
            }

            Ok(routes)
        })
        .await
        .context("Failed to find routes")
}

/// Find all relationship types for a chunk (comprehensive).
///
/// This is a convenience function that queries all relationship types
/// and returns them organized by category.
///
/// # Arguments
/// * `store` - SqliteStore
/// * `chunk_id` - Chunk to analyze
/// * `max_depth` - Maximum depth for caller/callee traversal
///
/// # Returns
/// Tuple of (tests, callers, callees, imports, exports, routes)
pub async fn find_all_relationships(
    store: &SqliteStore,
    chunk_id: i64,
    max_depth: i32,
) -> Result<(
    Vec<RelatedChunk>, // tests
    Vec<RelatedChunk>, // callers
    Vec<RelatedChunk>, // callees
    Vec<RelatedChunk>, // imports
    Vec<RelatedChunk>, // exports
    Vec<RelatedChunk>, // routes
)> {
    // Execute all queries in parallel for performance
    let (tests, callers, callees, imports, exports, routes) = tokio::try_join!(
        find_test_files(store, chunk_id),
        find_callers(store, chunk_id, max_depth),
        find_callees(store, chunk_id, max_depth),
        find_imports(store, chunk_id),
        find_exports(store, chunk_id),
        find_routes(store, chunk_id),
    )?;

    Ok((tests, callers, callees, imports, exports, routes))
}

#[cfg(test)]
mod tests {
    #[allow(unused_imports)]
    use super::*;

    // Unit tests for relationship logic
    // Integration tests with real database are in tests/ directory

    #[tokio::test]
    #[ignore] // Requires database connection
    async fn test_find_test_files() {
        // This is a placeholder for integration testing
        // Real tests go in tests/context/relationship_test.rs
    }

    #[tokio::test]
    #[ignore]
    async fn test_find_callers() {
        // Placeholder
    }

    #[tokio::test]
    #[ignore]
    async fn test_find_callees() {
        // Placeholder
    }
}