code-kb-core 2.8.1

Core library for code-kb AST fact querying, slicing, and progressive disclosure
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
use rusqlite::Connection;
use std::path::Path;
use thiserror::Error;

use crate::db::{DbError, ensure_fts_index_path};
use crate::edit_check::{self, BaseRequest, EditCheck, EditCheckError, EditLimits, PendingCheck};
use crate::formatters::{
    OutlineNode, add_path_to_outline, add_unsupported_to_outline, format_file_skeleton,
    format_find_symbol_results, render_outline_tree,
};
use crate::models::{BlastRadiusResult, ContextSlice, Symbol, SymbolSearchResult, TestTarget};
use crate::queries::{self, QueryError};
use crate::reference_report::{reference_report_for_edit, select_reference_target};
use crate::slicer::{self, SliceError};
use crate::sync::{self, SyncError};
use crate::workspace::{Workspace, WorkspaceError, paths_equal};

#[derive(Debug, Clone)]
pub enum SymbolSelector {
    Name(String),
    Id(String),
}

#[derive(Debug, Error)]
pub enum OpError {
    #[error("Symbol '{name}' not found in {workspace}. {hint}")]
    SymbolNotFound {
        name: String,
        workspace: String,
        hint: String,
    },
    #[error("File '{path}' not found in {workspace}. {hint}")]
    FileNotFound {
        path: String,
        workspace: String,
        hint: String,
    },
    #[error(
        "symbol_id '{id}' is no longer indexed in {workspace}; run lookup_symbol and select a current id"
    )]
    StaleSymbolId { id: String, workspace: String },
    #[error("A database path is required to refresh a symbol_id selector")]
    SymbolIdRequiresDatabasePath,
    #[error("Selected symbol is in '{actual}', not requested file '{requested}'")]
    FileGuardMismatch { requested: String, actual: String },
    #[error("Workspace error: {0}")]
    Workspace(#[from] WorkspaceError),
    #[error("Synchronization error: {0}")]
    Sync(#[from] SyncError),
    #[error("Query error: {0}")]
    Query(#[from] QueryError),
    #[error("Search index is not ready: {0}")]
    SearchIndex(#[from] DbError),
    #[error("Slice error: {0}")]
    Slice(#[from] SliceError),
    #[error(transparent)]
    EditCheck(#[from] EditCheckError),
}

/// What `lookup_symbol` found for one query.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct SymbolLookup {
    /// Rows named like the query, or the members of the owner it names.
    pub names: Vec<Symbol>,
    /// Ranked matches by name words, signatures, and docs that `names` does not already show.
    pub ranked: Vec<SymbolSearchResult>,
    /// The text for a query that finds nothing: the bound workspace and close names.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub miss: Option<String>,
}

/// Looks up `query` by name. A plain query that no row names exactly also gets the ranked search,
/// so one call answers a name and a concept.
pub fn lookup_symbols_op(
    db_path: &Path,
    conn: &Connection,
    query: &str,
    kind: Option<&str>,
    path_filter: Option<&str>,
    include_tests: bool,
    limit: usize,
) -> Result<SymbolLookup, OpError> {
    let names =
        queries::search_symbols_scoped(conn, query, kind, path_filter, include_tests, limit)?;
    let plain = !query.contains('.') && !query.contains("::");
    let named_exactly = names.iter().any(|s| s.name.eq_ignore_ascii_case(query));
    let mut ranked = Vec::new();
    if limit > 0 && plain && !named_exactly {
        ensure_fts_index_path(db_path)?;
        ranked = queries::fts_search_symbols_scoped(
            conn,
            query,
            kind,
            path_filter,
            include_tests,
            limit + names.len(),
        )?;
        ranked.retain(|hit| names.iter().all(|s| s.symbol_id != hit.symbol.symbol_id));
        ranked.truncate(limit);
    }
    let miss = (limit > 0 && names.is_empty() && ranked.is_empty()).then(|| {
        let (workspace, hint) = queries::symbol_not_found_parts(conn, query, path_filter);
        format!("No symbols found matching \"{query}\" in {workspace}. {hint}\n")
    });
    Ok(SymbolLookup {
        names,
        ranked,
        miss,
    })
}

/// The text of a lookup. Members show as `Owner.name`; the rows in `lookup` keep their raw names.
pub fn render_symbol_lookup(
    conn: &Connection,
    query: &str,
    lookup: &SymbolLookup,
    limit: usize,
) -> Result<String, QueryError> {
    if let Some(miss) = &lookup.miss {
        return Ok(miss.clone());
    }
    let mut names = lookup.names.clone();
    let mut ranked = lookup.ranked.clone();
    queries::qualify_members(
        conn,
        names
            .iter_mut()
            .chain(ranked.iter_mut().map(|hit| &mut hit.symbol)),
    )?;
    Ok(format_find_symbol_results(query, &names, &ranked, limit))
}

fn stale_symbol_id(conn: &Connection, id: &str) -> OpError {
    OpError::StaleSymbolId {
        id: id.to_string(),
        workspace: queries::workspace_name(conn),
    }
}

pub fn resolve_symbol_op(
    workspace: &Workspace,
    db_path: &Path,
    conn: &Connection,
    selector: &SymbolSelector,
    file_path: Option<&str>,
) -> Result<Symbol, OpError> {
    let id_selector = matches!(selector, SymbolSelector::Id(_));
    let mut folder = None;
    let guard = if let Some(file_path) = file_path {
        let (absolute, rel) = workspace.resolve_path(Path::new(file_path))?;
        if !absolute.exists() {
            return Err(file_not_found(conn, &rel));
        }
        if absolute.is_dir() {
            folder = Some(rel);
            None
        } else {
            if !id_selector {
                sync::ensure_fresh_file(workspace, db_path, conn, &rel)?;
            }
            Some((absolute, rel))
        }
    } else {
        None
    };
    let scope = guard
        .as_ref()
        .map(|(_, rel)| rel.as_str())
        .or(folder.as_deref());
    let lookup = |conn: &Connection| match selector {
        SymbolSelector::Name(name) => queries::get_symbol_by_name(conn, name, scope),
        SymbolSelector::Id(id) => queries::get_symbol_by_id(conn, id),
    };
    let initial = lookup(conn)?.ok_or_else(|| match selector {
        SymbolSelector::Name(name) => symbol_not_found(conn, name, scope),
        SymbolSelector::Id(id) => stale_symbol_id(conn, id),
    })?;
    if !id_selector
        && let Some((requested_abs, requested_rel)) = &guard
        && !paths_equal(requested_abs, &workspace.canonical_root.join(&initial.path))
    {
        return Err(OpError::FileGuardMismatch {
            requested: requested_rel.clone(),
            actual: initial.path,
        });
    }
    let refreshed = sync::ensure_fresh_file(workspace, db_path, conn, &initial.path)?;
    let refreshed_symbol = if refreshed {
        match selector {
            SymbolSelector::Name(name) => {
                queries::get_symbol_by_name_exact(conn, name, &initial.path)?
            }
            SymbolSelector::Id(id) => queries::get_symbol_by_id(conn, id)?,
        }
        .ok_or_else(|| match selector {
            SymbolSelector::Name(name) => symbol_not_found(conn, name, scope),
            SymbolSelector::Id(id) => stale_symbol_id(conn, id),
        })?
    } else {
        initial
    };
    if let Some((requested_abs, requested_rel)) = &guard
        && !paths_equal(
            requested_abs,
            &workspace.canonical_root.join(&refreshed_symbol.path),
        )
    {
        return Err(OpError::FileGuardMismatch {
            requested: requested_rel.clone(),
            actual: refreshed_symbol.path,
        });
    }
    Ok(refreshed_symbol)
}

fn symbol_not_found(conn: &Connection, name: &str, path_filter: Option<&str>) -> OpError {
    let (workspace, hint) = queries::symbol_not_found_parts(conn, name, path_filter);
    OpError::SymbolNotFound {
        name: name.to_string(),
        workspace,
        hint,
    }
}

fn file_not_found(conn: &Connection, rel_path: &str) -> OpError {
    let (workspace, hint) = queries::file_not_found_parts(conn, rel_path);
    OpError::FileNotFound {
        path: rel_path.to_string(),
        workspace,
        hint,
    }
}

/// Retrieve the body of a symbol by name, guaranteeing fresh offsets and file contents.
pub fn get_symbol_body_op(
    workspace: &Workspace,
    db_path: &Path,
    conn: &Connection,
    symbol_name: &str,
    file_path: Option<&str>,
) -> Result<(Symbol, String), OpError> {
    get_symbol_body_selected_op(
        workspace,
        db_path,
        conn,
        &SymbolSelector::Name(symbol_name.to_string()),
        file_path,
    )
}

pub fn get_symbol_body_selected_op(
    workspace: &Workspace,
    db_path: &Path,
    conn: &Connection,
    selector: &SymbolSelector,
    file_path: Option<&str>,
) -> Result<(Symbol, String), OpError> {
    let mut symbol = resolve_symbol_op(workspace, db_path, conn, selector, file_path)?;
    if let Some((start_byte, start_line)) = decorated_start(conn, &symbol) {
        symbol.start_byte = start_byte;
        symbol.start_line = start_line;
    }

    let abs_file = workspace.canonical_root.join(&symbol.path);
    let source = slicer::slice_symbol_source(&abs_file, &symbol, symbol.start_byte)?;

    Ok((symbol, source))
}

/// A context read builds callees, types, and tests for each overload, so it stops at this many.
pub const MAX_CONTEXT_OVERLOADS: usize = 4;

/// Like [`get_symbol_body_selected_op`], but a name that selects several overloads of one owner
/// in one file returns the body of each overload instead of an ambiguity error.
pub fn get_symbol_bodies_selected_op(
    workspace: &Workspace,
    db_path: &Path,
    conn: &Connection,
    selector: &SymbolSelector,
    file_path: Option<&str>,
) -> Result<Vec<(Symbol, String)>, OpError> {
    match get_symbol_body_selected_op(workspace, db_path, conn, selector, file_path) {
        Err(ambiguity @ OpError::Query(QueryError::AmbiguousSymbol(..))) => overload_selectors(
            workspace,
            db_path,
            conn,
            selector,
            file_path,
            ambiguity,
            usize::MAX,
        )?
        .iter()
        .map(|overload| get_symbol_body_selected_op(workspace, db_path, conn, overload, None))
        .collect(),
        result => result.map(|body| vec![body]),
    }
}

/// Like [`get_context_slice_selected_op`], but a name that selects up to
/// [`MAX_CONTEXT_OVERLOADS`] overloads of one owner in one file returns a slice for each overload.
pub fn get_context_slices_selected_op(
    workspace: &Workspace,
    db_path: &Path,
    conn: &Connection,
    selector: &SymbolSelector,
    file_path: Option<&str>,
    include_external: bool,
) -> Result<Vec<ContextSlice>, OpError> {
    let slice = |selector: &SymbolSelector, file_path: Option<&str>| {
        get_context_slice_selected_op(
            workspace,
            db_path,
            conn,
            selector,
            file_path,
            include_external,
        )
    };
    match slice(selector, file_path) {
        Err(ambiguity @ OpError::Query(QueryError::AmbiguousSymbol(..))) => overload_selectors(
            workspace,
            db_path,
            conn,
            selector,
            file_path,
            ambiguity,
            MAX_CONTEXT_OVERLOADS,
        )?
        .iter()
        .map(|overload| slice(overload, None))
        .collect(),
        result => result.map(|slice| vec![slice]),
    }
}

/// The current ids of the overloads a name selects, after their file is refreshed. Returns
/// `ambiguity` for an id selector, for more than `max` overloads, or when the refresh left none.
fn overload_selectors(
    workspace: &Workspace,
    db_path: &Path,
    conn: &Connection,
    selector: &SymbolSelector,
    file_path: Option<&str>,
    ambiguity: OpError,
    max: usize,
) -> Result<Vec<SymbolSelector>, OpError> {
    let SymbolSelector::Name(name) = selector else {
        return Err(ambiguity);
    };
    let scope = file_path
        .map(|path| workspace.resolve_path(Path::new(path)))
        .transpose()?
        .map(|(_, rel)| rel);
    let mut overloads = queries::get_symbol_overloads(conn, name, scope.as_deref())?;
    if let Some(path) = overloads.first().map(|symbol| symbol.path.clone())
        && sync::ensure_fresh_file(workspace, db_path, conn, &path)?
    {
        overloads = queries::get_symbol_overloads(conn, name, scope.as_deref())?;
    }
    if overloads.is_empty() || overloads.len() > max {
        return Err(ambiguity);
    }
    Ok(overloads
        .into_iter()
        .map(|symbol| SymbolSelector::Id(symbol.symbol_id))
        .collect())
}

/// The byte and line where the decorators above a Python symbol begin: julie starts the symbol at
/// its `def` or `class` line and records the decorated block as a `decorated_definition` fact.
fn decorated_start(conn: &Connection, symbol: &Symbol) -> Option<(usize, usize)> {
    conn.query_row(
        "SELECT start_byte, start_line FROM structural_facts
         WHERE path = ?1 AND pattern_id LIKE '%.decorated_definition.%'
           AND end_byte = ?2 AND start_byte < ?3
         ORDER BY start_byte DESC LIMIT 1",
        rusqlite::params![
            symbol.path,
            symbol.end_byte as i64,
            symbol.start_byte as i64
        ],
        |row| {
            Ok((
                row.get::<_, i64>(0)? as usize,
                row.get::<_, i64>(1)? as usize,
            ))
        },
    )
    .ok()
}

/// Retrieve a complete context slice for a symbol, guaranteeing fresh offsets.
pub fn get_context_slice_op(
    workspace: &Workspace,
    db_path: &Path,
    conn: &Connection,
    symbol_name: &str,
    file_path: Option<&str>,
    include_external: bool,
) -> Result<ContextSlice, OpError> {
    get_context_slice_selected_op(
        workspace,
        db_path,
        conn,
        &SymbolSelector::Name(symbol_name.to_string()),
        file_path,
        include_external,
    )
}

pub fn get_context_slice_selected_op(
    workspace: &Workspace,
    db_path: &Path,
    conn: &Connection,
    selector: &SymbolSelector,
    file_path: Option<&str>,
    include_external: bool,
) -> Result<ContextSlice, OpError> {
    let (target_symbol, target_body) =
        get_symbol_body_selected_op(workspace, db_path, conn, selector, file_path)?;

    let callee_signatures = queries::find_callee_signatures(
        conn,
        &target_symbol.name,
        &target_symbol.symbol_id,
        10,
        include_external,
    )?;

    let related_types = queries::find_related_types(conn, &target_symbol, 10)?;
    let related_tests = queries::find_related_tests(conn, &target_symbol, 5)?;

    Ok(ContextSlice {
        target_symbol,
        target_body,
        callee_signatures,
        related_types,
        related_tests,
    })
}

/// Generate file skeleton with fresh file synchronization.
pub fn file_skeleton_op(
    workspace: &Workspace,
    db_path: &Path,
    conn: &Connection,
    file_path: &str,
) -> Result<String, OpError> {
    let (effective_abs, rel_path) = workspace.resolve_path(Path::new(file_path))?;
    if !effective_abs.exists() {
        return Err(file_not_found(conn, &rel_path));
    }
    if effective_abs.is_dir() {
        return codebase_outline_op(workspace, conn, 2, Some(&rel_path));
    }
    sync::ensure_fresh_file(workspace, db_path, conn, &rel_path)?;

    let mut symbols = queries::load_file_symbols(conn, &rel_path)?;
    let inherited =
        queries::inherited_writes_among(conn, symbols.iter().map(|s| s.symbol_id.as_str()))?;
    symbols.retain(|symbol| !inherited.contains(&symbol.symbol_id));
    let file_meta = queries::get_file(conn, &rel_path)?;
    let line_count = file_meta.and_then(|m| m.line_count.map(|l| l as usize));
    let parse_errors = queries::count_parse_diagnostics(conn, &rel_path);

    Ok(format_file_skeleton(
        &rel_path,
        &symbols,
        line_count,
        parse_errors,
    ))
}

/// Generate a memory-bounded codebase outline pushed down into SQLite.
pub fn codebase_outline_op(
    workspace: &Workspace,
    conn: &Connection,
    depth: usize,
    path_filter: Option<&str>,
) -> Result<String, OpError> {
    let rel_filter = path_filter.map(|p| workspace.relativize_filter(p));
    let path_filter = rel_filter.as_deref().filter(|path| !path.is_empty());
    let norm = path_filter
        .map(|p| p.replace('\\', "/").trim_matches('/').to_string())
        .filter(|p| !p.is_empty());
    let scope = queries::OutlineScope::new(path_filter, depth);
    let symbols_by_file = queries::load_scoped_outline_symbols(conn, path_filter, depth, 5)?;
    let counts = queries::load_outline_counts(conn, path_filter, depth)?;

    let mut root_node = OutlineNode::default();
    let norm_filter = norm.as_deref().unwrap_or_default();
    let mut files_found = 0;
    let mut listed = 0;
    let mut truncated = false;
    queries::for_each_outline_path(conn, &scope, |file_path| {
        files_found += 1;
        if scope.lists(&file_path) {
            listed += 1;
            if listed > queries::OUTLINE_FILE_CAP {
                truncated = true;
                return false;
            }
        }
        add_path_to_outline(
            &mut root_node,
            &file_path,
            &symbols_by_file,
            &counts,
            depth,
            norm_filter,
        );
        true
    })?;

    let mut unsupported = 0;
    queries::for_each_unsupported_path(conn, &scope, |file_path| {
        unsupported += 1;
        add_unsupported_to_outline(&mut root_node, file_path, depth, norm_filter);
    })?;
    if let Some(filter) = path_filter
        && files_found == 0
        && unsupported == 0
    {
        return Err(file_not_found(conn, filter));
    }

    let display_root = if norm_filter.is_empty() {
        format!("{}/", workspace.repo_name)
    } else {
        format!("{}/{}/", workspace.repo_name, norm_filter)
    };

    let mut out = String::new();
    out.push_str(&format!("{display_root}\n"));
    render_outline_tree(&mut out, &root_node, "", 0, depth);

    if truncated {
        let msg = if path_filter.is_some() {
            "\n[Outline truncated: path matches over 1,000 files. Narrow your path filter or specify a deeper path to reduce scope.]\n"
        } else {
            "\n[Outline truncated: workspace contains over 1,000 files. Use a path filter (e.g. `code-kb outline <path>`) to narrow scope.]\n"
        };
        out.push_str(msg);
    }

    if unsupported > 0 {
        let noun = if unsupported == 1 { "file" } else { "files" };
        out.push_str(&format!(
            "\n[{unsupported} unsupported {noun}: no extractor for the language]\n"
        ));
    }

    Ok(out)
}

/// Checks the working tree against `base`, else the session base of the project, else `HEAD`:
/// the symbols whose shape changed and the sites of each that the diff did not reach.
pub fn edit_check_op(
    workspace: &Workspace,
    db_path: &Path,
    conn: &Connection,
    base: Option<&str>,
) -> Result<EditCheck, OpError> {
    match base.map(str::trim).filter(|rev| !rev.is_empty()) {
        Some(rev) => edit_check_with(
            workspace,
            db_path,
            conn,
            BaseRequest::Given(rev),
            EditLimits::default(),
        ),
        None => {
            let session_base = edit_check::latest_session_base(&workspace.canonical_root);
            edit_check_session_op(workspace, db_path, conn, session_base.as_deref())
        }
    }
}

/// Checks the working tree against the base a session recorded, else `HEAD`. A recorded base
/// that git no longer has counts as none.
pub fn edit_check_session_op(
    workspace: &Workspace,
    db_path: &Path,
    conn: &Connection,
    session_base: Option<&str>,
) -> Result<EditCheck, OpError> {
    Ok(edit_check_session_diff(workspace, conn, session_base)?.run(workspace, db_path, conn)?)
}

/// The first half of [`edit_check_session_op`]: the diff against the session base and its hash,
/// before any scan of the base. [`PendingCheck::run`] finishes the check.
pub fn edit_check_session_diff(
    workspace: &Workspace,
    conn: &Connection,
    session_base: Option<&str>,
) -> Result<PendingCheck, OpError> {
    let limits = EditLimits::default();
    if let Some(base) = session_base {
        match edit_check::prepare(workspace, conn, BaseRequest::Session(base), limits) {
            Err(EditCheckError::UnknownRevision(_)) => {}
            prepared => return Ok(prepared?),
        }
    }
    Ok(edit_check::prepare(
        workspace,
        conn,
        BaseRequest::Head,
        limits,
    )?)
}

/// Like [`edit_check_op`], with the base named by its source and the cuts given.
pub fn edit_check_with(
    workspace: &Workspace,
    db_path: &Path,
    conn: &Connection,
    request: BaseRequest<'_>,
    limits: EditLimits,
) -> Result<EditCheck, OpError> {
    Ok(edit_check::run(workspace, db_path, conn, request, limits)?)
}

/// Compute blast radius and likely tests for a symbol, file, or uncommitted git changes.
pub fn blast_radius_op(
    workspace: &Workspace,
    conn: &Connection,
    symbol: Option<&str>,
    file: Option<&str>,
    max_depth: usize,
    limit: usize,
) -> Result<BlastRadiusResult, OpError> {
    blast_radius_selected_op(
        workspace,
        None,
        conn,
        symbol.map(|s| SymbolSelector::Name(s.to_string())),
        file,
        max_depth,
        limit,
    )
}

pub fn blast_radius_selected_op(
    workspace: &Workspace,
    db_path: Option<&Path>,
    conn: &Connection,
    selector: Option<SymbolSelector>,
    file: Option<&str>,
    max_depth: usize,
    limit: usize,
) -> Result<BlastRadiusResult, OpError> {
    if let Some(selector @ SymbolSelector::Id(_)) = selector.as_ref() {
        let db_path = db_path.ok_or(OpError::SymbolIdRequiresDatabasePath)?;
        let selected = resolve_symbol_op(workspace, db_path, conn, selector, file)?;
        let res = queries::compute_blast_radius_scoped_with_ids(
            conn,
            &[],
            &[&selected.symbol_id],
            None,
            &[],
            if max_depth == 0 { 2 } else { max_depth.min(5) },
            limit,
        )?;
        return with_calling_tests(workspace, conn, Some(selected), res, limit);
    }
    let symbol = selector.as_ref().and_then(|selector| match selector {
        SymbolSelector::Name(name) => Some(name.as_str()),
        SymbolSelector::Id(_) => None,
    });
    let clean_symbol = symbol.and_then(|s| {
        let t = s.trim();
        if t.is_empty() { None } else { Some(t) }
    });
    let clean_file = file.and_then(|f| {
        let t = f.trim();
        if t.is_empty() {
            None
        } else {
            Some(workspace.relativize_filter(t))
        }
    });

    let mut discovered = Vec::new();
    let (seed_symbols, symbol_path_filter, seed_paths) = match (clean_symbol, clean_file) {
        (Some(s), Some(f)) => (vec![s], Some(f), vec![]),
        (Some(s), None) => (vec![s], None, vec![]),
        (None, Some(f)) => (vec![], None, vec![f]),
        (None, None) => {
            // Zero arguments: discover uncommitted working tree changes via git status
            let git_status = std::process::Command::new("git")
                .args(["status", "--porcelain"])
                .current_dir(&workspace.root)
                .output();

            if let Ok(output) = git_status
                && output.status.success()
            {
                let stdout = String::from_utf8_lossy(&output.stdout);
                for line in stdout.lines() {
                    if line.len() > 3 {
                        let path_part = line.get(3..).unwrap_or("").trim();
                        let target = if let Some((_, to)) = path_part.split_once("->") {
                            to.trim()
                        } else {
                            path_part
                        };
                        let p = target.trim_matches('"');
                        let p_fwd = p.replace('\\', "/");
                        if !p_fwd.is_empty() && !crate::workspace::is_hard_excluded(&p_fwd) {
                            discovered.push(p_fwd);
                        }
                    }
                }
            }
            (vec![], None, discovered)
        }
    };

    let depth = if max_depth == 0 { 2 } else { max_depth.min(5) };
    let seed_paths_refs: Vec<&str> = seed_paths.iter().map(|s| s.as_str()).collect();
    let res = queries::compute_blast_radius_scoped(
        conn,
        &seed_symbols,
        symbol_path_filter.as_deref(),
        &seed_paths_refs,
        depth,
        limit,
    )?;
    let target = match seed_symbols.as_slice() {
        [name] => select_reference_target(conn, name, symbol_path_filter.as_deref()).ok(),
        _ => None,
    };
    with_calling_tests(workspace, conn, target, res, limit)
}

/// The tests of the callers report of `target` when the walk found none, or `target` itself when
/// it is a test: the walk follows resolved and pending rows by name, and the report also proves a
/// call through a receiver's type.
fn with_calling_tests(
    workspace: &Workspace,
    conn: &Connection,
    target: Option<Symbol>,
    mut res: BlastRadiusResult,
    limit: usize,
) -> Result<BlastRadiusResult, OpError> {
    let Some(target) = target else {
        return Ok(res);
    };
    if !res.likely_tests.is_empty() || res.likely_tests_truncated || res.traversal_ceiling_reached {
        return Ok(res);
    }
    // The walk's answer stands alone; an index too old for the report keeps it.
    let Ok(report) = reference_report_for_edit(conn, &workspace.root, &target, None) else {
        return Ok(res);
    };
    res.likely_tests = report
        .tests
        .into_iter()
        .map(|test| TestTarget {
            reason: if test.name_only {
                "calls it by name only (find_references)"
            } else {
                "calls it (find_references)"
            }
            .to_string(),
            name: test.name,
            path: test.path,
            line: test.line,
        })
        .collect();
    if res.likely_tests.is_empty() && (target.is_test || target.test_container) {
        res.likely_tests.push(TestTarget {
            name: target.name,
            path: target.path.replace('\\', "/"),
            line: target.start_line,
            reason: "the target is a test".to_string(),
        });
    }
    res.likely_tests_found = res.likely_tests.len();
    res.likely_tests_truncated = res.likely_tests.len() > limit;
    res.likely_tests.truncate(limit);
    Ok(res)
}

#[cfg(test)]
mod tests {
    use std::fs;

    use rusqlite::Connection;

    use super::codebase_outline_op;
    use crate::workspace::Workspace;

    #[test]
    fn codebase_outline_accepts_absolute_workspace_root_filter() {
        let temp = crate::safe_tempdir();
        fs::write(temp.path().join("root.rs"), "pub fn root() {}\n").unwrap();
        let workspace = Workspace::new(temp.path().to_path_buf());
        let conn = Connection::open(temp.path().join("index.db")).unwrap();
        conn.execute_batch(
            "CREATE TABLE files (
                file_id TEXT, path TEXT, language TEXT, content_hash TEXT,
                content_bytes INTEGER, line_count INTEGER, indexed_at TEXT
            );
            CREATE TABLE symbols (
                symbol_id TEXT, file_id TEXT, path TEXT, language TEXT, name TEXT, kind TEXT,
                signature TEXT, doc_comment TEXT, visibility TEXT, parent_symbol_id TEXT,
                start_line INTEGER, start_column INTEGER, end_line INTEGER, end_column INTEGER,
                start_byte INTEGER, end_byte INTEGER, body_start_line INTEGER,
                body_start_column INTEGER, body_end_line INTEGER, body_end_column INTEGER,
                body_start_byte INTEGER, body_end_byte INTEGER, body_hash TEXT,
                semantic_group TEXT, is_test INTEGER, test_container INTEGER
            );
            INSERT INTO files VALUES ('f', 'root.rs', 'rust', 'hash', 17, 1, 'now');
            INSERT INTO symbols VALUES (
                's', 'f', 'root.rs', 'rust', 'root', 'function', 'pub fn root()', NULL,
                'pub', NULL, 1, 0, 1, 16, 0, 16, 1, 0, 1, 16, 0, 16, NULL, NULL, 0, 0
            );",
        )
        .unwrap();

        let outline =
            codebase_outline_op(&workspace, &conn, 1, Some(temp.path().to_str().unwrap())).unwrap();

        assert!(outline.contains("root.rs"));

        fs::create_dir(temp.path().join("src")).unwrap();
        fs::write(temp.path().join("src/lib.rs"), "pub fn nested() {}\n").unwrap();
        conn.execute_batch(
            "INSERT INTO files VALUES ('nested-file', 'src/lib.rs', 'rust', 'hash', 19, 1, 'now');
             INSERT INTO symbols VALUES (
                'nested-symbol', 'nested-file', 'src/lib.rs', 'rust', 'nested', 'function',
                'pub fn nested()', NULL, 'pub', NULL, 1, 0, 1, 18, 0, 18, 1, 0, 1, 18, 0, 18,
                NULL, NULL, 0, 0
             );",
        )
        .unwrap();

        assert!(
            codebase_outline_op(&workspace, &conn, 2, Some("."))
                .unwrap()
                .contains("root.rs")
        );
        assert!(
            codebase_outline_op(&workspace, &conn, 1, Some("src"))
                .unwrap()
                .contains("lib.rs")
        );
        assert!(
            codebase_outline_op(
                &workspace,
                &conn,
                1,
                Some(temp.path().join("src").to_str().unwrap()),
            )
            .unwrap()
            .contains("lib.rs")
        );
        assert!(
            codebase_outline_op(
                &workspace,
                &conn,
                1,
                Some(temp.path().parent().unwrap().to_str().unwrap()),
            )
            .is_err()
        );
    }

    #[test]
    fn codebase_outline_counts_unsupported_files() {
        let temp = crate::safe_tempdir();
        let workspace = Workspace::new(temp.path().to_path_buf());
        let conn = Connection::open(temp.path().join("index.db")).unwrap();
        conn.execute_batch(
            "CREATE TABLE files (
                file_id TEXT, path TEXT, language TEXT, content_hash TEXT,
                content_bytes INTEGER, line_count INTEGER, indexed_at TEXT, status TEXT
            );
            CREATE TABLE symbols (
                symbol_id TEXT, file_id TEXT, path TEXT, language TEXT, name TEXT, kind TEXT,
                signature TEXT, doc_comment TEXT, visibility TEXT, parent_symbol_id TEXT,
                start_line INTEGER, start_column INTEGER, end_line INTEGER, end_column INTEGER,
                start_byte INTEGER, end_byte INTEGER, body_start_line INTEGER,
                body_start_column INTEGER, body_end_line INTEGER, body_end_column INTEGER,
                body_start_byte INTEGER, body_end_byte INTEGER, body_hash TEXT,
                semantic_group TEXT, is_test INTEGER, test_container INTEGER
            );
            INSERT INTO files VALUES ('f1', 'src/lib.rs', 'rust', 'h', 0, 1, 'now', 'indexed');
            INSERT INTO files VALUES ('f2', 'src/blob.bin', 'unknown', 'h', 0, 1, 'now', 'unsupported');
            INSERT INTO files VALUES ('f3', 'docs/blob.bin', 'unknown', 'h', 0, 1, 'now', 'unsupported');
            INSERT INTO files VALUES ('f4', 'src/assets/a.png', 'unknown', 'h', 0, 1, 'now', 'unsupported');
            INSERT INTO symbols VALUES (
                's', 'f1', 'src/lib.rs', 'rust', 'root', 'function', 'pub fn root()', NULL,
                'pub', NULL, 1, 0, 1, 16, 0, 16, 1, 0, 1, 16, 0, 16, NULL, NULL, 0, 0
            );",
        )
        .unwrap();

        let all = codebase_outline_op(&workspace, &conn, 2, None).unwrap();
        assert!(all.contains("3 unsupported files"));
        assert!(all.contains("docs/ (1 unsupported file)"), "{all}");
        assert!(all.contains("src/ (2 unsupported files)"), "{all}");
        assert!(!all.contains("assets/"), "{all}");

        let scoped = codebase_outline_op(&workspace, &conn, 2, Some("src")).unwrap();
        assert!(scoped.contains("2 unsupported files:"), "{scoped}");
    }

    #[test]
    fn codebase_outline_names_plain_files_and_shows_an_overload_once() {
        let temp = crate::safe_tempdir();
        let workspace = Workspace::new(temp.path().to_path_buf());
        let conn = Connection::open(temp.path().join("index.db")).unwrap();
        conn.execute_batch(
            "CREATE TABLE files (
                file_id TEXT, path TEXT, language TEXT, content_hash TEXT,
                content_bytes INTEGER, line_count INTEGER, indexed_at TEXT, status TEXT
            );
            CREATE TABLE symbols (
                symbol_id TEXT, file_id TEXT, path TEXT, language TEXT, name TEXT, kind TEXT,
                signature TEXT, doc_comment TEXT, visibility TEXT, parent_symbol_id TEXT,
                start_line INTEGER, start_column INTEGER, end_line INTEGER, end_column INTEGER,
                start_byte INTEGER, end_byte INTEGER, body_start_line INTEGER,
                body_start_column INTEGER, body_end_line INTEGER, body_end_column INTEGER,
                body_start_byte INTEGER, body_end_byte INTEGER, body_hash TEXT,
                semantic_group TEXT, is_test INTEGER, test_container INTEGER
            );
            INSERT INTO files VALUES ('f1', 'src/helpers.py', 'python', 'h', 0, 9, 'now', 'indexed');
            INSERT INTO files VALUES ('f2', 'src/signals.py', 'python', 'h', 0, 3, 'now', 'indexed');
            INSERT INTO files VALUES ('f3', 'src/py.typed', 'unknown', 'h', 0, 0, 'now', 'unsupported');
            INSERT INTO symbols VALUES (
                'a', 'f1', 'src/helpers.py', 'python', 'stream', 'function', 'def stream()', NULL,
                NULL, NULL, 1, 0, 2, 0, 0, 10, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0
            );
            INSERT INTO symbols VALUES (
                'b', 'f1', 'src/helpers.py', 'python', 'stream', 'function', 'def stream(x)', NULL,
                NULL, NULL, 4, 0, 5, 0, 11, 20, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0
            );
            INSERT INTO symbols VALUES (
                'c', 'f2', 'src/signals.py', 'python', 'started', 'variable', 'started = Signal()',
                NULL, NULL, NULL, 1, 0, 1, 0, 0, 18, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0
            );",
        )
        .unwrap();

        let out = codebase_outline_op(&workspace, &conn, 2, Some("src")).unwrap();

        assert!(out.contains("helpers.py [function stream]\n"), "{out}");
        assert!(
            out.contains("(1 file without functions or classes: signals.py)"),
            "{out}"
        );
        assert!(!out.contains("py.typed"), "{out}");
    }

    #[test]
    fn codebase_outline_lists_namespaced_classes_past_deep_files_and_caps_each_subfolder() {
        let temp = crate::safe_tempdir();
        let workspace = Workspace::new(temp.path().to_path_buf());
        let conn = Connection::open(temp.path().join("index.db")).unwrap();
        conn.execute_batch(
            "CREATE TABLE files (
                file_id TEXT, path TEXT, language TEXT, content_hash TEXT,
                content_bytes INTEGER, line_count INTEGER, indexed_at TEXT, status TEXT
            );
            CREATE TABLE symbols (
                symbol_id TEXT, file_id TEXT, path TEXT, language TEXT, name TEXT, kind TEXT,
                signature TEXT, doc_comment TEXT, visibility TEXT, parent_symbol_id TEXT,
                start_line INTEGER, start_column INTEGER, end_line INTEGER, end_column INTEGER,
                start_byte INTEGER, end_byte INTEGER, body_start_line INTEGER,
                body_start_column INTEGER, body_end_line INTEGER, body_end_column INTEGER,
                body_start_byte INTEGER, body_end_byte INTEGER, body_hash TEXT,
                semantic_group TEXT, is_test INTEGER, test_container INTEGER
            );
            INSERT INTO files VALUES ('z', 'z/Late.cs', 'csharp', 'h', 0, 9, 'now', 'indexed');
            INSERT INTO symbols VALUES (
                'ns', 'z', 'z/Late.cs', 'csharp', 'App', 'namespace', 'namespace App', NULL,
                NULL, NULL, 1, 0, 9, 0, 0, 90, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0
            );
            INSERT INTO symbols VALUES (
                'late', 'z', 'z/Late.cs', 'csharp', 'Late', 'class', 'class Late', NULL,
                NULL, 'ns', 2, 0, 8, 0, 20, 80, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0
            );",
        )
        .unwrap();
        let tx = conn.unchecked_transaction().unwrap();
        for i in 0..1005 {
            tx.execute(
                "INSERT INTO files VALUES (?1, ?2, 'rust', 'h', 0, 1, 'now', 'indexed')",
                rusqlite::params![format!("d{i}"), format!("a/deep/x/file_{i}.rs")],
            )
            .unwrap();
        }
        for i in 10..55 {
            let path = format!("m/mod_{i}.rs");
            tx.execute(
                "INSERT INTO files VALUES (?1, ?2, 'rust', 'h', 0, 1, 'now', 'indexed')",
                rusqlite::params![format!("m{i}"), path],
            )
            .unwrap();
            tx.execute(
                "INSERT INTO symbols VALUES (?1, ?2, ?3, 'rust', ?4, 'function', 'fn f()', NULL,
                 NULL, NULL, 1, 0, 1, 0, 0, 9, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0)",
                rusqlite::params![format!("s{i}"), format!("m{i}"), path, format!("f{i}")],
            )
            .unwrap();
        }
        tx.commit().unwrap();

        let out = codebase_outline_op(&workspace, &conn, 2, None).unwrap();

        assert!(out.contains("deep/ (1005 indexed files)"), "{out}");
        assert!(out.contains("Late.cs [class Late]"), "{out}");
        assert!(out.contains("mod_49.rs [function f49]"), "{out}");
        assert!(!out.contains("mod_50.rs"), "{out}");
        assert!(
            out.contains("(+5 more files with functions or classes; pass this folder as the path"),
            "{out}"
        );
        assert!(!out.contains("truncated"), "{out}");

        let scoped = codebase_outline_op(&workspace, &conn, 2, Some("m")).unwrap();
        assert!(scoped.contains("mod_54.rs [function f54]"), "{scoped}");
    }

    #[test]
    fn codebase_outline_truncates_over_1000_files() {
        let temp = crate::safe_tempdir();
        let workspace = Workspace::new(temp.path().to_path_buf());
        let conn = Connection::open(temp.path().join("index.db")).unwrap();
        conn.execute_batch(
            "CREATE TABLE files (
                file_id TEXT, path TEXT, language TEXT, content_hash TEXT,
                content_bytes INTEGER, line_count INTEGER, indexed_at TEXT
            );
            CREATE TABLE symbols (
                symbol_id TEXT, file_id TEXT, path TEXT, language TEXT, name TEXT, kind TEXT,
                signature TEXT, doc_comment TEXT, visibility TEXT, parent_symbol_id TEXT,
                start_line INTEGER, start_column INTEGER, end_line INTEGER, end_column INTEGER,
                start_byte INTEGER, end_byte INTEGER, body_start_line INTEGER,
                body_start_column INTEGER, body_end_line INTEGER, body_end_column INTEGER,
                body_start_byte INTEGER, body_end_byte INTEGER, body_hash TEXT,
                semantic_group TEXT, is_test INTEGER, test_container INTEGER
            );",
        )
        .unwrap();

        let tx = conn.unchecked_transaction().unwrap();
        for i in 1..=1005 {
            tx.execute(
                "INSERT INTO files VALUES (?1, ?2, 'rust', 'hash', 10, 1, 'now')",
                rusqlite::params![format!("f{i}"), format!("src/file_{i}.rs")],
            )
            .unwrap();
        }
        tx.commit().unwrap();

        let outline = codebase_outline_op(&workspace, &conn, 2, None).unwrap();
        assert!(outline.contains("[Outline truncated: workspace contains over 1,000 files."));

        let scoped_outline = codebase_outline_op(&workspace, &conn, 2, Some("src")).unwrap();
        assert!(scoped_outline.contains("[Outline truncated: path matches over 1,000 files."));
    }
}