knot 1.14.0

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, C/C++, C#, Build Systems, and HTML/CSS codebases
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
//! Core `list_files` logic shared between CLI and MCP.
//!
//! A read-only enumeration of the files an indexed repository carries,
//! backed by the Neo4j graph (`QueryExt::list_files`). Agents that do not
//! already know a path can discover the available files before narrowing
//! their searches (`search_hybrid_context` accepts the same prefixes via
//! its `path` parameter).
//!
//! # Semantics
//! - `path` is optional: absent/empty lists every file of the repository
//!   scope; otherwise it is normalized exactly like `explore_file` (POSIX
//!   separators, no leading `./`, local-root stripping) and matched as a
//!   **directory-prefix with path boundary**: `src/api` matches
//!   `src/api/users.ts` but not `src/api-notes.md`.
//! - Both plain prefixes and glob patterns (`*`, `?`, `**`) page the graph
//!   in reads of [`MAX_FILES`], applying the path-boundary filter to each
//!   page, so a literal `STARTS WITH` over-match can never fill the output
//!   window and hide valid files behind it. A glob scans the whole scope;
//!   a plain prefix lets the graph query pre-narrow the rows.
//! - The pager is capped at [`MAX_SCAN_PAGES`] iterations so a non-advancing
//!   fetcher terminates with `"truncated": true` instead of looping forever.
//! - Ordering is deterministic: `(repo_name, file_path)` from the graph
//!   query; glob filtering preserves that order; the reply carries
//!   `"truncated": true` when the output file count exceeds [`MAX_FILES`].
//! - `"total_matches"` is the pre-truncation match count. It is exact when
//!   the scan consumed the source and a lower bound otherwise, which
//!   `"total_is_lower_bound"` states explicitly.
//! - When truncated, the rendered markdown surfaces a notice indicating the
//!   truncation while still rendering the first [`MAX_FILES`] matches.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::Result;
use serde_json::json;

use crate::db::graph::{GraphDb, QueryExt};
use crate::models::RepoScope;

/// Hard cap on output files returned: the read-only surface stays
/// bounded, and the reply surfaces `"truncated": true` so callers
/// know to narrow the filter.
const MAX_FILES: usize = 2000;

/// Hard cap on the number of pages a single listing scan may read.
/// The real Neo4j backend honours `SKIP`, so a scan always converges;
/// this bounds a fetcher that does not (non-advancing or non-shrinking
/// pages) so it terminates instead of looping forever. Reaching the cap
/// is reported as a truncated result โ€” never a panic, never a silent stop.
const MAX_SCAN_PAGES: usize = 64;

/// Normalize caller-supplied path input to the canonical relative form of
/// the index โ€” the `explore_file` ยง4 behavior inherited wholesale: POSIX
/// separators, no leading `./`, local-root stripping when the input names
/// something that exists on disk.
pub fn normalize_list_path(path: &str, cwd: Option<&Path>, repo_root: Option<&Path>) -> String {
    super::explore_file::normalize_explore_input(path, repo_root)
        .pipe(|normalized| resolve_against_disk(path, cwd, repo_root, normalized))
}

/// Helper so the normalization stays a single readable expression.
trait Pipe: Sized {
    fn pipe<T>(self, f: impl FnOnce(Self) -> T) -> T {
        f(self)
    }
}
impl<T> Pipe for T {}

fn resolve_against_disk(
    raw: &str,
    cwd: Option<&Path>,
    repo_root: Option<&Path>,
    normalized: String,
) -> String {
    let resolved = super::explore_file::resolve_explore_input(raw, cwd, repo_root);
    // `resolve_explore_input` only returns a shorter, meaningful value
    // when the input exists on disk; otherwise it echoes the normalized
    // form. Accept whichever is the canonical relative path.
    if resolved.len() < raw.len() && !resolved.is_empty() {
        resolved
    } else {
        normalized
    }
}

