relay-knowledge 1.1.6

Graph-database-based knowledge graph project.
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
use std::{
    collections::{BTreeMap, BTreeSet},
    path::PathBuf,
};

use crate::domain::{
    CodeImpactPathGroups, CodeRepositoryExcludedPath, CodeRepositoryLanguagePreview,
    CodeRepositoryLargestFile, CodeRepositoryRegistration, CodeRepositoryScopePreview,
    CodeRepositorySelector,
};

use super::{
    CodeIndexError,
    changes::GitTreeEntry,
    languages::language_id,
    parser::dependency_manifest_language_ids,
    parser::dependency_manifest_overrides_default_exclusion,
    snapshot,
    source::{
        FileSystemScanPolicy, RepositorySourceKind, RepositorySourceSnapshot,
        filesystem_source_snapshot, source_snapshot,
    },
    source::{
        explicit_path_filter_opts_into_default_file_exclusion, filesystem_content_hashes_for_paths,
        filesystem_default_source_allows, filesystem_registration_identity,
        filesystem_tree_hash_from_path_hashes, source_commit_is_filesystem,
        source_default_file_preset_excludes, source_kind, source_language_filter_allows,
        source_path_has_indexable_content,
    },
    source_roots::{NESTED_SOURCE_MARKERS, STRIPPABLE_SOURCE_ROOTS},
};

const PREVIEW_MAX_EXCLUDED_PATHS: usize = 50;
const PREVIEW_MAX_LARGEST_FILES: usize = 10;
const DEFAULT_TEXT_FILE_BUDGET_BYTES: usize = 512 * 1024;
const SOURCE_LAYOUT_DISCOVERY_MAX_PATHS: usize = 200_000;
const SOURCE_LAYOUT_DISCOVERY_MAX_ROOTS: usize = 512;
const AUTO_SOURCE_SCOPE_FILTERS: &[&str] = &[".", "src", "include", "lib", "Sources"];

#[derive(Debug, Clone)]
pub(super) struct ScopedSourceSnapshot {
    pub(super) kind: RepositorySourceKind,
    pub(super) root: PathBuf,
    pub(super) resolved_commit_sha: String,
    pub(super) tree_hash: String,
    pub(super) entries: Vec<GitTreeEntry>,
    pub(super) content_hashes: BTreeMap<String, String>,
    pub(super) path_filters: Vec<String>,
    pub(super) language_filters: Vec<String>,
}

pub(super) fn scoped_source_snapshot(
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
    root: &std::path::Path,
    ref_selector: &str,
) -> Result<ScopedSourceSnapshot, CodeIndexError> {
    let allow_filesystem_ref =
        registration_allows_filesystem_ref(registration, root, ref_selector)?;
    scoped_source_snapshot_inner(
        registration,
        selector,
        root,
        ref_selector,
        allow_filesystem_ref,
    )
}

pub(super) fn scoped_source_snapshot_for_filters(
    root: &std::path::Path,
    ref_selector: &str,
    path_filters: &[String],
    language_filters: &[String],
) -> Result<ScopedSourceSnapshot, CodeIndexError> {
    let registration = CodeRepositoryRegistration {
        repository_id: "repo".to_owned(),
        alias: "alias".to_owned(),
        root_path: root.display().to_string(),
        path_filters: path_filters.to_vec(),
        language_filters: language_filters.to_vec(),
    };
    let selector = CodeRepositorySelector {
        repository: "alias".to_owned(),
        ref_selector: ref_selector.to_owned(),
        path_filters: Vec::new(),
        language_filters: Vec::new(),
    };

    scoped_source_snapshot_inner(&registration, &selector, root, ref_selector, true)
}

pub(super) fn scoped_source_snapshot_for_registration(
    registration: &CodeRepositoryRegistration,
    ref_selector: &str,
) -> Result<ScopedSourceSnapshot, CodeIndexError> {
    let root = PathBuf::from(&registration.root_path);
    let selector = CodeRepositorySelector {
        repository: registration.alias.clone(),
        ref_selector: ref_selector.to_owned(),
        path_filters: Vec::new(),
        language_filters: Vec::new(),
    };

    scoped_source_snapshot(registration, &selector, &root, ref_selector)
}

