dirge-agent 0.18.3

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
//! Path resolution helpers for the permission engine.
//!
//! Provides canonicalisation and symlink resolution. `resolve_absolute`
//! is the entry point — resolves a possibly-relative path through the
//! working directory, follows symlinks, and normalises `..` / `.`
//! components. Used by the engine's path classifier and by external
//! callers that need the same canonical path the permission check ran
//! against (closing the symlink-swap TOCTOU between check and open).

use std::path::Path;

/// One-shot canonicalize for the working-directory cache. Best
/// effort: if canonicalize fails (cwd doesn't exist on disk, e.g.
/// in tests that pass a fixture path), fall back to the literal
/// string so the `starts_with` comparisons in `is_external_path`
/// still work for the literal form.
pub(crate) fn canonicalize_for_cache(working_dir: &str) -> String {
    dunce::canonicalize(working_dir)
        .ok()
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_else(|| working_dir.to_string())
}

/// Best-effort canonicalize a `Path`, falling back to the path itself
/// when it can't be resolved (doesn't exist on disk, permission error).
/// The `PathBuf` analogue of [`canonicalize_for_cache`] and the single
/// home for the `path.canonicalize().unwrap_or_else(|_| path.into())`
/// idiom that was copy-pasted with varied fallbacks (dirge-b2g7).
pub fn canonical_or_self(path: &Path) -> std::path::PathBuf {
    dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

/// Normalize a path string for prefix comparison. On Windows
/// `canonicalize` yields a `\\?\C:\...` verbatim path with backslashes,
/// and callers may pass `/`-vs-`\` mixed separators or differing
/// drive-letter case; left unnormalized, the slash-anchored prefix test
/// in [`path_is_within`] never matches and every in-cwd file is
/// misclassified as external. Strip the `\\?\` / `\\?\UNC\` prefix,
/// unify separators to `/`, and lowercase (NTFS is case-insensitive).
/// No-op on Unix, so the existing forward-slash logic is unchanged.
#[cfg(windows)]
fn normalize_for_prefix(s: &str) -> String {
    let stripped = s
        .strip_prefix(r"\\?\UNC\")
        .map(|rest| format!(r"\\{rest}"))
        .unwrap_or_else(|| s.strip_prefix(r"\\?\").unwrap_or(s).to_string());
    stripped.replace('\\', "/").to_lowercase()
}

#[cfg(not(windows))]
fn normalize_for_prefix(s: &str) -> String {
    s.to_string()
}

/// Whether `child` is `base` itself or a path nested under it. The
/// comparison is boundary-safe — `/foo` does NOT contain `/foobar` —
/// because the prefix test requires a trailing separator. On Windows it
/// tolerates the `\\?\` verbatim prefix, `/`-vs-`\` separators, and
/// drive-letter case (see [`normalize_for_prefix`]). An empty or root
/// `base` matches nothing (callers treat "no usable cwd" as external).
pub(crate) fn path_is_within(child: &str, base: &str) -> bool {
    let child = normalize_for_prefix(child);
    let base = normalize_for_prefix(base);
    let base = base.trim_end_matches('/');
    // Refuse filesystem roots as a containing dir: empty, `/`, and the
    // Windows drive-root form (`c:` after the trailing-slash trim). Without
    // the drive-root guard, `c:/` would match every path on the drive and
    // a `/` working_dir would silently allow everything.
    if base.is_empty() || base == "/" || is_drive_root(base) {
        return false;
    }
    child == base || child.starts_with(&format!("{base}/"))
}

/// Drop-in replacement for `Path::starts_with` when the two sides may
/// come back from canonicalization in different Windows forms. dunce
/// returns MIXED forms within one tree: short paths get simplified
/// (`C:\proj`) while >MAX_PATH or reserved-name (aux/nul) paths stay
/// verbatim (`\\?\C:\...`). `Path::starts_with` compares prefix
/// components (`VerbatimDisk` vs `Disk`) and returns false, so prefix
/// guards silently fail. Compares the [`normalize_for_prefix`] forms
/// instead, boundary-safe. Unlike [`path_is_within`] a root `base`
/// matches (same as `Path::starts_with`) — callers like the LSP
/// root walk own their boundary semantics. No-op normalization on
/// Unix, so behavior there is identical to `Path::starts_with`.
pub(crate) fn path_starts_with(child: &Path, base: &Path) -> bool {
    let child = normalize_for_prefix(&child.to_string_lossy());
    let base = normalize_for_prefix(&base.to_string_lossy());
    let base = base.trim_end_matches('/');
    if base.is_empty() {
        // `base` was the filesystem root (`/`): every absolute path is
        // under it, matching `Path::starts_with`.
        return child.starts_with('/');
    }
    child == base || child.starts_with(&format!("{base}/"))
}

/// Path equality over the [`normalize_for_prefix`] forms — the `==`
/// analogue of [`path_starts_with`], for the same mixed
/// verbatim-vs-simplified reason. No-op normalization on Unix.
pub(crate) fn paths_equivalent(a: &Path, b: &Path) -> bool {
    normalize_for_prefix(&a.to_string_lossy()) == normalize_for_prefix(&b.to_string_lossy())
}

/// `c:` / `Z:` — a normalized drive root with no path component.
fn is_drive_root(s: &str) -> bool {
    let b = s.as_bytes();
    b.len() == 2 && b[0].is_ascii_alphabetic() && b[1] == b':'
}

/// `C:\` — a drive letter, colon, and backslash: a drive-absolute Windows
/// path, the only shape [`verbatim_extend`] prepends a drive verbatim prefix to.
fn is_drive_absolute(s: &str) -> bool {
    let b = s.as_bytes();
    b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && b[2] == b'\\'
}

/// Re-apply the `\\?\` extended-length prefix to an absolute Windows path that
/// exceeds MAX_PATH and lacks it. [`resolve_absolute`]'s ancestor walk reattaches
/// a nonexistent tail onto dunce's de-verbatimized ancestor, which can push a
/// new-file path back over 260 chars WITHOUT the prefix dunce would otherwise
/// have kept; `std::fs` then fails on machines without the long-path opt-in
/// (dirge-8gdv.3). Only over-limit drive-absolute (`C:\…`) and UNC
/// (`\\server\share\…`) paths are touched; short, already-verbatim, and
/// non-Windows-shaped paths (every Unix path) pass through unchanged, so this
/// is a safe no-op off Windows. Classification is unaffected —
/// [`normalize_for_prefix`] strips the prefix on both sides before comparing.
fn verbatim_extend(path: String) -> String {
    const MAX_PATH: usize = 260;
    if path.len() <= MAX_PATH || path.starts_with(r"\\?\") {
        return path;
    }
    if let Some(rest) = path.strip_prefix(r"\\") {
        // UNC share: `\\server\share\…` -> `\\?\UNC\server\share\…`.
        format!(r"\\?\UNC\{rest}")
    } else if is_drive_absolute(&path) {
        // Drive path: `C:\…` -> `\\?\C:\…`.
        format!(r"\\?\{path}")
    } else {
        // Relative or an unexpected shape — not safe to extend.
        path
    }
}

pub(crate) fn resolve_absolute(path: &str, working_dir: &str) -> String {
    let p = Path::new(path);
    let joined = if p.is_absolute() {
        p.to_path_buf()
    } else {
        Path::new(working_dir).join(p)
    };
    match dunce::canonicalize(&joined) {
        Ok(canonical) => canonical.to_string_lossy().to_string(),
        Err(_) => {
            // The full path doesn't exist on disk (e.g. a write to a
            // brand-new file, possibly in a brand-new nested dir).
            // Canonicalize the DEEPEST existing ancestor so any
            // symlink in the existing prefix is resolved to its
            // realpath, then re-attach the still-nonexistent tail.
            //
            // Why the deepest ancestor and not just the immediate
            // parent: when the agent writes to `new_a/new_b/file.rs`
            // inside a symlinked cwd, neither `file.rs`'s parent
            // (`new_b`) nor its grandparent (`new_a`) exist, so the
            // old single-level parent canonicalize failed and we fell
            // through to a purely lexical result that kept the SYMLINK
            // form of the cwd. That form never matches the CWD-allow
            // rule (built from the canonical cwd), so in-project writes
            // re-prompted. Walking to the nearest existing ancestor
            // fixes that while staying inside the project subtree.
            //
            // The tail is lexically normalized FIRST (resolving `.` /
            // `..` without touching disk) so an attacker can't smuggle
            // an escape through `existing_dir/../../etc/passwd`: the
            // `..` are collapsed against the lexical components, and
            // any that climb above the existing ancestor are preserved
            // as `..` (see `lexical_normalize`), so the result escapes
            // the cwd subtree and is correctly classified external.
            let normalized = lexical_normalize(&joined);
            let mut ancestor = normalized.as_path();
            let mut tail: Vec<std::ffi::OsString> = Vec::new();
            loop {
                if let Ok(canonical_ancestor) = dunce::canonicalize(ancestor) {
                    let mut out = canonical_ancestor;
                    for seg in tail.iter().rev() {
                        out.push(seg);
                    }
                    // dunce de-verbatimizes the existing ancestor, but the
                    // reattached tail can push the result back over MAX_PATH
                    // without the `\\?\` prefix dunce would have kept — a
                    // brand-new deep file then fails to write on Windows
                    // without the long-path opt-in (dirge-8gdv.3).
                    return verbatim_extend(out.to_string_lossy().to_string());
                }
                match (ancestor.parent(), ancestor.file_name()) {
                    (Some(parent), Some(name)) => {
                        tail.push(name.to_os_string());
                        ancestor = parent;
                    }
                    // Reached the root with nothing canonicalizable
                    // (e.g. a fully bogus working_dir). Fall back to
                    // the lexical form so the literal-prefix checks in
                    // `is_external_path` still have something to match.
                    _ => return normalized.to_string_lossy().to_string(),
                }
            }
        }
    }
}

/// Resolve `.` and `..` components of `p` without touching the
/// filesystem. `..` pops the previous `Normal` component; consecutive
/// `..` at the start (i.e. attempting to climb above root) are
/// retained as `..` so an attacker can't disguise an escape by
/// chaining enough `..` to underflow a real-path prefix check.
/// Doesn't follow symlinks — callers that need symlink resolution
/// should use `std::fs::canonicalize`; this helper exists for the
/// nonexistent-path fallback where canonicalize is impossible.
fn lexical_normalize(p: &Path) -> std::path::PathBuf {
    use std::path::{Component, PathBuf};
    let mut out: Vec<Component> = Vec::new();
    for c in p.components() {
        match c {
            Component::CurDir => {}
            Component::ParentDir => {
                if matches!(out.last(), Some(Component::Normal(_))) {
                    out.pop();
                } else {
                    out.push(c);
                }
            }
            other => out.push(other),
        }
    }
    let mut buf = PathBuf::new();
    for c in &out {
        buf.push(c.as_os_str());
    }
    buf
}

/// Reject paths that are clearly LLM hallucinations before they
/// trigger permission dialogs.  Relative single-segment paths
/// that are purely numeric ("1", "42") or trivially short
/// ("a", "x") are never valid file names a well-behaved
/// agent would genuinely want to use; the model is confusing
/// a counter, index, or file-descriptor number with a file
/// path.
///
/// Returns `Ok(())` for plausible paths, `Err(reason)` for
/// paths that should be hard-rejected.
#[allow(dead_code)] // Phase 4: only reached via the legacy check_path facade
pub fn validate_path(path: &str) -> Result<(), String> {
    let p = Path::new(path);
    if p.is_absolute() {
        return Ok(());
    }
    // Has a directory component — plausible relative path.
    if path.contains('/') || path.contains('\\') {
        return Ok(());
    }
    // Has a file extension — plausible filename.
    if path.contains('.') {
        return Ok(());
    }
    // Just a bare name.  Reject single-segment names that are
    // purely numeric ("1", "42") or a single short token
    // with no extension ("a", "xy").
    if path.chars().all(|c| c.is_ascii_digit()) {
        return Err(format!(
            "Refusing to use numeric path {:?}. Use an absolute path with a real file name.",
            path,
        ));
    }
    if path.chars().count() <= 2 {
        return Err(format!(
            "Refusing to use trivial path {:?}. Use an absolute path with a real file name.",
            path,
        ));
    }
    Ok(())
}

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

    #[test]
    fn path_starts_with_basic_and_boundary() {
        assert!(path_starts_with(
            Path::new("/proj/src/a.rs"),
            Path::new("/proj")
        ));
        assert!(path_starts_with(Path::new("/proj"), Path::new("/proj")));
        // Boundary-safe: a sibling sharing a name prefix is NOT within.
        assert!(!path_starts_with(
            Path::new("/proj-other/a.rs"),
            Path::new("/proj")
        ));
        assert!(!path_starts_with(
            Path::new("/elsewhere/a.rs"),
            Path::new("/proj")
        ));
        // Unlike `path_is_within`, a root base matches (Path::starts_with
        // semantics — nearest_root callers may legitimately stop at `/`).
        assert!(path_starts_with(Path::new("/a/b"), Path::new("/")));
    }

    #[test]
    fn paths_equivalent_basic() {
        assert!(paths_equivalent(
            Path::new("/proj/src"),
            Path::new("/proj/src")
        ));
        assert!(!paths_equivalent(
            Path::new("/proj/src"),
            Path::new("/proj")
        ));
    }

    /// The LSP regression: dunce returns MIXED forms within one tree on
    /// Windows — short paths simplified (`C:\proj`), >MAX_PATH or
    /// reserved-name (aux/nul) paths verbatim (`\\?\C:\...`). A raw
    /// `Path::starts_with` compares VerbatimDisk vs Disk prefix components
    /// and always fails, so `nearest_root` bailed and LSP root detection
    /// silently stopped for that file.
    #[cfg(windows)]
    #[test]
    fn path_starts_with_windows_verbatim_vs_simplified() {
        assert!(path_starts_with(
            Path::new(r"\\?\C:\proj\aux\src\a.rs"),
            Path::new(r"C:\proj"),
        ));
        assert!(path_starts_with(
            Path::new(r"C:\proj\src\a.rs"),
            Path::new(r"\\?\C:\proj"),
        ));
        // Drive-letter case and mixed separators.
        assert!(path_starts_with(
            Path::new(r"\\?\c:\proj/src/a.rs"),
            Path::new(r"C:\proj"),
        ));
        // Boundary still enforced under normalization.
        assert!(!path_starts_with(
            Path::new(r"\\?\C:\proj-other\a.rs"),
            Path::new(r"C:\proj"),
        ));
    }

    #[cfg(windows)]
    #[test]
    fn paths_equivalent_windows_verbatim_vs_simplified() {
        assert!(paths_equivalent(
            Path::new(r"\\?\C:\proj"),
            Path::new(r"C:\proj")
        ));
        assert!(paths_equivalent(
            Path::new(r"\\?\c:\proj"),
            Path::new(r"C:\proj")
        ));
        assert!(!paths_equivalent(
            Path::new(r"\\?\C:\proj2"),
            Path::new(r"C:\proj")
        ));
    }

    #[test]
    fn path_is_within_basic_and_boundary() {
        assert!(path_is_within("/proj/src/a.rs", "/proj"));
        assert!(path_is_within("/proj", "/proj"));
        assert!(path_is_within("/proj/", "/proj"));
        // Boundary-safe: a sibling sharing a name prefix is NOT within.
        assert!(!path_is_within("/proj-other/a.rs", "/proj"));
        assert!(!path_is_within("/elsewhere/a.rs", "/proj"));
        // Empty / root base matches nothing.
        assert!(!path_is_within("/a", ""));
        assert!(!path_is_within("/a", "/"));
    }

    /// The Windows regression: a `\\?\C:\...` verbatim canonical path,
    /// mixed `/`-vs-`\` separators, and drive-letter case must all still
    /// resolve as in-cwd. Before the fix the slash-anchored prefix test
    /// failed on every Windows in-project file → "outside project".
    #[cfg(windows)]
    #[test]
    fn path_is_within_windows_verbatim_separators_and_case() {
        assert!(path_is_within(r"\\?\C:\proj\src\a.dfy", r"C:\proj"));
        assert!(path_is_within(r"\\?\C:\proj/src/a.dfy", r"C:\proj"));
        assert!(path_is_within(r"\\?\c:\proj\src\a.dfy", r"C:\proj"));
        assert!(path_is_within(r"C:\proj\a.dfy", r"\\?\C:\proj"));
        // Boundary still enforced under normalization.
        assert!(!path_is_within(r"\\?\C:\proj-other\a.dfy", r"C:\proj"));
    }

    /// Regression: `resolve_absolute` must NOT leak a Windows verbatim
    /// (`\\?\`) prefix into the string it returns. That form flowed into
    /// tool `resolved_path`s (apply_patch, edit, read-gate cache keys) and
    /// surfaced to the model as `\\?\C:\...\file.dfy`. `dunce::canonicalize`
    /// strips it for normal-length paths. Applies to both existing files
    /// and not-yet-created ones (the ancestor-walk branch).
    #[cfg(windows)]
    #[test]
    fn resolve_absolute_has_no_verbatim_prefix() {
        let dir = std::env::temp_dir().join(format!("dirge-verbatim-test-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let existing = dir.join("here.dfy");
        std::fs::write(&existing, "x").unwrap();

        let r1 = resolve_absolute(existing.to_str().unwrap(), "/");
        assert!(
            !r1.starts_with(r"\\?\"),
            "existing file leaked verbatim prefix: {r1}"
        );

        // Nonexistent file (create path) — exercises the ancestor-walk branch.
        let missing = dir.join("newdir").join("not-yet.dfy");
        let r2 = resolve_absolute(missing.to_str().unwrap(), dir.to_str().unwrap());
        assert!(
            !r2.starts_with(r"\\?\"),
            "new-file path leaked verbatim prefix: {r2}"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// F7: `resolve_absolute` must follow symlinks so a symlink
    /// pointing at a deny-listed path can't bypass the rule.
    #[test]
    fn resolve_absolute_follows_symlinks() {
        let dir =
            std::env::temp_dir().join(format!("dirge-f7-symlink-test-{}", std::process::id(),));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let target = dir.join("real-secret.txt");
        std::fs::write(&target, "hunter2").unwrap();
        let link = dir.join("benign-name.txt");

        #[cfg(unix)]
        std::os::unix::fs::symlink(&target, &link).unwrap();
        #[cfg(windows)]
        if let Err(e) = std::os::windows::fs::symlink_file(&target, &link) {
            // Creating symlinks on Windows needs SeCreateSymbolicLinkPrivilege
            // (Developer Mode or admin; OS error 1314 otherwise). Skip
            // gracefully where it's unavailable instead of failing the suite.
            eprintln!("skipping resolve_absolute_follows_symlinks: cannot create symlink: {e}");
            let _ = std::fs::remove_dir_all(&dir);
            return;
        }

        let resolved = resolve_absolute(link.to_str().unwrap(), "/");
        let expected = dunce::canonicalize(&target)
            .unwrap()
            .to_string_lossy()
            .into_owned();
        assert_eq!(resolved, expected, "symlink should resolve to its target",);

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Regression: a write to a brand-new file in a brand-new
    /// NESTED directory inside a symlinked cwd must resolve through
    /// the symlink to the real path. The immediate parent doesn't
    /// exist (so single-level parent canonicalize fails); the fix
    /// walks up to the deepest existing ancestor, canonicalizes
    /// that (resolving the symlinked cwd), and re-attaches the
    /// nonexistent tail. Without this the result kept the symlink
    /// form, the CWD-allow rule (built from the canonical cwd) never
    /// matched, and in-project writes re-prompted.
    #[test]
    fn resolve_absolute_walks_to_deepest_existing_ancestor_through_symlink() {
        let base = std::env::temp_dir().join(format!("dirge-deepancestor-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let real = base.join("real_proj");
        std::fs::create_dir_all(&real).unwrap();
        let link = base.join("link_proj");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&real, &link).unwrap();
        #[cfg(windows)]
        if let Err(e) = std::os::windows::fs::symlink_dir(&real, &link) {
            // Needs SeCreateSymbolicLinkPrivilege on Windows (OS error 1314
            // without Developer Mode / admin). Skip gracefully.
            eprintln!(
                "skipping resolve_absolute_walks_to_deepest_existing_ancestor_through_symlink: \
                 cannot create symlink: {e}"
            );
            let _ = std::fs::remove_dir_all(&base);
            return;
        }

        // newdir/sub do NOT exist yet; only `link_proj` (→ real_proj) does.
        let target = link.join("newdir/sub/file.rs");
        let resolved = resolve_absolute(target.to_str().unwrap(), link.to_str().unwrap());

        // Build the tail with per-component joins so the separators match how
        // `resolve_absolute` reattaches them (platform-native: `\` on Windows).
        let expected = dunce::canonicalize(&real)
            .unwrap()
            .join("newdir")
            .join("sub")
            .join("file.rs")
            .to_string_lossy()
            .into_owned();
        assert_eq!(
            resolved, expected,
            "deep new path under symlinked cwd must resolve to realpath form",
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    /// Security: the deepest-ancestor walk must NOT let a `..`
    /// traversal disguise an escape as internal. `..` is lexically
    /// collapsed BEFORE the ancestor canonicalize, so a path that
    /// climbs out of the (symlinked) cwd resolves outside the
    /// subtree and is classified external (→ prompt), not allowed.
    #[test]
    fn resolve_absolute_dotdot_escape_through_symlinked_cwd_still_escapes() {
        let base = std::env::temp_dir().join(format!("dirge-escape-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let real = base.join("real_proj");
        std::fs::create_dir_all(&real).unwrap();
        let link = base.join("link_proj");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&real, &link).unwrap();

        let cwd = link.to_string_lossy().into_owned();
        // newdir doesn't exist; the `..` chain climbs above the project.
        let traversal = "newdir/../../../../../../etc/passwd";
        let resolved = resolve_absolute(traversal, &cwd);

        let cwd_canonical = dunce::canonicalize(&real).unwrap();
        let resolved_path = std::path::PathBuf::from(&resolved);
        assert!(
            !resolved_path.starts_with(&cwd_canonical),
            "escape via .. must resolve outside the cwd subtree; got {resolved:?}",
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    /// F7: nonexistent paths (writes to new files) must still
    /// resolve sensibly. They can't canonicalize fully but we
    /// canonicalize the parent so `/real/parent/../../etc/passwd`
    /// becomes `/etc/passwd` instead of staying lexical.
    #[test]
    fn resolve_absolute_handles_nonexistent_via_parent_canonicalize() {
        let dir =
            std::env::temp_dir().join(format!("dirge-f7-newfile-test-{}", std::process::id(),));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let new_file = dir.join("does-not-exist-yet.txt");

        let resolved = resolve_absolute(new_file.to_str().unwrap(), "/");
        let expected_parent = dunce::canonicalize(&dir).unwrap();
        let expected = expected_parent
            .join("does-not-exist-yet.txt")
            .to_string_lossy()
            .into_owned();
        assert_eq!(resolved, expected);

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Regression for audit C3: when BOTH `canonicalize(joined)` AND
    /// `canonicalize(parent)` fail, the previous fallback returned
    /// the joined path with `..` components intact. Since
    /// `Path::starts_with` operates on path *components*, a crafted
    /// path like `/cwd/nonexistent_subdir/../../etc/passwd` would
    /// classify as internal because the first three components match
    /// `/cwd`. Attacker (LLM/agent) can synthesize such a path
    /// trivially. After the fix, `..` components are lexically
    /// resolved before the fallback returns, so the path escapes
    /// the cwd subtree.
    #[test]
    fn resolve_absolute_normalizes_dotdot_in_full_lexical_fallback() {
        let dir = std::env::temp_dir().join(format!("dirge-c3-traversal-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let cwd = dir.to_string_lossy().into_owned();

        let traversal = "no_such_dir/no_such_subdir/../../../etc/passwd";

        let resolved = resolve_absolute(traversal, &cwd);

        let cwd_canonical = dunce::canonicalize(&cwd).unwrap();
        let resolved_path = std::path::PathBuf::from(&resolved);
        assert!(
            !resolved_path.starts_with(&cwd_canonical) && !resolved_path.starts_with(&cwd),
            "lexical-fallback path-traversal should escape cwd subtree; got {:?}, cwd {:?}",
            resolved_path,
            cwd_canonical,
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    // ── validate_path ────────────────────────────────────────────

    #[test]
    fn validate_accepts_absolute_paths() {
        assert!(validate_path("/etc/hosts").is_ok());
        assert!(validate_path("/Users/bob/src/main.rs").is_ok());
    }

    #[test]
    fn validate_accepts_relative_paths_with_separator() {
        assert!(validate_path("src/main.rs").is_ok());
        assert!(validate_path("lib/core.js").is_ok());
        assert!(validate_path("..\\windows\\path").is_ok());
    }

    #[test]
    fn validate_accepts_relative_names_with_extension() {
        assert!(validate_path("Cargo.toml").is_ok());
        assert!(validate_path("README.md").is_ok());
        assert!(validate_path("build.sh").is_ok());
    }

    #[test]
    fn validate_accepts_extensionless_names_that_are_not_trivial() {
        // Common extensionless filenames.
        assert!(validate_path("Makefile").is_ok());
        assert!(validate_path("Dockerfile").is_ok());
        assert!(validate_path("README").is_ok());
        assert!(validate_path("LICENSE").is_ok());
        assert!(validate_path("abc").is_ok());
    }

    #[test]
    fn validate_rejects_numeric_paths() {
        assert!(validate_path("1").is_err());
        assert!(validate_path("42").is_err());
        assert!(validate_path("007").is_err());
    }

    #[test]
    fn validate_rejects_short_nonsense_paths() {
        assert!(validate_path("a").is_err());
        assert!(validate_path("xy").is_err());
    }

    // dirge-8gdv.3: string-only, so it runs on every platform even though it
    // guards a Windows-only failure mode.
    #[test]
    fn verbatim_extend_reapplies_prefix_only_for_overlong_windows_paths() {
        let long = "a".repeat(300);

        // Over-limit drive path gains the `\\?\` prefix.
        let drive = format!(r"C:\proj\{long}\file.rs");
        assert_eq!(verbatim_extend(drive.clone()), format!(r"\\?\{drive}"));

        // Over-limit UNC path gains the `\\?\UNC\` prefix.
        let unc = format!(r"\\server\share\{long}\file.rs");
        assert_eq!(
            verbatim_extend(unc),
            format!(r"\\?\UNC\server\share\{long}\file.rs")
        );

        // Short drive path is left alone.
        let short = r"C:\proj\src\a.rs".to_string();
        assert_eq!(verbatim_extend(short.clone()), short);

        // Already-verbatim over-limit path is not double-prefixed.
        let verbatim = format!(r"\\?\C:\proj\{long}\file.rs");
        assert_eq!(verbatim_extend(verbatim.clone()), verbatim);

        // A long Unix-shaped path (no drive, no UNC) passes through — the
        // reason this helper is safe to call unconditionally.
        let unix = format!("/home/user/{long}/file.rs");
        assert_eq!(verbatim_extend(unix.clone()), unix);
    }
}