/// Whether `candidate` (a normalized repo-relative path) matches the
/// normalized `prefix` under directory-boundary semantics.
///
/// An empty prefix (or `.`, or `/`) matches everything. A plain directory
/// prefix must match on a `/` boundary: `src/api` matches `src/api/users.ts`
/// and the bare `src/api` itself, but not `src/api-notes.md`. A prefix
/// containing `*` or `?` is treated as a glob ([`glob_match`]).
pub fn path_matches(prefix: &str, candidate: &str) -> bool {
    let p = prefix.trim_matches('/');
    if p.is_empty() || p == "." {
        return true;
    }
    if p.contains('*') || p.contains('?') {
        return glob_match(p, candidate);
    }
    candidate == p || candidate.starts_with(&format!("{p}/"))
}

/// Minimal deterministic glob matcher over `/`-separated paths.
///
/// Pattern language:
/// - `?` โ€” exactly one character, never `/`
/// - `*` โ€” any run of characters except `/` (segment-local)
/// - `**` โ€” a full path segment that matches any number of segments
///   (including zero): `src/**/*.rs`
///
/// Case-sensitive on all platforms. Segment-wise, so `*` can never cross
/// a path edge.
pub fn glob_match(pattern: &str, candidate: &str) -> bool {
    let p_segs: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect();
    let c_segs: Vec<&str> = candidate.split('/').filter(|s| !s.is_empty()).collect();
    segments_match(&p_segs, &c_segs)
}

/// Segment-wise matcher with recursion only on `**` patterns (patterns
/// chains are tiny; deterministic depth).
fn segments_match(p: &[&str], c: &[&str]) -> bool {
    match p.first() {
        None => c.is_empty(),
        Some(&"**") => {
            // Zero or more segments consumed.
            for skip in 0..=c.len() {
                if segments_match(&p[1..], &c[skip..]) {
                    return true;
                }
            }
            false
        }
        Some(&first) => {
            if c.is_empty() || !segment_match(first, c[0]) {
                return false;
            }
            segments_match(&p[1..], &c[1..])
        }
    }
}

/// One `/`-free segment: `*` wildcard runs and `?` single non-`/` chars.
fn segment_match(pattern: &str, segment: &str) -> bool {
    let p: Vec<char> = pattern.chars().collect();
    let s: Vec<char> = segment.chars().collect();
    // Classic two-slot wildcard match (backtracking on the last `*`).
    let (mut pi, mut si) = (0usize, 0usize);
    let mut star: Option<(usize, usize)> = None;
    while si < s.len() {
        if pi < p.len() {
            match p[pi] {
                '*' => {
                    star = Some((pi, si));
                    pi += 1;
                    continue;
                }
                '?' => {
                    pi += 1;
                    si += 1;
                    continue;
                }
                ch if ch == s[si] => {
                    pi += 1;
                    si += 1;
                    continue;
                }
                _ => {}
            }
        }
        match star {
            Some((re_pi, advanced_si)) => {
                pi = re_pi + 1;
                si = advanced_si + 1;
                star = Some((re_pi, advanced_si + 1));
            }
            None => return false,
        }
    }
    while pi < p.len() && p[pi] == '*' {
        pi += 1;
    }
    pi == p.len()
}

/// Format the JSON listing as a deterministic Markdown table; shared by
/// the MCP tool and the CLI.
pub fn format_list_files_markdown(files: &serde_json::Value) -> String {
    let rows = files
        .get("files")
        .or_else(|| files.as_array().map(|_| files))
        .and_then(|v| v.as_array())
        .map(Vec::as_slice)
        .unwrap_or(&[]);
    if rows.is_empty() {
        return "No indexed files matched the given path.".to_string();
    }
    let mut out = String::from("| Repository | File | Entities |\n|---|---|---:|\n");
    for row in rows {
        let repo = row.get("repo_name").and_then(|v| v.as_str()).unwrap_or("?");
        let file = row.get("file_path").and_then(|v| v.as_str()).unwrap_or("?");
        let count = row
            .get("entity_count")
            .and_then(|v| v.as_i64())
            .unwrap_or(0);
        out.push_str(&format!("| {repo} | {file} | {count} |\n"));
    }
    let is_truncated = files
        .get("truncated")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    if is_truncated {
        let shown = rows.len();
        let exact = files
            .get("total_matches")
            .and_then(serde_json::Value::as_u64)
            .filter(|_| {
                !files
                    .get("total_is_lower_bound")
                    .and_then(serde_json::Value::as_bool)
                    .unwrap_or(true)
            });
        match exact {
            Some(total) => out.push_str(&format!(
                "\nShowing first {shown} of {total} files (truncated) โ€” narrow the pattern."
            )),
            None => out.push_str(&format!(
                "\nShowing first {shown} of more than {shown} files (truncated) โ€” narrow the pattern."
            )),
        }
    }
    out
}

