Skip to main content

code_kb_core/
ops.rs

1use rusqlite::Connection;
2use std::path::Path;
3use thiserror::Error;
4
5use crate::formatters::{
6    OutlineNode, add_path_to_outline, format_file_skeleton, render_outline_tree,
7};
8use crate::models::{BlastRadiusResult, ContextSlice, Symbol};
9use crate::queries::{self, QueryError};
10use crate::slicer::{self, SliceError};
11use crate::sync::{self, SyncError};
12use crate::workspace::{Workspace, WorkspaceError, paths_equal};
13
14#[derive(Debug, Clone)]
15pub enum SymbolSelector {
16    Name(String),
17    Id(String),
18}
19
20#[derive(Debug, Error)]
21pub enum OpError {
22    #[error("Symbol '{name}' not found in {workspace}. {hint}")]
23    SymbolNotFound {
24        name: String,
25        workspace: String,
26        hint: String,
27    },
28    #[error("File '{path}' not found in {workspace}. {hint}")]
29    FileNotFound {
30        path: String,
31        workspace: String,
32        hint: String,
33    },
34    #[error("Path '{0}' is a directory, not a file")]
35    IsADirectory(String),
36    #[error(
37        "symbol_id '{id}' is no longer indexed in {workspace}; run lookup_symbol or search_symbols and select a current id"
38    )]
39    StaleSymbolId { id: String, workspace: String },
40    #[error("A database path is required to refresh a symbol_id selector")]
41    SymbolIdRequiresDatabasePath,
42    #[error("Selected symbol is in '{actual}', not requested file '{requested}'")]
43    FileGuardMismatch { requested: String, actual: String },
44    #[error("Workspace error: {0}")]
45    Workspace(#[from] WorkspaceError),
46    #[error("Synchronization error: {0}")]
47    Sync(#[from] SyncError),
48    #[error("Query error: {0}")]
49    Query(#[from] QueryError),
50    #[error("Slice error: {0}")]
51    Slice(#[from] SliceError),
52}
53
54fn stale_symbol_id(conn: &Connection, id: &str) -> OpError {
55    OpError::StaleSymbolId {
56        id: id.to_string(),
57        workspace: queries::workspace_name(conn),
58    }
59}
60
61pub fn resolve_symbol_op(
62    workspace: &Workspace,
63    db_path: &Path,
64    conn: &Connection,
65    selector: &SymbolSelector,
66    file_path: Option<&str>,
67) -> Result<Symbol, OpError> {
68    let id_selector = matches!(selector, SymbolSelector::Id(_));
69    let guard = if let Some(file_path) = file_path {
70        let (absolute, rel) = workspace.resolve_path(Path::new(file_path))?;
71        if !absolute.exists() {
72            return Err(file_not_found(conn, &rel));
73        }
74        if absolute.is_dir() {
75            return Err(OpError::IsADirectory(rel));
76        }
77        if !id_selector {
78            sync::ensure_fresh_file(workspace, db_path, conn, &rel)?;
79        }
80        Some((absolute, rel))
81    } else {
82        None
83    };
84    let lookup = |conn: &Connection| match selector {
85        SymbolSelector::Name(name) => {
86            queries::get_symbol_by_name(conn, name, guard.as_ref().map(|(_, rel)| rel.as_str()))
87        }
88        SymbolSelector::Id(id) => queries::get_symbol_by_id(conn, id),
89    };
90    let initial = lookup(conn)?.ok_or_else(|| match selector {
91        SymbolSelector::Name(name) => {
92            symbol_not_found(conn, name, guard.as_ref().map(|(_, rel)| rel.as_str()))
93        }
94        SymbolSelector::Id(id) => stale_symbol_id(conn, id),
95    })?;
96    if !id_selector
97        && let Some((requested_abs, requested_rel)) = &guard
98        && !paths_equal(requested_abs, &workspace.canonical_root.join(&initial.path))
99    {
100        return Err(OpError::FileGuardMismatch {
101            requested: requested_rel.clone(),
102            actual: initial.path,
103        });
104    }
105    let refreshed = sync::ensure_fresh_file(workspace, db_path, conn, &initial.path)?;
106    let refreshed_symbol = if refreshed {
107        match selector {
108            SymbolSelector::Name(name) => {
109                queries::get_symbol_by_name_exact(conn, name, &initial.path)?
110            }
111            SymbolSelector::Id(id) => queries::get_symbol_by_id(conn, id)?,
112        }
113        .ok_or_else(|| match selector {
114            SymbolSelector::Name(name) => {
115                symbol_not_found(conn, name, guard.as_ref().map(|(_, rel)| rel.as_str()))
116            }
117            SymbolSelector::Id(id) => stale_symbol_id(conn, id),
118        })?
119    } else {
120        initial
121    };
122    if let Some((requested_abs, requested_rel)) = &guard
123        && !paths_equal(
124            requested_abs,
125            &workspace.canonical_root.join(&refreshed_symbol.path),
126        )
127    {
128        return Err(OpError::FileGuardMismatch {
129            requested: requested_rel.clone(),
130            actual: refreshed_symbol.path,
131        });
132    }
133    Ok(refreshed_symbol)
134}
135
136fn symbol_not_found(conn: &Connection, name: &str, path_filter: Option<&str>) -> OpError {
137    let (workspace, hint) = queries::symbol_not_found_parts(conn, name, path_filter);
138    OpError::SymbolNotFound {
139        name: name.to_string(),
140        workspace,
141        hint,
142    }
143}
144
145fn file_not_found(conn: &Connection, rel_path: &str) -> OpError {
146    let (workspace, hint) = queries::file_not_found_parts(conn, rel_path);
147    OpError::FileNotFound {
148        path: rel_path.to_string(),
149        workspace,
150        hint,
151    }
152}
153
154/// Retrieve the body of a symbol by name, guaranteeing fresh offsets and file contents.
155pub fn get_symbol_body_op(
156    workspace: &Workspace,
157    db_path: &Path,
158    conn: &Connection,
159    symbol_name: &str,
160    file_path: Option<&str>,
161) -> Result<(Symbol, String), OpError> {
162    get_symbol_body_selected_op(
163        workspace,
164        db_path,
165        conn,
166        &SymbolSelector::Name(symbol_name.to_string()),
167        file_path,
168    )
169}
170
171pub fn get_symbol_body_selected_op(
172    workspace: &Workspace,
173    db_path: &Path,
174    conn: &Connection,
175    selector: &SymbolSelector,
176    file_path: Option<&str>,
177) -> Result<(Symbol, String), OpError> {
178    let symbol = resolve_symbol_op(workspace, db_path, conn, selector, file_path)?;
179
180    let abs_file = workspace.canonical_root.join(&symbol.path);
181    let body = slicer::slice_symbol_body(&abs_file, &symbol)?;
182
183    Ok((symbol, body))
184}
185
186/// Retrieve a complete context slice for a symbol, guaranteeing fresh offsets.
187pub fn get_context_slice_op(
188    workspace: &Workspace,
189    db_path: &Path,
190    conn: &Connection,
191    symbol_name: &str,
192    file_path: Option<&str>,
193    include_external: bool,
194) -> Result<ContextSlice, OpError> {
195    get_context_slice_selected_op(
196        workspace,
197        db_path,
198        conn,
199        &SymbolSelector::Name(symbol_name.to_string()),
200        file_path,
201        include_external,
202    )
203}
204
205pub fn get_context_slice_selected_op(
206    workspace: &Workspace,
207    db_path: &Path,
208    conn: &Connection,
209    selector: &SymbolSelector,
210    file_path: Option<&str>,
211    include_external: bool,
212) -> Result<ContextSlice, OpError> {
213    let (target_symbol, target_body) =
214        get_symbol_body_selected_op(workspace, db_path, conn, selector, file_path)?;
215
216    let callee_signatures = queries::find_callee_signatures(
217        conn,
218        &target_symbol.name,
219        &target_symbol.symbol_id,
220        10,
221        include_external,
222    )?;
223
224    let related_types = queries::find_related_types(conn, &target_symbol, 10)?;
225    let related_tests = queries::find_related_tests(conn, &target_symbol, 5)?;
226
227    Ok(ContextSlice {
228        target_symbol,
229        target_body,
230        callee_signatures,
231        related_types,
232        related_tests,
233    })
234}
235
236/// Generate file skeleton with fresh file synchronization.
237pub fn file_skeleton_op(
238    workspace: &Workspace,
239    db_path: &Path,
240    conn: &Connection,
241    file_path: &str,
242) -> Result<String, OpError> {
243    let (effective_abs, rel_path) = workspace.resolve_path(Path::new(file_path))?;
244    if !effective_abs.exists() {
245        return Err(file_not_found(conn, &rel_path));
246    }
247    if effective_abs.is_dir() {
248        return codebase_outline_op(workspace, conn, 2, Some(&rel_path));
249    }
250    sync::ensure_fresh_file(workspace, db_path, conn, &rel_path)?;
251
252    let symbols = queries::load_file_symbols(conn, &rel_path)?;
253    let file_meta = queries::get_file(conn, &rel_path)?;
254    let line_count = file_meta.and_then(|m| m.line_count.map(|l| l as usize));
255    let parse_errors = queries::count_parse_diagnostics(conn, &rel_path);
256
257    Ok(format_file_skeleton(
258        &rel_path,
259        &symbols,
260        line_count,
261        parse_errors,
262    ))
263}
264
265/// Generate a memory-bounded codebase outline pushed down into SQLite.
266pub fn codebase_outline_op(
267    workspace: &Workspace,
268    conn: &Connection,
269    depth: usize,
270    path_filter: Option<&str>,
271) -> Result<String, OpError> {
272    let rel_filter = path_filter.map(|p| workspace.relativize_filter(p));
273    let path_filter = rel_filter.as_deref().filter(|path| !path.is_empty());
274    let norm = path_filter
275        .map(|p| p.replace('\\', "/").trim_matches('/').to_string())
276        .filter(|p| !p.is_empty());
277    let norm_bs = norm.as_ref().map(|p| p.replace('/', "\\"));
278    let prefix = norm
279        .as_ref()
280        .map(|path| format!("{}/%", queries::escape_like(path)));
281    let prefix_bs = norm_bs
282        .as_ref()
283        .map(|path| format!("{}\\\\%", queries::escape_like(path)));
284
285    let mut stmt = conn
286        .prepare(
287            "SELECT path FROM files
288             WHERE (:path IS NULL
289                OR path = :path COLLATE NOCASE
290                OR path = :path_bs COLLATE NOCASE
291                OR path LIKE :path_prefix ESCAPE '\\'
292                OR path LIKE :path_prefix_bs ESCAPE '\\')
293             ORDER BY path ASC
294             LIMIT 1001",
295        )
296        .map_err(QueryError::Sqlite)?;
297
298    let mut rows = stmt
299        .query(rusqlite::named_params! {
300            ":path": norm.as_deref(),
301            ":path_bs": norm_bs.as_deref(),
302            ":path_prefix": prefix.as_deref(),
303            ":path_prefix_bs": prefix_bs.as_deref(),
304        })
305        .map_err(QueryError::Sqlite)?;
306
307    let mut file_paths = Vec::new();
308    let mut files_found = 0;
309    let mut truncated = false;
310
311    while let Some(row) = rows.next().map_err(QueryError::Sqlite)? {
312        files_found += 1;
313        if files_found > 1000 {
314            truncated = true;
315            break;
316        }
317        let file_path: String = row.get(0).map_err(QueryError::Sqlite)?;
318        file_paths.push(file_path);
319    }
320
321    if let Some(filter) = path_filter
322        && files_found == 0
323    {
324        return Err(file_not_found(conn, filter));
325    }
326
327    let symbols_by_file = if file_paths.is_empty() {
328        std::collections::HashMap::new()
329    } else {
330        queries::load_scoped_outline_symbols(conn, path_filter, depth, 5)?
331    };
332
333    let mut root_node = OutlineNode::default();
334    let norm_filter = norm.as_deref().unwrap_or_default();
335
336    for file_path in &file_paths {
337        add_path_to_outline(
338            &mut root_node,
339            file_path,
340            &symbols_by_file,
341            depth,
342            norm_filter,
343        );
344    }
345
346    let display_root = if norm_filter.is_empty() {
347        format!("{}/", workspace.repo_name)
348    } else {
349        format!("{}/{}/", workspace.repo_name, norm_filter)
350    };
351
352    let mut out = String::new();
353    out.push_str(&format!("{display_root}\n"));
354    render_outline_tree(&mut out, &root_node, "", 0, depth);
355
356    if truncated {
357        let msg = if path_filter.is_some() {
358            "\n[Outline truncated: path matches over 1,000 files. Narrow your path filter or specify a deeper path to reduce scope.]\n"
359        } else {
360            "\n[Outline truncated: workspace contains over 1,000 files. Use a path filter (e.g. `code-kb outline <path>`) to narrow scope.]\n"
361        };
362        out.push_str(msg);
363    }
364
365    let unsupported = queries::count_unsupported_files(conn, norm.as_deref());
366    if unsupported > 0 {
367        let noun = if unsupported == 1 { "file" } else { "files" };
368        out.push_str(&format!(
369            "\n[{unsupported} unsupported {noun}: no extractor for the language]\n"
370        ));
371    }
372
373    Ok(out)
374}
375
376/// Compute blast radius and likely tests for a symbol, file, or uncommitted git changes.
377pub fn blast_radius_op(
378    workspace: &Workspace,
379    conn: &Connection,
380    symbol: Option<&str>,
381    file: Option<&str>,
382    max_depth: usize,
383    limit: usize,
384) -> Result<BlastRadiusResult, OpError> {
385    blast_radius_selected_op(
386        workspace,
387        None,
388        conn,
389        symbol.map(|s| SymbolSelector::Name(s.to_string())),
390        file,
391        max_depth,
392        limit,
393    )
394}
395
396pub fn blast_radius_selected_op(
397    workspace: &Workspace,
398    db_path: Option<&Path>,
399    conn: &Connection,
400    selector: Option<SymbolSelector>,
401    file: Option<&str>,
402    max_depth: usize,
403    limit: usize,
404) -> Result<BlastRadiusResult, OpError> {
405    if let Some(selector @ SymbolSelector::Id(_)) = selector.as_ref() {
406        let db_path = db_path.ok_or(OpError::SymbolIdRequiresDatabasePath)?;
407        let selected = resolve_symbol_op(workspace, db_path, conn, selector, file)?;
408        return Ok(queries::compute_blast_radius_scoped_with_ids(
409            conn,
410            &[],
411            &[&selected.symbol_id],
412            None,
413            &[],
414            if max_depth == 0 { 2 } else { max_depth.min(5) },
415            limit,
416        )?);
417    }
418    let symbol = selector.as_ref().and_then(|selector| match selector {
419        SymbolSelector::Name(name) => Some(name.as_str()),
420        SymbolSelector::Id(_) => None,
421    });
422    let clean_symbol = symbol.and_then(|s| {
423        let t = s.trim();
424        if t.is_empty() { None } else { Some(t) }
425    });
426    let clean_file = file.and_then(|f| {
427        let t = f.trim();
428        if t.is_empty() {
429            None
430        } else {
431            Some(workspace.relativize_filter(t))
432        }
433    });
434
435    let mut discovered = Vec::new();
436    let (seed_symbols, symbol_path_filter, seed_paths) = match (clean_symbol, clean_file) {
437        (Some(s), Some(f)) => (vec![s], Some(f), vec![]),
438        (Some(s), None) => (vec![s], None, vec![]),
439        (None, Some(f)) => (vec![], None, vec![f]),
440        (None, None) => {
441            // Zero arguments: discover uncommitted working tree changes via git status
442            let git_status = std::process::Command::new("git")
443                .args(["status", "--porcelain"])
444                .current_dir(&workspace.root)
445                .output();
446
447            if let Ok(output) = git_status
448                && output.status.success()
449            {
450                let stdout = String::from_utf8_lossy(&output.stdout);
451                for line in stdout.lines() {
452                    if line.len() > 3 {
453                        let path_part = line.get(3..).unwrap_or("").trim();
454                        let target = if let Some((_, to)) = path_part.split_once("->") {
455                            to.trim()
456                        } else {
457                            path_part
458                        };
459                        let p = target.trim_matches('"');
460                        let p_fwd = p.replace('\\', "/");
461                        if !p_fwd.is_empty() && !crate::workspace::is_hard_excluded(&p_fwd) {
462                            discovered.push(p_fwd);
463                        }
464                    }
465                }
466            }
467            (vec![], None, discovered)
468        }
469    };
470
471    let depth = if max_depth == 0 { 2 } else { max_depth.min(5) };
472    let seed_paths_refs: Vec<&str> = seed_paths.iter().map(|s| s.as_str()).collect();
473    let res = queries::compute_blast_radius_scoped(
474        conn,
475        &seed_symbols,
476        symbol_path_filter.as_deref(),
477        &seed_paths_refs,
478        depth,
479        limit,
480    )?;
481    Ok(res)
482}
483
484#[cfg(test)]
485mod tests {
486    use std::fs;
487
488    use rusqlite::Connection;
489
490    use super::codebase_outline_op;
491    use crate::workspace::Workspace;
492
493    #[test]
494    fn codebase_outline_accepts_absolute_workspace_root_filter() {
495        let temp = crate::safe_tempdir();
496        fs::write(temp.path().join("root.rs"), "pub fn root() {}\n").unwrap();
497        let workspace = Workspace::new(temp.path().to_path_buf());
498        let conn = Connection::open(temp.path().join("index.db")).unwrap();
499        conn.execute_batch(
500            "CREATE TABLE files (
501                file_id TEXT, path TEXT, language TEXT, content_hash TEXT,
502                content_bytes INTEGER, line_count INTEGER, indexed_at TEXT
503            );
504            CREATE TABLE symbols (
505                symbol_id TEXT, file_id TEXT, path TEXT, language TEXT, name TEXT, kind TEXT,
506                signature TEXT, doc_comment TEXT, visibility TEXT, parent_symbol_id TEXT,
507                start_line INTEGER, start_column INTEGER, end_line INTEGER, end_column INTEGER,
508                start_byte INTEGER, end_byte INTEGER, body_start_line INTEGER,
509                body_start_column INTEGER, body_end_line INTEGER, body_end_column INTEGER,
510                body_start_byte INTEGER, body_end_byte INTEGER, body_hash TEXT,
511                semantic_group TEXT, is_test INTEGER, test_container INTEGER
512            );
513            INSERT INTO files VALUES ('f', 'root.rs', 'rust', 'hash', 17, 1, 'now');
514            INSERT INTO symbols VALUES (
515                's', 'f', 'root.rs', 'rust', 'root', 'function', 'pub fn root()', NULL,
516                'pub', NULL, 1, 0, 1, 16, 0, 16, 1, 0, 1, 16, 0, 16, NULL, NULL, 0, 0
517            );",
518        )
519        .unwrap();
520
521        let outline =
522            codebase_outline_op(&workspace, &conn, 1, Some(temp.path().to_str().unwrap())).unwrap();
523
524        assert!(outline.contains("root.rs"));
525
526        fs::create_dir(temp.path().join("src")).unwrap();
527        fs::write(temp.path().join("src/lib.rs"), "pub fn nested() {}\n").unwrap();
528        conn.execute_batch(
529            "INSERT INTO files VALUES ('nested-file', 'src/lib.rs', 'rust', 'hash', 19, 1, 'now');
530             INSERT INTO symbols VALUES (
531                'nested-symbol', 'nested-file', 'src/lib.rs', 'rust', 'nested', 'function',
532                'pub fn nested()', NULL, 'pub', NULL, 1, 0, 1, 18, 0, 18, 1, 0, 1, 18, 0, 18,
533                NULL, NULL, 0, 0
534             );",
535        )
536        .unwrap();
537
538        assert!(
539            codebase_outline_op(&workspace, &conn, 2, Some("."))
540                .unwrap()
541                .contains("root.rs")
542        );
543        assert!(
544            codebase_outline_op(&workspace, &conn, 1, Some("src"))
545                .unwrap()
546                .contains("lib.rs")
547        );
548        assert!(
549            codebase_outline_op(
550                &workspace,
551                &conn,
552                1,
553                Some(temp.path().join("src").to_str().unwrap()),
554            )
555            .unwrap()
556            .contains("lib.rs")
557        );
558        assert!(
559            codebase_outline_op(
560                &workspace,
561                &conn,
562                1,
563                Some(temp.path().parent().unwrap().to_str().unwrap()),
564            )
565            .is_err()
566        );
567    }
568
569    #[test]
570    fn codebase_outline_counts_unsupported_files() {
571        let temp = crate::safe_tempdir();
572        let workspace = Workspace::new(temp.path().to_path_buf());
573        let conn = Connection::open(temp.path().join("index.db")).unwrap();
574        conn.execute_batch(
575            "CREATE TABLE files (
576                file_id TEXT, path TEXT, language TEXT, content_hash TEXT,
577                content_bytes INTEGER, line_count INTEGER, indexed_at TEXT, status TEXT
578            );
579            CREATE TABLE symbols (
580                symbol_id TEXT, file_id TEXT, path TEXT, language TEXT, name TEXT, kind TEXT,
581                signature TEXT, doc_comment TEXT, visibility TEXT, parent_symbol_id TEXT,
582                start_line INTEGER, start_column INTEGER, end_line INTEGER, end_column INTEGER,
583                start_byte INTEGER, end_byte INTEGER, body_start_line INTEGER,
584                body_start_column INTEGER, body_end_line INTEGER, body_end_column INTEGER,
585                body_start_byte INTEGER, body_end_byte INTEGER, body_hash TEXT,
586                semantic_group TEXT, is_test INTEGER, test_container INTEGER
587            );
588            INSERT INTO files VALUES ('f1', 'src/lib.rs', 'rust', 'h', 0, 1, 'now', 'indexed');
589            INSERT INTO files VALUES ('f2', 'src/blob.bin', 'unknown', 'h', 0, 1, 'now', 'unsupported');
590            INSERT INTO files VALUES ('f3', 'docs/blob.bin', 'unknown', 'h', 0, 1, 'now', 'unsupported');
591            INSERT INTO symbols VALUES (
592                's', 'f1', 'src/lib.rs', 'rust', 'root', 'function', 'pub fn root()', NULL,
593                'pub', NULL, 1, 0, 1, 16, 0, 16, 1, 0, 1, 16, 0, 16, NULL, NULL, 0, 0
594            );",
595        )
596        .unwrap();
597
598        let all = codebase_outline_op(&workspace, &conn, 2, None).unwrap();
599        assert!(all.contains("2 unsupported files"));
600
601        let scoped = codebase_outline_op(&workspace, &conn, 2, Some("src")).unwrap();
602        assert!(scoped.contains("1 unsupported file:"));
603    }
604
605    #[test]
606    fn codebase_outline_truncates_over_1000_files() {
607        let temp = crate::safe_tempdir();
608        let workspace = Workspace::new(temp.path().to_path_buf());
609        let conn = Connection::open(temp.path().join("index.db")).unwrap();
610        conn.execute_batch(
611            "CREATE TABLE files (
612                file_id TEXT, path TEXT, language TEXT, content_hash TEXT,
613                content_bytes INTEGER, line_count INTEGER, indexed_at TEXT
614            );
615            CREATE TABLE symbols (
616                symbol_id TEXT, file_id TEXT, path TEXT, language TEXT, name TEXT, kind TEXT,
617                signature TEXT, doc_comment TEXT, visibility TEXT, parent_symbol_id TEXT,
618                start_line INTEGER, start_column INTEGER, end_line INTEGER, end_column INTEGER,
619                start_byte INTEGER, end_byte INTEGER, body_start_line INTEGER,
620                body_start_column INTEGER, body_end_line INTEGER, body_end_column INTEGER,
621                body_start_byte INTEGER, body_end_byte INTEGER, body_hash TEXT,
622                semantic_group TEXT, is_test INTEGER, test_container INTEGER
623            );",
624        )
625        .unwrap();
626
627        for i in 1..=1005 {
628            conn.execute(
629                "INSERT INTO files VALUES (?1, ?2, 'rust', 'hash', 10, 1, 'now')",
630                rusqlite::params![format!("f{i}"), format!("src/file_{i}.rs")],
631            )
632            .unwrap();
633        }
634
635        let outline = codebase_outline_op(&workspace, &conn, 2, None).unwrap();
636        assert!(outline.contains("[Outline truncated: workspace contains over 1,000 files."));
637
638        let scoped_outline = codebase_outline_op(&workspace, &conn, 2, Some("src")).unwrap();
639        assert!(scoped_outline.contains("[Outline truncated: path matches over 1,000 files."));
640    }
641}