pub(super) fn scoped_source_snapshot_for_registration_filters(
    registration: &CodeRepositoryRegistration,
    ref_selector: &str,
    path_filters: &[String],
    language_filters: &[String],
) -> Result<ScopedSourceSnapshot, CodeIndexError> {
    let root = PathBuf::from(&registration.root_path);
    let selector = CodeRepositorySelector {
        repository: registration.alias.clone(),
        ref_selector: ref_selector.to_owned(),
        path_filters: path_filters.to_vec(),
        language_filters: language_filters.to_vec(),
    };

    scoped_source_snapshot(registration, &selector, &root, ref_selector)
}

fn scoped_source_snapshot_inner(
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
    root: &std::path::Path,
    ref_selector: &str,
    allow_filesystem_ref: bool,
) -> Result<ScopedSourceSnapshot, CodeIndexError> {
    let filesystem_policy = FileSystemScanPolicy::from_path_and_language_filters(
        registration
            .path_filters
            .iter()
            .chain(selector.path_filters.iter()),
        &registration.language_filters,
        &selector.language_filters,
    );
    let snapshot =
        source_snapshot_for_scope(root, ref_selector, filesystem_policy, allow_filesystem_ref)?;
    let source_layout = discover_source_layout(&snapshot.entries);
    let path_filters = effective_index_path_filters(registration, selector, &source_layout);
    let language_filters =
        snapshot::merged_filters(&registration.language_filters, &selector.language_filters);
    let entries = snapshot
        .entries
        .into_iter()
        .filter(|entry| {
            selection_exclusion_reason_for_source(
                &entry.path,
                registration,
                selector,
                &source_layout,
                snapshot.kind,
            )
            .is_none()
        })
        .collect::<Vec<_>>();
    let (resolved_commit_sha, tree_hash, content_hashes) = if snapshot.kind.is_filesystem() {
        scoped_filesystem_tree_hash(&snapshot.root, &entries, ref_selector)?
    } else {
        (
            snapshot.resolved_commit_sha,
            snapshot.tree_hash,
            BTreeMap::new(),
        )
    };

    Ok(ScopedSourceSnapshot {
        kind: snapshot.kind,
        root: snapshot.root,
        resolved_commit_sha,
        tree_hash,
        entries,
        content_hashes,
        path_filters,
        language_filters,
    })
}

fn source_snapshot_for_scope(
    root: &std::path::Path,
    ref_selector: &str,
    filesystem_policy: FileSystemScanPolicy,
    allow_filesystem_ref: bool,
) -> Result<RepositorySourceSnapshot, CodeIndexError> {
    if source_commit_is_filesystem(ref_selector) && allow_filesystem_ref {
        return filesystem_source_snapshot(root, filesystem_policy);
    }

    source_snapshot(root, ref_selector, filesystem_policy)
}

fn registration_allows_filesystem_ref(
    registration: &CodeRepositoryRegistration,
    root: &std::path::Path,
    ref_selector: &str,
) -> Result<bool, CodeIndexError> {
    if !source_commit_is_filesystem(ref_selector) {
        return Ok(false);
    }
    if registration.repository_id == filesystem_registration_identity(root)? {
        return Ok(true);
    }

    Ok(source_kind(root)?.is_filesystem())
}

pub(super) fn scoped_filesystem_tree_hash(
    root: &std::path::Path,
    entries: &[GitTreeEntry],
    ref_selector: &str,
) -> Result<(String, String, BTreeMap<String, String>), CodeIndexError> {
    let paths = entries
        .iter()
        .map(|entry| entry.path.clone())
        .collect::<Vec<_>>();
    let content_hashes = filesystem_content_hashes_for_paths(root, &paths)?;
    let tree_hash = filesystem_tree_hash_from_path_hashes(&content_hashes);
    if source_commit_is_filesystem(ref_selector) && ref_selector != tree_hash {
        return Err(CodeIndexError::InvalidInput(format!(
            "filesystem source snapshot {ref_selector} no longer matches live indexed scope {tree_hash}"
        )));
    }

    Ok((tree_hash.clone(), tree_hash, content_hashes))
}

