xbp 10.46.0

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
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
//! Project-local ignore rules for XBP discovery, versioning, and worktree-watch.
//!
//! Sources (merged, later sources override earlier for the same pattern text):
//! 1. Built-in skip directories used by service discovery
//! 2. `.xbpignore` at the project root (optional)
//! 3. `.xbp/.xbpignore` (canonical project file)
//! 4. Extra patterns passed by the caller from `.xbp/xbp.yaml`:
//!    - service discovery / version targets → `ignore_paths`
//!      (aliases: `ignored_paths`, `xbpignore`)
//!    - worktree-watch only → `watch_ignore_paths` (alias: `watch_ignore`)
//! 5. Global `~/.xbp/.xbp-worktree-ignore` (worktree-watch only; seeded by XBP)
//!
//! `ignore_paths` never silences worktree-watch; use `watch_ignore_paths` for that.
//!
//! Pattern syntax is a practical gitignore subset:
//! - blank lines and `#` comments are ignored
//! - `!pattern` negates a previous match
//! - trailing `/` matches directories only
//! - leading `/` anchors to the project root
//! - `*` matches within a path segment; `**` matches across segments
//! - unanchored patterns match as a path suffix or any path segment (e.g. `node_modules`)

use std::fs;
use std::path::{Path, PathBuf};

use super::strip_utf8_bom;

/// Filename for machine-wide worktree-watch ignore rules under the global XBP root.
pub const GLOBAL_WORKTREE_IGNORE_FILENAME: &str = ".xbp-worktree-ignore";

/// Directory **names** always skipped for service discovery walks and treated as
/// built-in worktree-watch forbidden folders (any path segment).
///
/// Includes tooling/cache/output trees that must never become services or activity.
pub const DEFAULT_NOISE_DIR_NAMES: &[&str] = &[
    // VCS / editor / agent tooling
    ".git",
    ".github",
    ".hg",
    ".svn",
    ".agents",
    ".cargo",
    ".codex",
    ".cursor",
    ".idea",
    ".postman",
    // Framework / monorepo caches
    ".next",
    ".nx",
    ".open-next",
    ".turbo",
    ".vercel",
    ".xbp",
    ".dist",
    // Dependency / build output
    "node_modules",
    "target",
    "target-publish",
    "dist",
    "build",
    "out",
    "coverage",
    "tmp",
    "vendor",
    "venv",
    ".venv",
    "__pycache__",
    // Local agent / CLI session noise
    "terminals",
    // Agent / MCP workspaces
    "mcps",
    "agent-tools",
];

/// Alias used by service discovery (`WalkDir` skip + project ignore seed).
pub const DEFAULT_DISCOVERY_SKIP_DIRS: &[&str] = DEFAULT_NOISE_DIR_NAMES;

/// Default gitignore-style patterns always merged into `~/.xbp/.xbp-worktree-ignore`.
/// Kept in sync with [`DEFAULT_NOISE_DIR_NAMES`] plus anchored root forms.
pub const DEFAULT_GLOBAL_WORKTREE_IGNORE_PATTERNS: &[&str] = &[
    // Tooling
    ".agents/",
    ".cargo/",
    ".codex/",
    ".cursor/",
    ".git/",
    ".github/",
    ".idea/",
    ".postman/",
    ".xbp/",
    // Framework caches
    ".next/",
    ".nx/",
    ".open-next/",
    ".turbo/",
    ".vercel/",
    ".dist/",
    // Build / deps
    "target/",
    "target-publish/",
    "/target-publish/",
    "dist/",
    "build/",
    "out/",
    "coverage/",
    "node_modules/",
    "tmp/",
    "vendor/",
    "venv/",
    ".venv/",
    "__pycache__/",
    // Local agent / CLI session noise
    "terminals/",
    "/terminals/",
    // Agent workspaces (also anchored)
    "mcps/",
    "/mcps/",
    "agent-tools/",
    "/agent-tools/",
];

