symforge 11.5.2

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
//! Worktree-aware path resolution for edit tools.
//!
//! SymForge indexes one repo path and stores absolute file paths in its
//! index. When an agent runs from inside a parallel `git worktree` that
//! shares the same `.git` objects, an edit that resolves against the
//! indexed absolute path silently writes to the *indexed* repo copy
//! instead of the agent's own working tree. The resolver below implements
//! explicit call-time routing through the `working_directory` edit parameter.
//!
//! The edit handlers call [`resolve_target_path`] before writing. When
//! `working_directory` is `None`, behavior is byte-identical to pre-routing
//! releases (write to the indexed absolute path). When `Some`, the path
//! is re-rooted against the working directory and validated against a
//! cached `git worktree list`, refreshed on cache miss.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};

use parking_lot::Mutex;

use crate::capability::WorktreeRoutingPolicy;
use crate::protocol::edit_hooks::{EditContext, EditHook};

pub const WORKTREE_ROUTING_ENV: &str = "SYMFORGE_WORKTREE_AWARE";

/// A worktree known to be associated with the indexed root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorktreeEntry {
    /// Canonical absolute path to the worktree root (main or linked).
    pub path: PathBuf,
}

/// Outcome of [`resolve_target_path`]: where the edit should land, plus
/// where the index believes the file lives, plus a flag flipping true
/// iff the two differ.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedTarget {
    /// Absolute path the tool should write to.
    pub target_path: PathBuf,
    /// Absolute path from the index (always the indexed-root copy).
    pub indexed_path: PathBuf,
    /// `true` when `target_path != indexed_path`.
    pub rerouted: bool,
}

/// Errors produced by worktree-aware resolution.
///
/// `Display` intentionally leads with the variant name so MCP tool output
/// exposes a stable, grep-friendly error tag (see
/// `tests/worktree_awareness.rs` AC4/AC6). Hints follow as plain prose so
/// callers can act without looking up docs.
#[derive(Debug, thiserror::Error)]
pub enum WorktreeError {
    #[error(
        "WorkingDirectoryNotARecognizedWorktree: working_directory `{}` is not a recognized worktree of `{}` — {hint}",
        cwd.display(), indexed_root.display()
    )]
    WorkingDirectoryNotARecognizedWorktree {
        cwd: PathBuf,
        indexed_root: PathBuf,
        hint: String,
    },

    #[error("TargetFileMissing: target file `{}` does not exist — {hint}", path.display())]
    TargetFileMissing { path: PathBuf, hint: String },

    #[error("TargetPathRefused: rerouted target `{}` is refused — {reason}", path.display())]
    TargetPathRefused { path: PathBuf, reason: String },

    #[error(
        "PathOutsideIndexedRoot: indexed path `{}` is not under the indexed root `{}`",
        path.display(), indexed_root.display()
    )]
    PathOutsideIndexedRoot {
        path: PathBuf,
        indexed_root: PathBuf,
    },

    #[error("filesystem error: {0}")]
    Io(#[from] std::io::Error),

    #[error("`git worktree list` failed: {0}")]
    GitWorktreeList(String),

    #[error(
        "WorktreeRoutingDisabledByPolicy: working_directory `{}` requested worktree routing, but worktree routing is disabled by policy — {hint}",
        cwd.display()
    )]
    WorktreeRoutingDisabledByPolicy { cwd: PathBuf, hint: String },
}

/// Canonicalize a path, returning a clean form without the `\\?\` UNC
/// prefix on Windows. Delegates to `dunce::canonicalize` which falls
/// back to `std::fs::canonicalize` on non-Windows.
///
/// The returned path has no trailing separator — `dunce` and the
/// platform canonicalizer both normalize this away.
pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
    dunce::canonicalize(path)
}