/// Returns a non-mutating preview of the effective repository indexing scope.
pub fn preview_repository_scope(
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
) -> Result<CodeRepositoryScopePreview, CodeIndexError> {
    let root = PathBuf::from(&registration.root_path);
    let filesystem_policy = FileSystemScanPolicy::from_path_and_language_filters(
        registration
            .path_filters
            .iter()
            .chain(selector.path_filters.iter()),
        &registration.language_filters,
        &selector.language_filters,
    );
    let allow_filesystem_ref =
        registration_allows_filesystem_ref(registration, &root, &selector.ref_selector)?;
    let snapshot = source_snapshot_for_scope(
        &root,
        &selector.ref_selector,
        filesystem_policy,
        allow_filesystem_ref,
    )?;
    let mut selected_byte_count = 0usize;
    let mut selected_file_count = 0usize;
    let mut unsupported_file_count = 0usize;
    let mut generated_or_heavy_file_count = 0usize;
    let mut expected_degraded_file_count = 0usize;
    let mut language_distribution = BTreeMap::<String, (usize, usize)>::new();
    let mut largest_files = Vec::<CodeRepositoryLargestFile>::new();
    let mut excluded_paths = Vec::<CodeRepositoryExcludedPath>::new();

    let entries = snapshot.entries;
    let source_layout = discover_source_layout(&entries);
    let mut selected_entries = Vec::new();
    for entry in entries {
        if let Some(reason) = selection_exclusion_reason_for_source(
            &entry.path,
            registration,
            selector,
            &source_layout,
            snapshot.kind,
        ) {
            if excluded_paths.len() < PREVIEW_MAX_EXCLUDED_PATHS {
                excluded_paths.push(CodeRepositoryExcludedPath {
                    path: entry.path,
                    reason,
                });
            }
            continue;
        }
        let language = preview_language_id(&entry.path);
        selected_file_count += 1;
        selected_byte_count = selected_byte_count.saturating_add(entry.byte_count);
        let bucket = language_distribution
            .entry(language.to_owned())
            .or_insert((0, 0));
        bucket.0 += 1;
        bucket.1 = bucket.1.saturating_add(entry.byte_count);
        let is_unsupported = language == "unknown";
        let is_heavy = entry.byte_count > DEFAULT_TEXT_FILE_BUDGET_BYTES;
        if is_unsupported {
            unsupported_file_count += 1;
        }
        if is_heavy {
            generated_or_heavy_file_count += 1;
        }
        if is_unsupported || is_heavy {
            expected_degraded_file_count += 1;
        }
        largest_files.push(CodeRepositoryLargestFile {
            path: entry.path.clone(),
            byte_count: entry.byte_count,
        });
        selected_entries.push(entry);
    }
    let (resolved_commit_sha, tree_hash, _) = if snapshot.kind.is_filesystem() {
        scoped_filesystem_tree_hash(&snapshot.root, &selected_entries, &selector.ref_selector)?
    } else {
        (
            snapshot.resolved_commit_sha,
            snapshot.tree_hash,
            BTreeMap::new(),
        )
    };
    largest_files.sort_by(|left, right| {
        right
            .byte_count
            .cmp(&left.byte_count)
            .then_with(|| left.path.cmp(&right.path))
    });
    largest_files.truncate(PREVIEW_MAX_LARGEST_FILES);

    Ok(CodeRepositoryScopePreview {
        repository_id: registration.repository_id.clone(),
        alias: registration.alias.clone(),
        requested_ref: selector.ref_selector.clone(),
        resolved_commit_sha,
        tree_hash,
        selected_file_count,
        selected_byte_count,
        unsupported_file_count,
        generated_or_heavy_file_count,
        expected_degraded_file_count,
        language_distribution: language_distribution
            .into_iter()
            .map(
                |(language_id, (file_count, byte_count))| CodeRepositoryLanguagePreview {
                    language_id,
                    file_count,
                    byte_count,
                },
            )
            .collect(),
        largest_files,
        excluded_paths,
    })
}