#[derive(Debug, Clone, PartialEq, Eq)]
struct IgnorePattern {
    raw: String,
    negated: bool,
    dir_only: bool,
    /// Pattern body after stripping `!` and trailing `/`, normalized to `/`.
    body: String,
    anchored: bool,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct XbpIgnoreSet {
    patterns: Vec<IgnorePattern>,
}

impl XbpIgnoreSet {
    pub fn empty() -> Self {
        Self {
            patterns: Vec::new(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.patterns.is_empty()
    }

    pub fn patterns(&self) -> impl Iterator<Item = &str> {
        self.patterns.iter().map(|pattern| pattern.raw.as_str())
    }

    pub fn from_patterns<I, S>(patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut set = Self::empty();
        set.extend_patterns(patterns);
        set
    }

    pub fn from_file_content(content: &str) -> Self {
        let mut set = Self::empty();
        set.extend_file_content(content);
        set
    }

    pub fn extend_patterns<I, S>(&mut self, patterns: I)
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        for pattern in patterns {
            if let Some(parsed) = parse_ignore_pattern(pattern.as_ref()) {
                self.patterns.push(parsed);
            }
        }
    }

    pub fn extend_file_content(&mut self, content: &str) {
        let stripped = strip_utf8_bom(content);
        for line in stripped.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }
            if let Some(parsed) = parse_ignore_pattern(trimmed) {
                self.patterns.push(parsed);
            }
        }
    }

    pub fn merge(&mut self, other: &XbpIgnoreSet) {
        self.patterns.extend(other.patterns.iter().cloned());
    }

    /// True when the relative path should be ignored.
    ///
    /// `is_dir` should be true when the path is known to be a directory (walk
    /// filtering, service roots). When unknown, pass `false` so file-oriented
    /// patterns still apply and directory-only patterns only match if the path
    /// looks like a directory prefix match via children is not required.
    pub fn is_ignored_relative(&self, relative: &str, is_dir: bool) -> bool {
        let normalized = normalize_relative_path(relative);
        if normalized.is_empty() || normalized == "." {
            return false;
        }

        let mut ignored = false;
        for pattern in &self.patterns {
            if pattern_matches(pattern, &normalized, is_dir) {
                ignored = !pattern.negated;
            }
        }
        ignored
    }

    pub fn is_ignored_path(&self, project_root: &Path, path: &Path) -> bool {
        let relative = match path.strip_prefix(project_root) {
            Ok(rel) => rel.to_string_lossy().replace('\\', "/"),
            Err(_) => path.to_string_lossy().replace('\\', "/"),
        };
        let is_dir = path.is_dir();
        self.is_ignored_relative(&relative, is_dir)
    }

    /// True when a directory entry should not be descended into during discovery.
    pub fn skips_dir_name(&self, dir_name: &str) -> bool {
        let name = dir_name.trim().trim_matches(|ch| ch == '/' || ch == '\\');
        if name.is_empty() || name == "." || name == ".." {
            return false;
        }
        // Bare folder names in patterns (and built-ins expressed as such).
        self.is_ignored_relative(name, true)
    }

    /// True when a service root directory (project-relative) is ignored.
    pub fn ignores_service_root(&self, root_directory: &str) -> bool {
        let normalized = normalize_relative_path(root_directory);
        if normalized.is_empty() || normalized == "." {
            return false;
        }
        self.is_ignored_relative(&normalized, true)
    }

    /// True when a version target path should be excluded from versioning.
    pub fn ignores_version_target(&self, target: &str) -> bool {
        let normalized = normalize_relative_path(target);
        if normalized.is_empty() {
            return false;
        }
        // Version manifests are files; also ignore when a parent directory is banned.
        if self.is_ignored_relative(&normalized, false) {
            return true;
        }
        // Parent path segments: packages/icons/package.json → packages/icons
        if let Some(parent) = Path::new(&normalized).parent() {
            let parent_rel = parent.to_string_lossy().replace('\\', "/");
            if !parent_rel.is_empty() && parent_rel != "." {
                return self.is_ignored_relative(&parent_rel, true);
            }
        }
        false
    }
}

/// Load ignore rules for a project root.
///
/// Order: optional extra patterns (e.g. from yaml) are applied after files so
/// config can refine file rules. Built-in discovery skip dirs are always first.
pub fn load_project_xbp_ignore(project_root: &Path, extra_patterns: &[String]) -> XbpIgnoreSet {
    let mut set = XbpIgnoreSet::from_patterns(
        DEFAULT_DISCOVERY_SKIP_DIRS
            .iter()
            .map(|name| (*name).to_string()),
    );

    for candidate in xbp_ignore_file_candidates(project_root) {
        if let Ok(content) = fs::read_to_string(&candidate) {
            set.extend_file_content(&content);
        }
    }

    if !extra_patterns.is_empty() {
        set.extend_patterns(extra_patterns.iter().map(String::as_str));
    }

    set
}