/// Best-effort canonicalize. Falls back to the input when the target
/// does not exist — useful for paths produced by symbolic lookups that
/// may name files not yet on disk.
fn canonicalize_or_identity(path: &Path) -> PathBuf {
    canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

/// Cache of known worktrees, FENCED per indexed root (Feature 020 Slice 4,
/// C4c cache census). Populated on demand by `refresh()`; `lookup()`
/// refreshes once on cache miss before concluding the directory is unknown.
///
/// The fence is the point: the hook holding this cache is process-wide,
/// and a hit may only be served from entries the REQUESTING root's own
/// `git worktree list` produced. Before the fence, entries cached for
/// project A satisfied lookups for project B and authorized rerouting B's
/// edit into A's worktree — a routing decision a fresh listing against B
/// would refuse. A cache must never be more permissive than the
/// observation it stands in for.
#[derive(Debug, Default)]
pub struct WorktreeCache {
    roots: HashMap<PathBuf, RootWorktrees>,
}

/// One indexed root's slice of the cache.
#[derive(Debug, Default)]
struct RootWorktrees {
    entries: HashMap<PathBuf, WorktreeEntry>,
    last_refreshed: Option<Instant>,
}

impl WorktreeCache {
    /// Empty cache. The first `lookup` will trigger a refresh.
    pub fn new() -> Self {
        Self::default()
    }

    /// The canonical key one indexed root's entries live under. Callers
    /// pass roots in whatever spelling they hold; convergence here keeps
    /// insert/lookup/refresh on one slice per physical root.
    fn root_key(indexed_root: &Path) -> PathBuf {
        canonicalize_or_identity(indexed_root)
    }

    /// Inject a worktree entry directly under `indexed_root`'s slice.
    /// Primarily used by tests that want to exercise the resolution
    /// algorithm without shelling out to `git`.
    pub fn insert(&mut self, indexed_root: &Path, path: PathBuf) {
        self.roots
            .entry(Self::root_key(indexed_root))
            .or_default()
            .entries
            .insert(path.clone(), WorktreeEntry { path });
    }

    /// Number of cached worktree entries across all roots.
    pub fn len(&self) -> usize {
        self.roots.values().map(|slice| slice.entries.len()).sum()
    }

    /// Whether the cache holds no entries.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Timestamp of the most recent successful refresh across all roots,
    /// if any.
    pub fn last_refreshed(&self) -> Option<Instant> {
        self.roots
            .values()
            .filter_map(|slice| slice.last_refreshed)
            .max()
    }

    /// Canonicalize `dir` and look it up WITHIN `indexed_root`'s slice.
    /// On a miss, force one refresh of that slice (cheap — single `git`
    /// invocation) and try again.
    ///
    /// Returns `Ok(Some(entry))` when the directory resolves to a
    /// worktree of `indexed_root`, `Ok(None)` when the refresh completed
    /// cleanly but the directory is still unknown to that root.
    pub fn lookup(
        &mut self,
        dir: &Path,
        indexed_root: &Path,
    ) -> Result<Option<WorktreeEntry>, WorktreeError> {
        let canon = canonicalize(dir)?;
        let key = Self::root_key(indexed_root);
        if let Some(entry) = self
            .roots
            .get(&key)
            .and_then(|slice| slice.entries.get(&canon))
        {
            return Ok(Some(entry.clone()));
        }
        self.refresh(indexed_root)?;
        Ok(self
            .roots
            .get(&key)
            .and_then(|slice| slice.entries.get(&canon).cloned()))
    }

    /// Wipe `indexed_root`'s slice and repopulate it from `git -C
    /// <indexed_root> worktree list --porcelain`. Other roots' slices are
    /// untouched. Callers rarely need this directly; `lookup` calls it on
    /// cache miss.
    pub fn refresh(&mut self, indexed_root: &Path) -> Result<(), WorktreeError> {
        let paths = list_worktrees(indexed_root)?;
        let slice = self.roots.entry(Self::root_key(indexed_root)).or_default();
        slice.entries.clear();
        for path in paths {
            slice.entries.insert(path.clone(), WorktreeEntry { path });
        }
        slice.last_refreshed = Some(Instant::now());
        Ok(())
    }

    /// Read-only view of the cached paths across all roots in no
    /// particular order. Useful for diagnostics (e.g. building `health`
    /// output).
    pub fn paths(&self) -> impl Iterator<Item = &Path> {
        self.roots
            .values()
            .flat_map(|slice| slice.entries.keys().map(|p| p.as_path()))
    }
}

/// Re-root an indexed absolute path against an optional working
/// directory, applying the spec §2.2 resolution algorithm.
///
/// * `working_directory = None` or equal to the canonical indexed root
///   → pass through unchanged (`rerouted = false`).
/// * Otherwise the directory must be a known worktree of the indexed
///   root (cache refresh on miss). The target file must exist in that
///   worktree; otherwise `TargetFileMissing` with a hint.
pub fn resolve_target_path(
    indexed_abs: &Path,
    indexed_root: &Path,
    working_directory: Option<&Path>,
    cache: &mut WorktreeCache,
) -> Result<ResolvedTarget, WorktreeError> {
    let Some(raw_wd) = working_directory else {
        return Ok(ResolvedTarget {
            target_path: indexed_abs.to_path_buf(),
            indexed_path: indexed_abs.to_path_buf(),
            rerouted: false,
        });
    };

    let canonical_indexed_abs = canonicalize_or_identity(indexed_abs);
    let canonical_indexed_root = canonicalize(indexed_root)?;

    // Canonicalize fails with NotFound when the supplied working_directory
    // doesn't exist on disk (e.g. a typo or a yet-to-be-created worktree
    // path). Treat that as "not a recognized worktree" rather than a raw IO
    // error — it's the same user-facing condition and the tests
    // (`matrix_cache_refresh_newly_created_worktree_accepted`) assert this.
    let canonical_wd = match canonicalize(raw_wd) {
        Ok(p) => p,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(WorktreeError::WorkingDirectoryNotARecognizedWorktree {
                cwd: raw_wd.to_path_buf(),
                indexed_root: canonical_indexed_root,
                hint: "pass a path that is the root of a `git worktree list` entry, or omit to write to the indexed root".to_string(),
            });
        }
        Err(e) => return Err(WorktreeError::Io(e)),
    };
    if canonical_wd == canonical_indexed_root {
        return Ok(ResolvedTarget {
            target_path: canonical_indexed_abs.clone(),
            indexed_path: canonical_indexed_abs,
            rerouted: false,
        });
    }

    let relative = canonical_indexed_abs
        .strip_prefix(&canonical_indexed_root)
        .map_err(|_| WorktreeError::PathOutsideIndexedRoot {
            path: canonical_indexed_abs.clone(),
            indexed_root: canonical_indexed_root.clone(),
        })?;

    let entry = cache.lookup(&canonical_wd, &canonical_indexed_root)?;
    if entry.is_none() {
        return Err(WorktreeError::WorkingDirectoryNotARecognizedWorktree {
            cwd: canonical_wd,
            indexed_root: canonical_indexed_root,
            hint: "pass a path that is the root of a `git worktree list` entry, or omit to write to the indexed root".to_string(),
        });
    }

    let target_path = canonical_wd.join(relative);
    // The target is read and written, so it must be the worktree's own file
    // under its own name. It is resolved like any caller path beneath that
    // root: a link out of the worktree or another spelling of a file is
    // refused before anything opens it.
    match crate::discovery::resolve_repo_path(&canonical_wd, &relative.to_string_lossy()) {
        Ok(Some(_)) => {}
        Ok(None) => {
            return Err(WorktreeError::TargetFileMissing {
                path: target_path,
                hint: "the worktree may be at a commit where this file does not yet exist; check `git ls-tree HEAD <relative_path>` in the worktree".to_string(),
            });
        }
        Err(refusal) => {
            return Err(WorktreeError::TargetPathRefused {
                path: target_path,
                reason: format!("{refusal:?}"),
            });
        }
    }

    Ok(ResolvedTarget {
        target_path,
        indexed_path: canonical_indexed_abs,
        rerouted: true,
    })
}