/// Splits diff paths by the same selector rules used by indexing and impact.
pub fn partition_changed_paths_for_selector(
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
    paths: Vec<String>,
) -> Result<CodeImpactPathGroups, CodeIndexError> {
    if paths.is_empty() {
        return Ok(CodeImpactPathGroups {
            in_scope_changed_paths: Vec::new(),
            out_of_scope_changed_paths: Vec::new(),
        });
    }
    let root = PathBuf::from(&registration.root_path);
    let filesystem_policy = FileSystemScanPolicy::from_path_and_language_filters(
        registration
            .path_filters
            .iter()
            .chain(selector.path_filters.iter()),
        &registration.language_filters,
        &selector.language_filters,
    );
    let (source_layout, source_kind) = if source_commit_is_filesystem(&selector.ref_selector) {
        let snapshot =
            scoped_source_snapshot(registration, selector, &root, &selector.ref_selector)?;
        (discover_source_layout(&snapshot.entries), snapshot.kind)
    } else {
        let snapshot = source_snapshot(&root, &selector.ref_selector, filesystem_policy)?;
        (discover_source_layout(&snapshot.entries), snapshot.kind)
    };
    let mut in_scope_changed_paths = Vec::new();
    let mut out_of_scope_changed_paths = Vec::new();
    for path in paths {
        if selection_exclusion_reason_for_source(
            &path,
            registration,
            selector,
            &source_layout,
            source_kind,
        )
        .is_none()
        {
            in_scope_changed_paths.push(path);
        } else {
            out_of_scope_changed_paths.push(path);
        }
    }
    in_scope_changed_paths.sort();
    in_scope_changed_paths.dedup();
    out_of_scope_changed_paths.sort();
    out_of_scope_changed_paths.dedup();

    Ok(CodeImpactPathGroups {
        in_scope_changed_paths,
        out_of_scope_changed_paths,
    })
}

pub(super) fn path_is_selected(
    path: &str,
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
) -> bool {
    selection_exclusion_reason(path, registration, selector).is_none()
}

pub(super) fn path_is_selected_with_layout(
    path: &str,
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
    source_layout: &SourceLayoutDiscovery,
) -> bool {
    selection_exclusion_reason_with_layout(path, registration, selector, source_layout).is_none()
}

pub(super) fn selection_exclusion_reason(
    path: &str,
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
) -> Option<String> {
    selection_exclusion_reason_with_layout(
        path,
        registration,
        selector,
        &SourceLayoutDiscovery::default(),
    )
}

pub(super) fn selection_exclusion_reason_with_layout(
    path: &str,
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
    source_layout: &SourceLayoutDiscovery,
) -> Option<String> {
    selection_exclusion_reason_for_source(
        path,
        registration,
        selector,
        source_layout,
        RepositorySourceKind::Git,
    )
}