/// Canonical ignore file paths for a project (existence not required).
pub fn xbp_ignore_file_candidates(project_root: &Path) -> Vec<PathBuf> {
    vec![
        project_root.join(".xbpignore"),
        project_root.join(".xbp").join(".xbpignore"),
    ]
}

pub fn default_xbp_ignore_path(project_root: &Path) -> PathBuf {
    project_root.join(".xbp").join(".xbpignore")
}

/// Initial contents written when the global worktree-watch ignore file is first created.
pub fn default_global_worktree_ignore_content() -> String {
    let mut lines = vec![
        "# Global worktree-watch ignore patterns (gitignore-style syntax).".to_string(),
        "# Managed by XBP at ~/.xbp/.xbp-worktree-ignore (platform equivalent).".to_string(),
        "# Edit to add machine-wide paths excluded from worktree-watch activity.".to_string(),
        "# Built-in noise dirs (target, .next, .xbp, mcps, …) are also hard-coded in the CLI.".to_string(),
        String::new(),
    ];
    for pattern in DEFAULT_GLOBAL_WORKTREE_IGNORE_PATTERNS {
        lines.push((*pattern).to_string());
    }
    lines.push(String::new());
    lines.join("\n")
}

/// Load global worktree-watch ignore rules from the given file (missing file → empty set).
pub fn load_global_worktree_ignore_from_path(path: &Path) -> XbpIgnoreSet {
    match fs::read_to_string(path) {
        Ok(content) => XbpIgnoreSet::from_file_content(&content),
        Err(_) => XbpIgnoreSet::empty(),
    }
}

/// Ensure default MCP ignore patterns exist in the global worktree-watch ignore file.
pub fn sync_global_worktree_ignore_file(path: &Path) -> Result<(), String> {
    if !path.exists() {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|error| {
                format!(
                    "Failed to create global worktree-ignore directory {}: {error}",
                    parent.display()
                )
            })?;
        }
        fs::write(path, default_global_worktree_ignore_content()).map_err(|error| {
            format!(
                "Failed to write global worktree-ignore file {}: {error}",
                path.display()
            )
        })?;
        return Ok(());
    }

    let content = fs::read_to_string(path).map_err(|error| {
        format!(
            "Failed to read global worktree-ignore file {}: {error}",
            path.display()
        )
    })?;

    let existing_patterns = content
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .map(|line| line.trim_end_matches('/').to_string())
        .collect::<Vec<_>>();

    let missing = DEFAULT_GLOBAL_WORKTREE_IGNORE_PATTERNS
        .iter()
        .copied()
        .filter(|pattern| {
            let normalized = pattern.trim_end_matches('/');
            !existing_patterns.iter().any(|existing| {
                existing == normalized || existing == *pattern
            })
        })
        .collect::<Vec<_>>();

    if missing.is_empty() {
        return Ok(());
    }

    let mut updated = content;
    if !updated.ends_with('\n') {
        updated.push('\n');
    }
    updated.push_str("\n# Added by XBP (default worktree-watch exclusions)\n");
    for pattern in missing {
        updated.push_str(pattern);
        updated.push('\n');
    }

    fs::write(path, updated).map_err(|error| {
        format!(
            "Failed to update global worktree-ignore file {}: {error}",
            path.display()
        )
    })
}

fn parse_ignore_pattern(raw: &str) -> Option<IgnorePattern> {
    let trimmed = raw.trim();
    if trimmed.is_empty() || trimmed.starts_with('#') {
        return None;
    }

    let (negated, rest) = if let Some(rest) = trimmed.strip_prefix('!') {
        (true, rest.trim())
    } else {
        (false, trimmed)
    };
    if rest.is_empty() {
        return None;
    }

    let dir_only = rest.ends_with('/');
    let without_slash = rest.trim_end_matches(|ch| ch == '/' || ch == '\\');
    let normalized = without_slash.replace('\\', "/");
    let anchored = normalized.starts_with('/');
    let body = normalized
        .trim_start_matches('/')
        .trim_start_matches("./")
        .trim_matches('/')
        .to_string();
    if body.is_empty() {
        return None;
    }

    Some(IgnorePattern {
        raw: trimmed.to_string(),
        negated,
        dir_only,
        body,
        anchored,
    })
}

fn normalize_relative_path(raw: &str) -> String {
    raw.trim()
        .replace('\\', "/")
        .trim_start_matches("./")
        .trim_matches('/')
        .to_string()
}