/// Format the JSON listing for the requested CLI output format, shared
/// with the MCP tool's markdown rendering.
pub fn format_files_output(
    result: &serde_json::Value,
    output: crate::config::OutputFormat,
) -> String {
    super::format_json_or_markdown(result, output, format_list_files_markdown)
}

/// Outcome of a paged scan over the graph's file listing.
struct ScanOutcome {
    /// Rows that passed [`path_matches`], in graph order.
    rows: Vec<serde_json::Value>,
    /// `true` when the source ran out of rows, which makes `rows.len()`
    /// the exact pre-truncation match total. `false` when the scan
    /// stopped early โ€” at the match cap or at [`MAX_SCAN_PAGES`] โ€” which
    /// makes `rows.len()` a lower bound only.
    exhausted: bool,
}

/// Parameters for [`scan_matching_files`].
struct ScanParams<'a> {
    query_prefix: &'a str,
    filter: &'a str,
    repo_names: &'a [String],
    page_size: usize,
    stop_after: usize,
}

/// Page the graph's file listing, applying [`path_matches`] per page so a
/// literal `STARTS WITH` over-match (`src/api` โ†’ `src/api-notes.md`) can
/// never consume the output window and hide valid files behind it.
///
/// Stops on the first of: the source running out of rows (`exhausted`),
/// `stop_after` valid matches collected, or [`MAX_SCAN_PAGES`] pages read.
async fn scan_matching_files<F, Fut>(fetch_page: F, params: ScanParams<'_>) -> Result<ScanOutcome>
where
    F: Fn(String, Vec<String>, usize, usize) -> Fut,
    Fut: Future<Output = Result<serde_json::Value>>,
{
    let mut rows: Vec<serde_json::Value> = Vec::new();
    let mut skip = 0usize;
    let mut exhausted = false;

    for _ in 0..MAX_SCAN_PAGES {
        let page = fetch_page(
            params.query_prefix.to_string(),
            params.repo_names.to_vec(),
            skip,
            params.page_size,
        )
        .await?;
        let page_arr = page.as_array().cloned().unwrap_or_default();
        let fetched_len = page_arr.len();
        rows.extend(page_arr.into_iter().filter(|row| {
            let candidate = row.get("file_path").and_then(|v| v.as_str()).unwrap_or("");
            path_matches(params.filter, candidate)
        }));

        if fetched_len < params.page_size {
            exhausted = true;
            break;
        }
        if rows.len() >= params.stop_after {
            rows.truncate(params.stop_after);
            break;
        }
        skip += params.page_size;
    }

    Ok(ScanOutcome { rows, exhausted })
}

/// Run the file listing shared by `knot files` and the `list_files` MCP
/// tool. Returns `{"files": [...], "truncated": bool}` or `null` when
/// nothing matched.
pub async fn run_list_files(
    path: Option<&str>,
    repo: &RepoScope,
    graph_db: &Arc<GraphDb>,
) -> Result<serde_json::Value> {
    run_list_files_with_fetcher(path, repo, |prefix, repo_names, skip, limit| async move {
        graph_db.list_files(&prefix, &repo_names, skip, limit).await
    })
    .await
}

async fn run_list_files_with_fetcher<F, Fut>(
    path: Option<&str>,
    repo: &RepoScope,
    fetch_page: F,
) -> Result<serde_json::Value>
where
    F: Fn(String, Vec<String>, usize, usize) -> Fut,
    Fut: Future<Output = Result<serde_json::Value>>,
{
    let cwd = std::env::current_dir().ok();
    let repo_root = std::env::var("KNOT_REPO_PATH").ok().map(PathBuf::from);
    let normalized = path
        .filter(|p| !p.trim().is_empty())
        .map(|p| normalize_list_path(p, cwd.as_deref(), repo_root.as_deref()))
        .unwrap_or_default();
    let repo_names = repo.filter_names();

    let is_glob = normalized.contains('*') || normalized.contains('?');

    let query_prefix = if is_glob { "" } else { normalized.as_str() };

    let scan = scan_matching_files(
        &fetch_page,
        ScanParams {
            query_prefix,
            filter: &normalized,
            repo_names: &repo_names,
            page_size: MAX_FILES,
            stop_after: MAX_FILES + 1,
        },
    )
    .await?;

    if scan.rows.is_empty() {
        return Ok(serde_json::Value::Null);
    }

    let total_matches = scan.rows.len();
    let is_truncated = total_matches > MAX_FILES || !scan.exhausted;
    let mut final_files = scan.rows;
    final_files.truncate(MAX_FILES);

    Ok(json!({
        "files": final_files,
        "truncated": is_truncated,
        "total_matches": total_matches,
        "total_is_lower_bound": !scan.exhausted,
    }))
}

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

    // --- normalize_list_path ---

    #[test]
    fn normalize_list_path_posix() {
        assert_eq!(normalize_list_path("src/api", None, None), "src/api");
        assert_eq!(normalize_list_path("./src/api", None, None), "src/api");
        assert_eq!(normalize_list_path(r"src\api", None, None), "src/api");
        assert_eq!(normalize_list_path("", None, None), "");
    }

    #[test]
    fn normalize_list_path_strips_local_root() {
        let root = Path::new("/home/dev/repo");
        assert_eq!(
            normalize_list_path("/home/dev/repo/src/api", Some(root), Some(root)),
            "src/api"
        );
    }

    // --- path_matches ---

    #[test]
    fn empty_prefix_matches_everything() {
        assert!(path_matches("", "src/main.rs"));
        assert!(path_matches(".", "Cargo.toml"));
    }

    #[test]
    fn boundary_prefix_respects_directory_edges() {
        assert!(path_matches("src/api", "src/api/users.ts"));
        assert!(path_matches("src/api", "src/api"));
        assert!(!path_matches("src/api", "src/api-notes.md"));
        assert!(!path_matches("src/api", "src/hooks/useThing.ts"));
    }

    // --- glob_match ---

    #[test]
    fn glob_star_is_segment_local() {
        assert!(glob_match("src/*.rs", "src/main.rs"));
        assert!(!glob_match("src/*.rs", "src/cli/main.rs"));
        assert!(glob_match("*/tests/*.ts", "hooks/tests/a.ts"));
    }

    #[test]
    fn glob_double_star_crosses_segments() {
        assert!(glob_match("src/**", "src/api/v1/users.ts"));
        assert!(glob_match("src/**/*.rs", "src/cli_tools/x/tests/a.rs"));
        // Zero segments also match.
        assert!(glob_match("src/**", "src"));
    }

    #[test]
    fn glob_question_mark_is_single_non_slash() {
        assert!(glob_match("a?.rs", "ab.rs"));
        assert!(!glob_match("a?.rs", "abc.rs"));
    }

    // --- format ---

    #[test]
    fn markdown_table_lists_repo_file_count() {
        let files = json!({
            "files": [
                {"repo_name": "r", "file_path": "src/a.rs", "entity_count": 3},
                {"repo_name": "r", "file_path": "src/b.rs", "entity_count": 1},
            ],
            "truncated": false,
        });
        let md = format_list_files_markdown(&files);
        assert!(md.contains("| Repository | File | Entities |"));
        assert!(md.contains("| r | src/a.rs | 3 |"));
        assert!(md.contains("| r | src/b.rs | 1 |"));
        assert!(!md.contains("(truncated)"));
    }

    #[test]
    fn markdown_table_renders_exact_truncated_notice() {
        let files = json!({
            "files": [
                {"repo_name": "r", "file_path": "src/a.rs", "entity_count": 3},
                {"repo_name": "r", "file_path": "src/b.rs", "entity_count": 1},
            ],
            "truncated": true,
            "total_matches": 3471,
            "total_is_lower_bound": false,
        });
        let md = format_list_files_markdown(&files);
        assert!(md.contains("| Repository | File | Entities |"));
        assert!(md.contains("| r | src/a.rs | 3 |"));
        assert!(md.contains("| r | src/b.rs | 1 |"));
        assert!(md.contains("Showing first 2 of 3471 files (truncated) โ€” narrow the pattern."));
    }

    #[test]
    fn markdown_table_renders_lower_bound_notice() {
        let files = json!({
            "files": [
                {"repo_name": "r", "file_path": "src/a.rs", "entity_count": 3},
                {"repo_name": "r", "file_path": "src/b.rs", "entity_count": 1},
            ],
            "truncated": true,
            "total_matches": 2,
            "total_is_lower_bound": true,
        });
        let md = format_list_files_markdown(&files);
        assert!(
            md.contains("Showing first 2 of more than 2 files (truncated) โ€” narrow the pattern.")
        );
        assert!(!md.contains("of at least 3"));
    }

    #[test]
    fn markdown_empty_list_hits_the_no_match_message() {
        let md = format_list_files_markdown(&json!([]));
        assert!(md.contains("No indexed files matched"));
    }

    #[tokio::test]
    async fn plain_prefix_behind_many_non_matching_siblings_pages_and_returns_matches() {
        let mut mock_files = Vec::new();
        for i in 0..2400 {
            mock_files.push(json!({
                "repo_name": "repo",
                "file_path": format!("src/api-notes/f{i}.md"),
                "entity_count": 1,
            }));
        }
        for i in 0..5 {
            mock_files.push(json!({
                "repo_name": "repo",
                "file_path": format!("src/api/users{i}.ts"),
                "entity_count": 2,
            }));
        }

        let repo_scope = RepoScope::All;

        let res = run_list_files_with_fetcher(
            Some("src/api"),
            &repo_scope,
            |prefix, _repo_names, skip, limit| {
                let mock_files = mock_files.clone();
                async move {
                    let filtered: Vec<serde_json::Value> = mock_files
                        .into_iter()
                        .filter(|f| {
                            let path = f.get("file_path").and_then(|v| v.as_str()).unwrap_or("");
                            path.starts_with(&prefix)
                        })
                        .skip(skip)
                        .take(limit)
                        .collect();
                    Ok(json!(filtered))
                }
            },
        )
        .await
        .unwrap();

        let files = res.get("files").and_then(|v| v.as_array()).unwrap();
        assert_eq!(files.len(), 5);
        for f in files {
            let path = f.get("file_path").and_then(|v| v.as_str()).unwrap();
            assert!(path.starts_with("src/api/"));
        }
        assert_eq!(res.get("truncated").and_then(|v| v.as_bool()), Some(false));
        assert_eq!(res.get("total_matches").and_then(|v| v.as_u64()), Some(5));
        assert_eq!(
            res.get("total_is_lower_bound").and_then(|v| v.as_bool()),
            Some(false)
        );
    }

    #[tokio::test]
    async fn plain_prefix_with_unfiltered_overflow_but_filtered_under_cap_reports_not_truncated() {
        let mut mock_files = Vec::new();
        for i in 0..3000 {
            mock_files.push(json!({
                "repo_name": "repo",
                "file_path": format!("src/api-notes/f{i}.md"),
                "entity_count": 1,
            }));
        }
        for i in 0..10 {
            mock_files.push(json!({
                "repo_name": "repo",
                "file_path": format!("src/api/x{i}.ts"),
                "entity_count": 2,
            }));
        }

        let repo_scope = RepoScope::All;

        let res = run_list_files_with_fetcher(
            Some("src/api"),
            &repo_scope,
            |prefix, _repo_names, skip, limit| {
                let mock_files = mock_files.clone();
                async move {
                    let filtered: Vec<serde_json::Value> = mock_files
                        .into_iter()
                        .filter(|f| {
                            let path = f.get("file_path").and_then(|v| v.as_str()).unwrap_or("");
                            path.starts_with(&prefix)
                        })
                        .skip(skip)
                        .take(limit)
                        .collect();
                    Ok(json!(filtered))
                }
            },
        )
        .await
        .unwrap();

        let files = res.get("files").and_then(|v| v.as_array()).unwrap();
        assert_eq!(files.len(), 10);
        assert_eq!(res.get("truncated").and_then(|v| v.as_bool()), Some(false));
    }

    #[tokio::test]
    async fn pager_terminates_at_max_scan_pages_when_fetcher_ignores_skip() {
        use std::time::Duration;

        let repo_scope = RepoScope::All;

        let res = tokio::time::timeout(
            Duration::from_secs(5),
            run_list_files_with_fetcher(
                Some("auto/**"),
                &repo_scope,
                |_prefix, _repo_names, _skip, _limit| async move {
                    let mut page = Vec::new();
                    page.push(json!({
                        "repo_name": "repo",
                        "file_path": "auto/keep.java",
                        "entity_count": 1,
                    }));
                    for i in 0..1999 {
                        page.push(json!({
                            "repo_name": "repo",
                            "file_path": format!("other/f{i}.java"),
                            "entity_count": 1,
                        }));
                    }
                    Ok(json!(page))
                },
            ),
        )
        .await
        .expect("listing timed out โ€” pager did not terminate")
        .unwrap();

        let files = res.get("files").and_then(|v| v.as_array()).unwrap();
        assert_eq!(files.len(), MAX_SCAN_PAGES);
        assert_eq!(res.get("truncated").and_then(|v| v.as_bool()), Some(true));
        assert_eq!(
            res.get("total_matches").and_then(|v| v.as_u64()),
            Some(MAX_SCAN_PAGES as u64)
        );
        assert_eq!(
            res.get("total_is_lower_bound").and_then(|v| v.as_bool()),
            Some(true)
        );
    }

    #[tokio::test]
    async fn glob_pages_entire_graph_scope_without_dropping_matches() {
        // Create 2500 mock files where only the last 10 match the glob pattern.
        let mut mock_files = Vec::new();
        for i in 0..2490 {
            mock_files.push(json!({
                "repo_name": "spring-ai",
                "file_path": format!("core/src/main/java/File{i}.java"),
                "entity_count": 1,
            }));
        }
        for i in 0..10 {
            mock_files.push(json!({
                "repo_name": "spring-ai",
                "file_path": format!("auto-configurations/src/main/java/Config{i}.java"),
                "entity_count": 2,
            }));
        }

        let repo_scope = RepoScope::All;

        let res = run_list_files_with_fetcher(
            Some("auto-configurations/**/*.java"),
            &repo_scope,
            |prefix, _repo_names, skip, limit| {
                let mock_files = mock_files.clone();
                async move {
                    let filtered: Vec<serde_json::Value> = mock_files
                        .into_iter()
                        .filter(|f| {
                            let path = f.get("file_path").and_then(|v| v.as_str()).unwrap_or("");
                            path.starts_with(&prefix)
                        })
                        .skip(skip)
                        .take(limit)
                        .collect();
                    Ok(json!(filtered))
                }
            },
        )
        .await
        .unwrap();

        let files = res.get("files").and_then(|v| v.as_array()).unwrap();
        assert_eq!(files.len(), 10);
        assert_eq!(res.get("truncated").and_then(|v| v.as_bool()), Some(false));
        assert_eq!(res.get("total_matches").and_then(|v| v.as_u64()), Some(10));
        assert_eq!(
            res.get("total_is_lower_bound").and_then(|v| v.as_bool()),
            Some(false)
        );
    }
}