pub(super) fn selection_exclusion_reason_for_source(
    path: &str,
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
    source_layout: &SourceLayoutDiscovery,
    source_kind: RepositorySourceKind,
) -> Option<String> {
    if !path_scope_allows(path, registration, selector)
        && !source_layout.extends_path_scope(path, registration, selector)
    {
        return Some("outside registered/requested path scope".to_owned());
    }
    if source_kind.is_filesystem()
        && filesystem_default_scope_excludes(path, registration, selector)
    {
        return Some("outside non-git default source whitelist".to_owned());
    }
    if !source_language_filter_allows(path, &registration.language_filters)
        || !source_language_filter_allows(path, &selector.language_filters)
    {
        return Some("outside registered/requested language scope".to_owned());
    }
    if source_default_file_preset_excludes(path)
        && !dependency_manifest_overrides_default_exclusion(path)
        && !source_layout.keeps_default_excluded_source(path)
        && !explicit_path_filter_opts_into_default_file_exclusion(
            path,
            registration
                .path_filters
                .iter()
                .chain(selector.path_filters.iter()),
        )
    {
        return Some("excluded by file preset".to_owned());
    }

    None
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct SourceLayoutDiscovery {
    source_roots: BTreeSet<String>,
}

impl SourceLayoutDiscovery {
    fn keeps_default_excluded_source(&self, path: &str) -> bool {
        source_path_has_indexable_content(path)
            && !path_contains_broad_dependency_segment(path)
            && self
                .source_roots
                .iter()
                .any(|root| path_matches_filter(path, root))
    }

    fn extends_path_scope(
        &self,
        path: &str,
        registration: &CodeRepositoryRegistration,
        selector: &CodeRepositorySelector,
    ) -> bool {
        registration_scope_can_discover_source_roots(&registration.path_filters)
            && selector_path_scope_allows_discovered_root(path, &selector.path_filters)
            && self.keeps_default_excluded_source(path)
    }
}

pub(super) fn discover_source_layout(entries: &[GitTreeEntry]) -> SourceLayoutDiscovery {
    let mut source_roots = BTreeSet::new();
    for entry in entries.iter().take(SOURCE_LAYOUT_DISCOVERY_MAX_PATHS) {
        if !source_path_has_indexable_content(&entry.path)
            || path_contains_broad_dependency_segment(&entry.path)
            || source_default_file_preset_excludes(&entry.path)
        {
            continue;
        }
        for root in source_layout_roots_for_path(&entry.path) {
            source_roots.insert(root);
            if source_roots.len() >= SOURCE_LAYOUT_DISCOVERY_MAX_ROOTS {
                return SourceLayoutDiscovery { source_roots };
            }
        }
    }

    SourceLayoutDiscovery { source_roots }
}

pub(super) fn effective_index_path_filters(
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
    source_layout: &SourceLayoutDiscovery,
) -> Vec<String> {
    effective_index_path_filters_for_layouts(registration, selector, &[source_layout])
}

pub(super) fn effective_index_path_filters_for_layouts(
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
    source_layouts: &[&SourceLayoutDiscovery],
) -> Vec<String> {
    let mut filters = merged_path_filters(&registration.path_filters, &selector.path_filters);
    if !registration_scope_can_discover_source_roots(&registration.path_filters) {
        return filters;
    }
    for source_layout in source_layouts {
        for root in &source_layout.source_roots {
            if !selector_filter_allows_root(root, &selector.path_filters) {
                continue;
            }
            push_filter_if_uncovered(&mut filters, root);
        }
    }

    filters
}

fn filesystem_default_scope_excludes(
    path: &str,
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
) -> bool {
    if !registration.path_filters.is_empty() || !selector.path_filters.is_empty() {
        return false;
    }

    !filesystem_default_source_allows(path)
}

fn preview_language_id(path: &str) -> &'static str {
    language_id(path).unwrap_or_else(|| {
        dependency_manifest_language_ids(path)
            .and_then(|languages| languages.first().copied())
            .unwrap_or("unknown")
    })
}

fn path_contains_broad_dependency_segment(path: &str) -> bool {
    normalize_path_filter(path)
        .split('/')
        .any(|segment| matches!(segment, "vendor" | "third_party" | "node_modules"))
}

fn registration_scope_can_discover_source_roots(filters: &[String]) -> bool {
    !filters.is_empty()
        && filters.iter().all(|filter| {
            let filter = normalize_path_filter(filter);
            AUTO_SOURCE_SCOPE_FILTERS.contains(&filter)
        })
}