fn pattern_matches(pattern: &IgnorePattern, path: &str, is_dir: bool) -> bool {
    if pattern.dir_only && !is_dir {
        // Directory-only patterns still match when the path is under that directory.
        // Example: `docs/` ignores `docs/readme.md`.
        let prefix = &pattern.body;
        if path == *prefix || path.starts_with(&format!("{prefix}/")) {
            // file under ignored dir → ignored
            return path != *prefix || is_dir;
        }
        // For exact file path that equals a dir pattern name without being a dir,
        // treat as no match unless path is under it.
        if path == *prefix {
            return false;
        }
        // Unanchored dir pattern: match if any ancestor segment path matches.
        return path_has_directory_match(path, pattern);
    }

    if pattern.anchored {
        return path_glob_match(&pattern.body, path)
            || (!pattern.dir_only && path_is_under_glob(&pattern.body, path));
    }

    // Unanchored: match full path, any suffix path, or a single path component.
    if path_glob_match(&pattern.body, path) {
        return true;
    }
    if path_is_under_glob(&pattern.body, path) {
        return true;
    }

    // Single-segment patterns match any path component (gitignore behavior).
    if !pattern.body.contains('/') && !pattern.body.contains("**") {
        return path
            .split('/')
            .any(|component| path_glob_match(&pattern.body, component));
    }

    // Multi-segment unanchored: match if any suffix matches the pattern.
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    for start in 0..segments.len() {
        let suffix = segments[start..].join("/");
        if path_glob_match(&pattern.body, &suffix)
            || path_is_under_glob(&pattern.body, &suffix)
        {
            return true;
        }
    }

    false
}

fn path_has_directory_match(path: &str, pattern: &IgnorePattern) -> bool {
    if pattern.anchored {
        return path == pattern.body || path.starts_with(&format!("{}/", pattern.body));
    }
    if !pattern.body.contains('/') && !pattern.body.contains('*') {
        return path
            .split('/')
            .any(|component| component.eq_ignore_ascii_case(&pattern.body));
    }
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    for start in 0..segments.len() {
        let suffix = segments[start..].join("/");
        if path_glob_match(&pattern.body, &suffix)
            || suffix.starts_with(&format!("{}/", pattern.body))
            || path_is_under_glob(&pattern.body, &suffix)
        {
            return true;
        }
    }
    false
}

fn path_is_under_glob(pattern: &str, path: &str) -> bool {
    // If pattern matches a parent of path, path is ignored.
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    for end in 1..segments.len() {
        let parent = segments[..end].join("/");
        if path_glob_match(pattern, &parent) {
            return true;
        }
    }
    false
}

/// Glob match with `*` (segment-local) and `**` (cross-segment).
fn path_glob_match(pattern: &str, path: &str) -> bool {
    let pattern = pattern.trim_matches('/');
    let path = path.trim_matches('/');
    if pattern == "**" {
        return true;
    }
    glob_match_segments(
        &split_glob_segments(pattern),
        &path.split('/').filter(|s| !s.is_empty()).collect::<Vec<_>>(),
    )
}

fn split_glob_segments(pattern: &str) -> Vec<&str> {
    pattern.split('/').filter(|s| !s.is_empty()).collect()
}

fn glob_match_segments(pattern: &[&str], path: &[&str]) -> bool {
    fn rec(p: &[&str], s: &[&str]) -> bool {
        match (p.first().copied(), s.first().copied()) {
            (None, None) => true,
            (Some("**"), _) => {
                // `**` matches zero or more segments, then the rest of the pattern.
                if rec(&p[1..], s) {
                    return true;
                }
                // Consume one path segment and keep `**`.
                if s.is_empty() {
                    return false;
                }
                rec(p, &s[1..])
            }
            (Some(pat), Some(seg)) => {
                if segment_glob_match(pat, seg) {
                    rec(&p[1..], &s[1..])
                } else {
                    false
                }
            }
            (Some(_), None) | (None, Some(_)) => false,
        }
    }
    rec(pattern, path)
}