/// Shell out to `git -C <indexed_root> worktree list --porcelain` and
/// return the canonicalized root path of every worktree (main + linked).
///
/// We shell out rather than using `git2` because the porcelain format
/// is stable, handles every edge case (bare, detached, locked, prunable)
/// uniformly, and the call only happens on cache miss.
fn list_worktrees(indexed_root: &Path) -> Result<Vec<PathBuf>, WorktreeError> {
    let output = crate::process_util::hidden_command("git")
        .arg("-C")
        .arg(indexed_root)
        .arg("worktree")
        .arg("list")
        .arg("--porcelain")
        .output()
        .map_err(|e| WorktreeError::GitWorktreeList(format!("spawn failed: {e}")))?;

    if !output.status.success() {
        return Err(WorktreeError::GitWorktreeList(format!(
            "exit {}: {}",
            output.status,
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }

    Ok(parse_porcelain(&String::from_utf8_lossy(&output.stdout)))
}

/// Parse `git worktree list --porcelain`. Each block opens with
/// `worktree <abs-path>`; we take that line, canonicalize it, and skip
/// the rest. Blank lines separate blocks and are ignored.
fn parse_porcelain(input: &str) -> Vec<PathBuf> {
    let mut out = Vec::new();
    for line in input.lines() {
        let Some(rest) = line.strip_prefix("worktree ") else {
            continue;
        };
        let raw = PathBuf::from(rest.trim());
        match canonicalize(&raw) {
            Ok(canon) => out.push(canon),
            Err(_) => out.push(raw),
        }
    }
    out
}

/// [`EditHook`] implementation that reroutes edits into a sibling `git
/// worktree` when the caller supplies `working_directory`. Holds one
/// shared [`WorktreeCache`] so repeated calls in the same session avoid
/// re-shelling out to `git worktree list`.
pub struct WorktreeAwareEditHook {
    cache: Mutex<WorktreeCache>,
}

impl WorktreeAwareEditHook {
    pub fn new() -> Self {
        Self {
            cache: Mutex::new(WorktreeCache::new()),
        }
    }
}

impl Default for WorktreeAwareEditHook {
    fn default() -> Self {
        Self::new()
    }
}

impl EditHook for WorktreeAwareEditHook {
    fn resolve_target_path(&self, ctx: &EditContext) -> Result<ResolvedTarget, String> {
        if let Some(cwd) = ctx.working_directory
            && routing_policy_from_env() == WorktreeRoutingPolicy::Disabled
        {
            return Err(WorktreeError::WorktreeRoutingDisabledByPolicy {
                cwd: cwd.to_path_buf(),
                hint: format!(
                    "unset {WORKTREE_ROUTING_ENV} or set it to `1`/`true`/`on` to allow explicit call-time routing"
                ),
            }
            .to_string());
        }
        let mut cache = self.cache.lock();
        resolve_target_path(
            ctx.indexed_absolute_path,
            ctx.repo_root,
            ctx.working_directory,
            &mut cache,
        )
        .map_err(|e| e.to_string())
    }
}

/// Interpret the transitional worktree-routing env var as policy. Unset means
/// explicit call-time routing is allowed; false/off/disabled values block
/// requested routing before any write.
pub fn routing_policy_from_env() -> WorktreeRoutingPolicy {
    match std::env::var(WORKTREE_ROUTING_ENV) {
        Ok(value) => match value.trim().to_ascii_lowercase().as_str() {
            "" | "1" | "true" | "yes" | "on" | "explicit" | "explicit-call-time"
            | "explicit_call_time" => WorktreeRoutingPolicy::ExplicitCallTime,
            "0" | "false" | "no" | "off" | "disabled" | "disable" => {
                WorktreeRoutingPolicy::Disabled
            }
            _ => WorktreeRoutingPolicy::Disabled,
        },
        Err(std::env::VarError::NotPresent) => WorktreeRoutingPolicy::ExplicitCallTime,
        Err(std::env::VarError::NotUnicode(_)) => WorktreeRoutingPolicy::Disabled,
    }
}

/// Install [`WorktreeAwareEditHook`] on the process-wide edit-hook
/// registry, exactly once. Routing policy is resolved inside the hook so
/// callers can request worktree routing at call time with `working_directory`.
///
/// Safe to call repeatedly — the first caller registers the hook and
/// every subsequent call short-circuits via the internal [`OnceLock`].
pub fn register_if_feature_enabled() {
    static REGISTERED: OnceLock<()> = OnceLock::new();
    REGISTERED.get_or_init(|| {
        crate::protocol::edit_hooks::register(Box::new(WorktreeAwareEditHook::new()));
    });
}

/// Length of the `health`-visible misuse window.
const MISUSE_WINDOW: Duration = Duration::from_secs(3600);

/// Counts edit-tool calls that omitted `working_directory` while the
/// transitional worktree observability knob is on. Exposed through the
/// `health` tool as a rolling "last hour" signal so regressions stay
/// visible after the feature ships.
///
/// The window rolls lazily: [`WorktreeMisuseCounter::record_missing_working_directory`] and
/// [`WorktreeMisuseCounter::current_window_count`] both reset the counter when the previous
/// window has elapsed before reading or incrementing it.
#[derive(Debug)]
pub struct WorktreeMisuseCounter {
    count: AtomicU64,
    window_start: Mutex<Instant>,
}

impl WorktreeMisuseCounter {
    pub fn new() -> Self {
        Self {
            count: AtomicU64::new(0),
            window_start: Mutex::new(Instant::now()),
        }
    }

    /// Bump the counter, rolling the window first if it has elapsed.
    pub fn record_missing_working_directory(&self) {
        self.maybe_reset_window();
        self.count.fetch_add(1, Ordering::Relaxed);
    }

    /// Read the current window's count, rolling first if it has elapsed.
    pub fn current_window_count(&self) -> u64 {
        self.maybe_reset_window();
        self.count.load(Ordering::Relaxed)
    }

    fn maybe_reset_window(&self) {
        let mut start = self.window_start.lock();
        if start.elapsed() >= MISUSE_WINDOW {
            *start = Instant::now();
            self.count.store(0, Ordering::Relaxed);
        }
    }
}

impl Default for WorktreeMisuseCounter {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn run_git(args: &[&str], cwd: &Path) {
        let output = crate::process_util::hidden_command("git")
            .args(args)
            .current_dir(cwd)
            .output()
            .expect("git command");
        assert!(
            output.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    /// Create a repo in `<tmp>/main` with one committed file and a
    /// linked worktree at `<tmp>/wt`. Returns canonicalized roots.
    fn make_repo_with_worktree() -> (tempfile::TempDir, PathBuf, PathBuf) {
        let dir = tempfile::tempdir().expect("tempdir");
        let main_root = dir.path().join("main");
        let worktree_root = dir.path().join("wt");
        fs::create_dir_all(&main_root).unwrap();

        run_git(&["init", "-q"], &main_root);
        run_git(&["config", "user.email", "t@t.test"], &main_root);
        run_git(&["config", "user.name", "t"], &main_root);
        run_git(&["config", "commit.gpgsign", "false"], &main_root);
        fs::create_dir_all(main_root.join("src")).unwrap();
        fs::write(main_root.join("src/file.rs"), "fn main() {}\n").unwrap();
        run_git(&["add", "."], &main_root);
        run_git(&["commit", "-q", "-m", "init"], &main_root);
        run_git(
            &[
                "worktree",
                "add",
                "-q",
                worktree_root.to_str().unwrap(),
                "-b",
                "feature",
            ],
            &main_root,
        );

        let main_canon = canonicalize(&main_root).unwrap();
        let wt_canon = canonicalize(&worktree_root).unwrap();
        (dir, main_canon, wt_canon)
    }

    #[test]
    fn canonicalize_strips_trailing_separator() {
        let tmp = tempfile::tempdir().unwrap();
        let canon = canonicalize(tmp.path()).unwrap();

        let with_sep = {
            let mut s = tmp.path().to_string_lossy().into_owned();
            if !s.ends_with(std::path::MAIN_SEPARATOR) {
                s.push(std::path::MAIN_SEPARATOR);
            }
            canonicalize(Path::new(&s)).unwrap()
        };

        assert_eq!(canon, with_sep);
        let s = canon.to_string_lossy();
        assert!(
            !s.ends_with('/') && !s.ends_with('\\'),
            "canonicalized path kept trailing separator: {s}"
        );
    }

    #[test]
    #[cfg(windows)]
    fn canonicalize_normalizes_windows_slash_direction() {
        let tmp = tempfile::tempdir().unwrap();
        let forward = tmp.path().to_string_lossy().replace('\\', "/");
        let back = tmp.path().to_string_lossy().replace('/', "\\");
        let a = canonicalize(Path::new(&forward)).unwrap();
        let b = canonicalize(Path::new(&back)).unwrap();
        assert_eq!(a, b);
    }

    #[test]
    #[cfg(windows)]
    fn canonicalize_does_not_produce_unc_prefix() {
        let tmp = tempfile::tempdir().unwrap();
        let canon = canonicalize(tmp.path()).unwrap();
        let s = canon.to_string_lossy();
        assert!(
            !s.starts_with(r"\\?\"),
            "dunce should have stripped the UNC prefix, got: {s}"
        );
    }

    #[test]
    fn parse_porcelain_extracts_worktree_paths() {
        let sample = "worktree /tmp/main\nHEAD abc123\nbranch refs/heads/main\n\nworktree /tmp/wt\nHEAD def456\nbranch refs/heads/feature\n";
        let paths = parse_porcelain(sample);
        assert_eq!(paths.len(), 2, "expected two worktrees, got {paths:?}");
    }

    #[test]
    fn parse_porcelain_ignores_blank_and_attribute_lines() {
        let sample = "\nworktree /only/one\nbare\n\n";
        let paths = parse_porcelain(sample);
        assert_eq!(paths.len(), 1);
    }

    #[test]
    fn new_cache_is_empty() {
        let cache = WorktreeCache::new();
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
        assert!(cache.last_refreshed().is_none());
    }

    #[test]
    fn insert_adds_entry_without_refresh() {
        let mut cache = WorktreeCache::new();
        let tmp = tempfile::tempdir().unwrap();
        let root = tempfile::tempdir().unwrap();
        let canon = canonicalize(tmp.path()).unwrap();
        cache.insert(root.path(), canon.clone());
        assert_eq!(cache.len(), 1);
        let paths: Vec<&Path> = cache.paths().collect();
        assert!(paths.contains(&canon.as_path()));
    }

    #[test]
    fn refresh_lists_main_and_linked_worktrees() {
        let (_tmp, main_root, wt_root) = make_repo_with_worktree();
        let mut cache = WorktreeCache::new();
        cache.refresh(&main_root).expect("refresh");
        assert!(cache.last_refreshed().is_some());
        assert_eq!(cache.len(), 2, "expected main + linked worktree");
        let paths: Vec<PathBuf> = cache.paths().map(Path::to_path_buf).collect();
        assert!(paths.contains(&main_root), "missing main in {paths:?}");
        assert!(paths.contains(&wt_root), "missing linked wt in {paths:?}");
    }

    #[test]
    fn lookup_returns_known_worktree() {
        let (_tmp, main_root, wt_root) = make_repo_with_worktree();
        let mut cache = WorktreeCache::new();
        let entry = cache
            .lookup(&wt_root, &main_root)
            .expect("lookup")
            .expect("entry");
        assert_eq!(entry.path, wt_root);
    }

    #[test]
    fn lookup_refreshes_on_miss() {
        let (_tmp, main_root, wt_root) = make_repo_with_worktree();
        let mut cache = WorktreeCache::new();
        assert!(cache.is_empty());
        let entry = cache.lookup(&wt_root, &main_root).expect("lookup");
        assert!(
            entry.is_some(),
            "expected cache to refresh and find worktree"
        );
        assert!(!cache.is_empty(), "refresh should have populated cache");
    }

    #[test]
    fn lookup_returns_none_for_unknown_directory() {
        let (_tmp, main_root, _wt_root) = make_repo_with_worktree();
        let stray = tempfile::tempdir().unwrap();
        let stray_canon = canonicalize(stray.path()).unwrap();
        let mut cache = WorktreeCache::new();
        let entry = cache.lookup(&stray_canon, &main_root).expect("lookup");
        assert!(
            entry.is_none(),
            "unrelated tempdir must not match a known worktree, got {entry:?}"
        );
    }

    #[test]
    fn resolve_returns_indexed_path_when_working_directory_omitted() {
        let (_tmp, main_root, _wt) = make_repo_with_worktree();
        let indexed_abs = main_root.join("src/file.rs");
        let mut cache = WorktreeCache::new();
        let resolved =
            resolve_target_path(&indexed_abs, &main_root, None, &mut cache).expect("resolve");
        assert!(!resolved.rerouted);
        assert_eq!(resolved.target_path, indexed_abs);
        assert_eq!(resolved.target_path, resolved.indexed_path);
    }

    #[test]
    fn resolve_omitted_working_directory_does_not_touch_filesystem() {
        let missing_root =
            std::env::temp_dir().join(format!("symforge-missing-root-{}", std::process::id()));
        let indexed_abs = missing_root.join("src/file.rs");
        let mut cache = WorktreeCache::new();
        let resolved = resolve_target_path(&indexed_abs, &missing_root, None, &mut cache)
            .expect("omitted working_directory should not canonicalize repo root");

        assert!(!resolved.rerouted);
        assert_eq!(resolved.target_path, indexed_abs);
        assert_eq!(resolved.target_path, resolved.indexed_path);
    }

    #[test]
    fn resolve_returns_indexed_path_when_working_directory_is_indexed_root() {
        let (_tmp, main_root, _wt) = make_repo_with_worktree();
        let indexed_abs = main_root.join("src/file.rs");
        let mut cache = WorktreeCache::new();
        let resolved = resolve_target_path(&indexed_abs, &main_root, Some(&main_root), &mut cache)
            .expect("resolve");
        assert!(!resolved.rerouted, "indexed root should not reroute");
    }

    #[test]
    fn resolve_reroutes_to_known_worktree() {
        let (_tmp, main_root, wt_root) = make_repo_with_worktree();
        let indexed_abs = main_root.join("src/file.rs");
        let mut cache = WorktreeCache::new();
        let resolved = resolve_target_path(&indexed_abs, &main_root, Some(&wt_root), &mut cache)
            .expect("resolve");
        assert!(resolved.rerouted);
        assert_eq!(resolved.target_path, wt_root.join("src/file.rs"));
        assert_eq!(resolved.indexed_path, canonicalize(&indexed_abs).unwrap());
    }

    #[test]
    fn resolve_errors_on_unknown_working_directory() {
        let (_tmp, main_root, _wt) = make_repo_with_worktree();
        let stray = tempfile::tempdir().unwrap();
        let indexed_abs = main_root.join("src/file.rs");
        let mut cache = WorktreeCache::new();
        let err = resolve_target_path(&indexed_abs, &main_root, Some(stray.path()), &mut cache)
            .expect_err("should reject unknown dir");
        assert!(
            matches!(
                err,
                WorktreeError::WorkingDirectoryNotARecognizedWorktree { .. }
            ),
            "got {err:?}"
        );
    }

    /// Feature 020 Slice 4, T030/T031 (C4c cache census): a cache hit is
    /// fenced to the REQUESTING indexed root. Entries cached from project
    /// A's `git worktree list` must not authorize rerouting project B's
    /// edit into A's worktree — a fresh listing against B would refuse,
    /// and the cache may not be more permissive than the observation it
    /// stands in for. The accepting control (A's own reroute through the
    /// same cache) is in the same test.
    #[test]
    fn worktree_hits_are_fenced_to_the_requesting_indexed_root() {
        let (_tmp_a, main_a, wt_a) = make_repo_with_worktree();
        let (_tmp_b, main_b, _wt_b) = make_repo_with_worktree();
        let mut cache = WorktreeCache::new();

        // Accepting control: A reroutes into its own worktree.
        let indexed_abs_a = main_a.join("src/file.rs");
        let resolved = resolve_target_path(&indexed_abs_a, &main_a, Some(&wt_a), &mut cache)
            .expect("A's own worktree reroutes");
        assert!(resolved.rerouted);

        // B, dispatched through the SAME (process-shared) cache, presents
        // A's worktree as its working directory. The target file exists
        // there (both repos share the fixture layout), so only the root
        // fence can refuse.
        let indexed_abs_b = main_b.join("src/file.rs");
        let err = resolve_target_path(&indexed_abs_b, &main_b, Some(&wt_a), &mut cache)
            .expect_err("a foreign root's cached worktree must not authorize B's reroute");
        assert!(
            matches!(
                err,
                WorktreeError::WorkingDirectoryNotARecognizedWorktree { .. }
            ),
            "got {err:?}"
        );
    }

    /// The reroute target is read and written, so it must be the worktree's
    /// own file: another spelling of it, or a link out of the worktree, is
    /// refused before anything opens it.
    #[test]
    fn resolve_refuses_an_aliased_or_linked_reroute_target() {
        let tmp = tempfile::tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("main/src")).unwrap();
        fs::create_dir_all(tmp.path().join("wt/src")).unwrap();
        let main_root = canonicalize(&tmp.path().join("main")).unwrap();
        let wt_root = canonicalize(&tmp.path().join("wt")).unwrap();
        fs::write(main_root.join("src/file.rs"), "fn main() {}\n").unwrap();

        #[cfg(windows)]
        fs::write(wt_root.join("src/FILE.rs"), "fn main() {}\n").unwrap();
        #[cfg(unix)]
        {
            let outside = tmp.path().join("outside.rs");
            fs::write(&outside, "placeholder\n").unwrap();
            std::os::unix::fs::symlink(&outside, wt_root.join("src/file.rs")).unwrap();
        }

        let mut cache = WorktreeCache::new();
        cache.insert(&main_root, wt_root.clone());
        let result = resolve_target_path(
            &main_root.join("src/file.rs"),
            &main_root,
            Some(&wt_root),
            &mut cache,
        );
        assert!(
            result
                .as_ref()
                .is_err_and(|err| err.to_string().starts_with("TargetPathRefused")),
            "got {result:?}"
        );
    }

    #[test]
    fn resolve_errors_when_target_file_missing() {
        let (_tmp, main_root, wt_root) = make_repo_with_worktree();
        // file exists in main; remove it in worktree so the reroute target is missing.
        fs::remove_file(wt_root.join("src/file.rs")).unwrap();
        let indexed_abs = main_root.join("src/file.rs");
        let mut cache = WorktreeCache::new();
        let err = resolve_target_path(&indexed_abs, &main_root, Some(&wt_root), &mut cache)
            .expect_err("should report missing target");
        assert!(
            matches!(err, WorktreeError::TargetFileMissing { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn resolve_errors_when_indexed_path_outside_indexed_root() {
        let (_tmp, main_root, wt_root) = make_repo_with_worktree();
        // Build an "indexed" absolute path that does not sit under main_root.
        let outside = tempfile::tempdir().unwrap();
        let outside_canon = canonicalize(outside.path()).unwrap();
        let stray_indexed = outside_canon.join("file.rs");
        fs::write(&stray_indexed, "x").unwrap();
        let mut cache = WorktreeCache::new();
        let err = resolve_target_path(&stray_indexed, &main_root, Some(&wt_root), &mut cache)
            .expect_err("should reject path outside indexed root");
        assert!(
            matches!(err, WorktreeError::PathOutsideIndexedRoot { .. }),
            "got {err:?}"
        );
    }

    #[test]
    #[cfg(windows)]
    fn resolve_normalizes_windows_slash_variants() {
        let (_tmp, main_root, wt_root) = make_repo_with_worktree();
        let indexed_abs = main_root.join("src/file.rs");
        let wt_forward = PathBuf::from(wt_root.to_string_lossy().replace('\\', "/"));
        let wt_back = PathBuf::from(wt_root.to_string_lossy().replace('/', "\\"));
        let mut cache = WorktreeCache::new();

        let a = resolve_target_path(&indexed_abs, &main_root, Some(&wt_forward), &mut cache)
            .expect("resolve forward");
        let b = resolve_target_path(&indexed_abs, &main_root, Some(&wt_back), &mut cache)
            .expect("resolve back");
        assert_eq!(a, b);
        assert!(a.rerouted);
    }
}