fn selector_path_scope_allows_discovered_root(path: &str, filters: &[String]) -> bool {
    filters.is_empty()
        || filters
            .iter()
            .any(|filter| path_matches_filter(path, filter))
}

fn selector_filter_allows_root(root: &str, filters: &[String]) -> bool {
    filters.is_empty()
        || filters
            .iter()
            .any(|filter| path_matches_filter(root, filter) || path_overlaps_filter(root, filter))
}

fn merged_path_filters(left: &[String], right: &[String]) -> Vec<String> {
    let mut merged = Vec::new();
    for filter in left.iter().chain(right.iter()) {
        let normalized = normalize_path_filter(filter);
        if !normalized.is_empty() && !merged.iter().any(|existing| existing == normalized) {
            merged.push(normalized.to_owned());
        }
    }

    merged
}

fn push_filter_if_uncovered(filters: &mut Vec<String>, root: &str) {
    if filters
        .iter()
        .any(|filter| path_filter_covers(filter, root))
    {
        return;
    }
    filters.retain(|filter| !path_filter_covers(root, filter));
    filters.push(root.to_owned());
}

fn path_filter_covers(filter: &str, path: &str) -> bool {
    let filter = normalize_path_filter(filter);
    filter == "." || path_matches_filter(path, filter)
}

fn source_layout_roots_for_path(path: &str) -> Vec<String> {
    let path = normalize_path_filter(path);
    let mut roots = Vec::new();
    if path_matches_filter(path, "include") {
        push_source_root(&mut roots, "include".to_owned());
    }
    for marker in NESTED_SOURCE_MARKERS {
        if let Some((prefix, _)) = path.split_once(marker) {
            push_source_root(&mut roots, format!("{prefix}{marker}"));
        }
    }
    for root in STRIPPABLE_SOURCE_ROOTS {
        if let Some(suffix) = path.strip_prefix(root) {
            let mut segments = suffix.split('/').filter(|segment| !segment.is_empty());
            if let Some(first) = segments.next() {
                push_source_root(&mut roots, format!("{root}{first}"));
            } else {
                push_source_root(&mut roots, root.trim_end_matches('/').to_owned());
            }
        }
    }
    roots
}

fn push_source_root(roots: &mut Vec<String>, root: String) {
    let root = root.trim_end_matches('/').to_owned();
    if !root.is_empty() && !roots.contains(&root) {
        roots.push(root);
    }
}

pub(super) fn path_scope_allows(
    path: &str,
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
) -> bool {
    path_filter_allows(path, &registration.path_filters)
        && path_filter_allows(path, &selector.path_filters)
}

pub(super) fn path_scope_overlaps(
    path: &str,
    registration: &CodeRepositoryRegistration,
    selector: &CodeRepositorySelector,
) -> bool {
    path_filter_overlaps(path, &registration.path_filters)
        && path_filter_overlaps(path, &selector.path_filters)
}

fn path_filter_allows(path: &str, filters: &[String]) -> bool {
    filters.is_empty()
        || filters
            .iter()
            .any(|filter| path_matches_filter(path, filter))
}

fn path_filter_overlaps(path: &str, filters: &[String]) -> bool {
    filters.is_empty()
        || filters
            .iter()
            .any(|filter| path_overlaps_filter(path, filter))
}

fn path_matches_filter(path: &str, filter: &str) -> bool {
    let path = normalize_path_filter(path);
    let filter = normalize_path_filter(filter);
    if filter == "." {
        return true;
    }
    !filter.is_empty() && (path == filter || path.starts_with(&format!("{filter}/")))
}

fn path_overlaps_filter(path: &str, filter: &str) -> bool {
    let path = normalize_path_filter(path);
    let filter = normalize_path_filter(filter);
    if filter == "." {
        return true;
    }
    !path.is_empty()
        && !filter.is_empty()
        && (path == filter
            || path.starts_with(&format!("{filter}/"))
            || filter.starts_with(&format!("{path}/")))
}