fn segment_glob_match(pattern: &str, segment: &str) -> bool {
    if pattern == "*" {
        return true;
    }
    if !pattern.contains('*') {
        return pattern == segment;
    }

    // Simple `*` wildcards within a single segment.
    let parts: Vec<&str> = pattern.split('*').collect();
    if parts.len() == 1 {
        return pattern == segment;
    }

    let mut rest = segment;
    for (index, part) in parts.iter().enumerate() {
        if part.is_empty() {
            continue;
        }
        if index == 0 {
            if !rest.starts_with(part) {
                return false;
            }
            rest = &rest[part.len()..];
            continue;
        }
        if index == parts.len() - 1 {
            return rest.ends_with(part);
        }
        if let Some(pos) = rest.find(part) {
            rest = &rest[pos + part.len()..];
        } else {
            return false;
        }
    }
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_root(name: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos();
        let path = std::env::temp_dir().join(format!("xbp-ignore-{name}-{nanos}"));
        let _ = fs::remove_dir_all(&path);
        fs::create_dir_all(path.join(".xbp")).expect("mkdir");
        path
    }

    #[test]
    fn matches_unanchored_folder_anywhere() {
        let set = XbpIgnoreSet::from_patterns(["node_modules"]);
        assert!(set.is_ignored_relative("node_modules", true));
        assert!(set.is_ignored_relative("apps/web/node_modules", true));
        assert!(set.is_ignored_relative("apps/web/node_modules/pkg/index.js", false));
        assert!(!set.is_ignored_relative("apps/web/src/main.ts", false));
    }

    #[test]
    fn matches_anchored_and_directory_only_patterns() {
        let set = XbpIgnoreSet::from_patterns(["/docs/", "packages/icons"]);
        assert!(set.is_ignored_relative("docs", true));
        assert!(set.is_ignored_relative("docs/guide.md", false));
        assert!(!set.is_ignored_relative("apps/docs/guide.md", false));
        assert!(set.is_ignored_relative("packages/icons", true));
        assert!(set.is_ignored_relative("packages/icons/package.json", false));
        assert!(!set.is_ignored_relative("packages/web/package.json", false));
    }

    #[test]
    fn supports_negation() {
        let set = XbpIgnoreSet::from_patterns(["secrets/", "!secrets/public.env"]);
        assert!(set.is_ignored_relative("secrets/private.key", false));
        assert!(!set.is_ignored_relative("secrets/public.env", false));
    }

    #[test]
    fn loads_dot_xbp_ignore_and_yaml_patterns() {
        let root = temp_root("load");
        fs::write(
            root.join(".xbp").join(".xbpignore"),
            "# project ignores\npackages/icons/\n*.snap\n",
        )
        .expect("write ignore");
        fs::write(root.join(".xbpignore"), "legacy-root-ignore/\n").expect("write root ignore");

        let set = load_project_xbp_ignore(
            &root,
            &["e2e/".to_string(), "packages/icons/README.md".to_string()],
        );

        assert!(set.ignores_service_root("packages/icons"));
        assert!(set.ignores_version_target("packages/icons/package.json"));
        assert!(set.is_ignored_relative("legacy-root-ignore/foo", false));
        assert!(set.is_ignored_relative("e2e/test.spec.ts", false));
        assert!(set.is_ignored_relative("apps/web/__snapshots__/a.snap", false));
        // built-in
        assert!(set.skips_dir_name("node_modules"));
        assert!(set.skips_dir_name("target"));

        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn global_mcps_patterns_ignore_nested_paths() {
        let set = XbpIgnoreSet::from_patterns(DEFAULT_GLOBAL_WORKTREE_IGNORE_PATTERNS);
        assert!(set.is_ignored_relative("mcps", true));
        assert!(set.is_ignored_relative("mcps/github/tools", false));
        assert!(set.is_ignored_relative("apps/api/mcps/local", true));
        assert!(set.is_ignored_relative("mcps/catalog.json", false));
        assert!(!set.is_ignored_relative("apps/web/src/main.ts", false));
    }

    #[test]
    fn sync_global_worktree_ignore_seeds_defaults() {
        let root = temp_root("global-watch-ignore");
        let path = root.join(GLOBAL_WORKTREE_IGNORE_FILENAME);
        sync_global_worktree_ignore_file(&path).expect("seed");
        let content = fs::read_to_string(&path).expect("read");
        assert!(content.contains("mcps/"));
        let set = load_global_worktree_ignore_from_path(&path);
        assert!(set.is_ignored_relative("packages/foo/mcps/bar.json", false));
        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn glob_double_star_and_star_segment() {
        let set = XbpIgnoreSet::from_patterns(["**/dist", "apps/*/tmp"]);
        assert!(set.is_ignored_relative("packages/foo/dist/index.js", false));
        assert!(set.is_ignored_relative("dist", true));
        assert!(set.is_ignored_relative("apps/web/tmp", true));
        assert!(set.is_ignored_relative("apps/web/tmp/cache", false));
        assert!(!set.is_ignored_relative("apps/web/src/tmp-file.ts", false));
    }
}