fn normalize_path_filter(filter: &str) -> &str {
    let mut filter = filter.trim_end_matches(['/', '\\']);
    while let Some(stripped) = filter.strip_prefix("./") {
        filter = stripped;
    }

    filter
}

#[cfg(test)]
mod tests {
    use crate::domain::{CodeRepositoryRegistration, CodeRepositorySelector};

    use super::*;

    #[test]
    fn source_preset_does_not_exclude_tracked_directory_names() {
        for path in [
            "build/workflow.yaml",
            ".cloudbuild/cloudbuild.yaml",
            ".cid/pipeline.yml",
            ".build_config/settings.toml",
            "dist/bundle.js",
            "frontend/dist/js/components/sidebar.js",
            "node_modules/pkg/dist/js/core/index.js",
            "target/generated.rs",
            "vendor/pkg/lib.rs",
            "third_party/pkg/lib.rs",
        ] {
            assert!(!source_default_file_preset_excludes(path), "{path}");
        }
    }

    #[test]
    fn explicit_default_exclusion_opt_in_normalizes_extension_case() {
        let registration = CodeRepositoryRegistration::new(
            "repo",
            "alias",
            "/tmp/repo",
            vec!["assets/logo.SVG".to_owned()],
            Vec::new(),
        )
        .expect("registration should validate");
        let selector = CodeRepositorySelector::new("alias", "HEAD", Vec::new(), Vec::new())
            .expect("selector should validate");

        assert!(path_is_selected(
            "assets/logo.SVG",
            &registration,
            &selector
        ));
    }

    #[test]
    fn default_file_preset_excludes_dataset_dumps_and_keeps_uv_lock_facts() {
        let registration = CodeRepositoryRegistration::new(
            "repo",
            "alias",
            "/tmp/repo",
            vec![".".to_owned()],
            Vec::new(),
        )
        .expect("registration should validate");
        let selector = CodeRepositorySelector::new("alias", "HEAD", Vec::new(), Vec::new())
            .expect("selector should validate");

        assert!(!path_is_selected(
            ".agent_teams/evals/datasets/swebench-verified-full.jsonl",
            &registration,
            &selector
        ));
        assert!(source_default_file_preset_excludes("uv.lock"));
        assert!(path_is_selected("uv.lock", &registration, &selector));
    }

    #[test]
    fn git_tracked_directory_names_are_selected_without_opt_in() {
        let registration = CodeRepositoryRegistration::new(
            "repo",
            "alias",
            "/tmp/repo",
            vec![".".to_owned()],
            Vec::new(),
        )
        .expect("registration should validate");
        let selector = CodeRepositorySelector::new("alias", "HEAD", Vec::new(), Vec::new())
            .expect("selector should validate");

        for path in [
            "build/workflow.yaml",
            ".cloudbuild/cloudbuild.yaml",
            ".cid/pipeline.yml",
            ".build_config/settings.toml",
            "external_deps/python_sdk/session_client.py",
            "packages/ui/src/index.ts",
            "modules/java_sdk/src/main/java/example/SessionClient.java",
            "plugins/example.com/nonstandard/session/client.go",
            "Sources/SwiftSdk/SessionClient.swift",
            "lib/app/controller.rb",
            "vendor/pkg/session_client.py",
            "third_party/pkg/session_client.py",
        ] {
            assert!(path_is_selected(path, &registration, &selector), "{path}");
        }
    }

    #[test]
    fn default_source_preset_keeps_file_extension_opt_in_scoped() {
        let registration = CodeRepositoryRegistration::new(
            "repo",
            "alias",
            "/tmp/repo",
            vec![".".to_owned(), "manual.pdf".to_owned()],
            Vec::new(),
        )
        .expect("registration should validate");
        let selector = CodeRepositorySelector::new("alias", "HEAD", Vec::new(), Vec::new())
            .expect("selector should validate");

        assert!(path_is_selected("manual.pdf", &registration, &selector));
        assert!(!path_is_selected("other.pdf", &registration, &selector));
    }
}