codescout 0.15.0

High-performance coding agent toolkit MCP server
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
use anyhow::Result;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashSet;
use std::path::Path;
use std::sync::OnceLock;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PathAnchor {
    pub path: String,
    pub hash: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AnchorFile {
    #[serde(default)]
    pub anchors: Vec<PathAnchor>,
}

const HEADER_COMMENT: &str = "\
# Anchor sidecar — tracks content hashes for referenced paths.\n\
# Auto-generated by codescout. Edit anchors list manually if needed.\n\n";

pub fn read_anchor_file(path: &Path) -> Result<AnchorFile> {
    match std::fs::read_to_string(path) {
        Ok(contents) => {
            let anchor_file: AnchorFile = toml::from_str(&contents)?;
            Ok(anchor_file)
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(AnchorFile::default()),
        Err(e) => Err(e.into()),
    }
}

pub fn write_anchor_file(path: &Path, anchor_file: &AnchorFile) -> Result<()> {
    let body = toml::to_string_pretty(anchor_file)?;
    let content = format!("{HEADER_COMMENT}{body}");
    crate::util::fs::atomic_write(path, &content)?;
    Ok(())
}

fn path_re() -> &'static Regex {
    static PATH_RE: OnceLock<Regex> = OnceLock::new();
    PATH_RE.get_or_init(|| {
        Regex::new(
            r"(?:^|[`\s\|(])((src/[\w/._-]+\.\w+|\.codescout/[\w/._-]+\.\w+|Cargo\.toml|CLAUDE\.md|docs/[\w/._-]+\.\w+))",
        )
        .unwrap()
    })
}

/// Extract file paths mentioned in memory content. Deduplicates and strips line-number suffixes.
pub fn extract_paths(content: &str) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut result = Vec::new();
    for cap in path_re().captures_iter(content) {
        let mut path = cap[1].to_string();
        // Strip :line_number suffix (e.g. "src/tools/mod.rs:228" → "src/tools/mod.rs")
        if let Some(colon_pos) = path.rfind(':') {
            if path[colon_pos + 1..].chars().all(|c| c.is_ascii_digit()) {
                path.truncate(colon_pos);
            }
        }
        if seen.insert(path.clone()) {
            result.push(path);
        }
    }
    result
}

/// Seed anchors from memory content. Only includes files that exist on disk.
pub fn seed_anchors(project_root: &Path, content: &str) -> Result<AnchorFile> {
    let paths = extract_paths(content);
    let mut anchors = Vec::new();
    for p in paths {
        let full = project_root.join(&p);
        if full.is_file() {
            let hash = super::hash::hash_file(&full)?;
            anchors.push(PathAnchor { path: p, hash });
        }
    }
    Ok(AnchorFile { anchors })
}

/// Merge existing sidecar with newly seeded anchors.
/// Keeps user-added paths, adds new paths, refreshes all hashes.
pub fn merge_anchors(
    project_root: &Path,
    existing: &AnchorFile,
    new_seed: &AnchorFile,
) -> Result<AnchorFile> {
    let mut seen = HashSet::new();
    let mut anchors = Vec::new();

    // Start with new-seed paths (hashes already fresh)
    for a in &new_seed.anchors {
        if seen.insert(a.path.clone()) {
            anchors.push(a.clone());
        }
    }

    // Add user-curated paths not in new seed, refresh their hashes
    for a in &existing.anchors {
        if seen.insert(a.path.clone()) {
            let full = project_root.join(&a.path);
            if let Ok(hash) = super::hash::hash_file(&full) {
                anchors.push(PathAnchor {
                    path: a.path.clone(),
                    hash,
                });
            }
            // If file deleted, silently drop
        }
    }

    Ok(AnchorFile { anchors })
}

#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AnchorStatus {
    Changed,
    Deleted,
}

#[derive(Debug, Clone, Serialize)]
pub struct StaleFile {
    pub path: String,
    pub status: AnchorStatus,
}

#[derive(Debug)]
pub struct StalenessReport {
    pub stale_files: Vec<StaleFile>,
}

impl StalenessReport {
    pub fn is_fresh(&self) -> bool {
        self.stale_files.is_empty()
    }
}

/// Check path anchors against current file state.
pub fn check_path_staleness(
    project_root: &Path,
    anchor_file: &AnchorFile,
) -> Result<StalenessReport> {
    let mut stale_files = Vec::new();
    for anchor in &anchor_file.anchors {
        let full = project_root.join(&anchor.path);
        if !full.exists() {
            stale_files.push(StaleFile {
                path: anchor.path.clone(),
                status: AnchorStatus::Deleted,
            });
        } else {
            let current_hash = super::hash::hash_file(&full)?;
            if current_hash != anchor.hash {
                stale_files.push(StaleFile {
                    path: anchor.path.clone(),
                    status: AnchorStatus::Changed,
                });
            }
        }
    }
    Ok(StalenessReport { stale_files })
}

/// Check all memory topics in a memories directory for staleness.
/// Check all memory topics in a memories directory for staleness.
pub fn check_all_memories(project_root: &Path, memories_dir: &Path) -> Result<Value> {
    let mut stale = Vec::new();
    let mut fresh: Vec<Value> = Vec::new();
    let mut untracked: Vec<String> = Vec::new();

    if !memories_dir.exists() {
        return Ok(json!({ "stale": stale, "fresh": fresh, "untracked": untracked }));
    }

    for entry in walkdir::WalkDir::new(memories_dir).into_iter().flatten() {
        let path = entry.path();
        // Skip directories and non-.md files.
        if !entry.file_type().is_file() || path.extension().is_none_or(|e| e != "md") {
            continue;
        }
        // Derive topic from relative path so nested topics like
        // "debugging/async-patterns" are included alongside flat ones.
        let Ok(rel) = path.strip_prefix(memories_dir) else {
            continue;
        };
        let topic = rel.with_extension("").to_string_lossy().replace('\\', "/");

        let sidecar = anchor_path_for_topic(memories_dir, &topic);

        if !sidecar.exists() {
            untracked.push(topic);
            continue;
        }

        let anchor_file = read_anchor_file(&sidecar)?;
        let report = check_path_staleness(project_root, &anchor_file)?;

        if report.is_fresh() {
            fresh.push(json!(topic));
        } else {
            let changed: Vec<&str> = report
                .stale_files
                .iter()
                .filter(|f| f.status == AnchorStatus::Changed)
                .map(|f| f.path.as_str())
                .collect();
            let deleted: Vec<&str> = report
                .stale_files
                .iter()
                .filter(|f| f.status == AnchorStatus::Deleted)
                .map(|f| f.path.as_str())
                .collect();
            let total_anchored = anchor_file.anchors.len();
            let total_stale = report.stale_files.len();
            let mut entry = json!({
                "topic": topic,
                "reason": format!("{} of {} anchored files changed", total_stale, total_anchored),
            });
            if !changed.is_empty() {
                entry["changed_files"] = json!(changed);
            }
            if !deleted.is_empty() {
                entry["deleted_files"] = json!(deleted);
            }
            stale.push(entry);
        }
    }

    fresh.sort_by(|a, b| a.as_str().cmp(&b.as_str()));
    untracked.sort();

    Ok(json!({
        "stale": stale,
        "fresh": fresh,
        "untracked": untracked,
    }))
}

/// Get the anchor sidecar path for a given memory topic within a memories directory.
pub fn anchor_path_for_topic(memories_dir: &Path, topic: &str) -> std::path::PathBuf {
    let safe = super::sanitize_topic(topic);
    memories_dir.join(format!("{}.anchors.toml", safe))
}

/// Seed or merge anchors for a memory topic after a write.
pub fn update_anchors_on_write(
    project_root: &Path,
    memories_dir: &Path,
    topic: &str,
    content: &str,
) -> Result<()> {
    let sidecar_path = anchor_path_for_topic(memories_dir, topic);
    let existing = read_anchor_file(&sidecar_path)?;
    let new_seed = seed_anchors(project_root, content)?;

    let merged = if existing.anchors.is_empty() {
        new_seed
    } else {
        merge_anchors(project_root, &existing, &new_seed)?
    };

    // Only write sidecar if there are anchors to track
    if !merged.anchors.is_empty() {
        write_anchor_file(&sidecar_path, &merged)?;
    }
    Ok(())
}

/// Re-hash all anchored files without changing the anchor list.
/// Used to acknowledge "I reviewed this memory, it's still accurate."
pub fn refresh_hashes(project_root: &Path, memories_dir: &Path, topic: &str) -> Result<()> {
    let sidecar_path = anchor_path_for_topic(memories_dir, topic);
    let mut anchor_file = read_anchor_file(&sidecar_path)?;

    // Re-hash existing paths, remove entries for deleted files
    anchor_file.anchors.retain_mut(|a| {
        let full = project_root.join(&a.path);
        if let Ok(hash) = super::hash::hash_file(&full) {
            a.hash = hash;
            true
        } else {
            false // file deleted, drop anchor
        }
    });

    write_anchor_file(&sidecar_path, &anchor_file)?;
    Ok(())
}

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

    #[test]
    fn roundtrip_anchor_file() {
        let dir = tempdir().unwrap();
        let anchors_path = dir.path().join("architecture.anchors.toml");

        let anchors = AnchorFile {
            anchors: vec![
                PathAnchor {
                    path: "src/server.rs".to_string(),
                    hash: "abc123".to_string(),
                },
                PathAnchor {
                    path: "src/tools/mod.rs".to_string(),
                    hash: "def456".to_string(),
                },
            ],
        };

        write_anchor_file(&anchors_path, &anchors).unwrap();
        let loaded = read_anchor_file(&anchors_path).unwrap();
        assert_eq!(loaded.anchors.len(), 2);
        assert_eq!(loaded.anchors[0].path, "src/server.rs");
        assert_eq!(loaded.anchors[0].hash, "abc123");
    }

    #[test]
    fn read_missing_returns_empty() {
        let dir = tempdir().unwrap();
        let anchors_path = dir.path().join("nonexistent.anchors.toml");
        let loaded = read_anchor_file(&anchors_path).unwrap();
        assert!(loaded.anchors.is_empty());
    }

    #[test]
    fn extract_paths_from_content() {
        let content = "## Key Abstractions\n\
                       | `Tool` trait | `src/tools/mod.rs:228` | Core tool abstraction |\n\
                       | `OutputGuard` | `src/tools/output.rs` | Progressive disclosure |\n\
                       See also `Cargo.toml` and `docs/ARCHITECTURE.md`.\n\
                       Not a path: src without extension or random text.";
        let paths = extract_paths(content);
        assert!(paths.contains(&"src/tools/mod.rs".to_string()));
        assert!(paths.contains(&"src/tools/output.rs".to_string()));
        assert!(paths.contains(&"Cargo.toml".to_string()));
        assert!(paths.contains(&"docs/ARCHITECTURE.md".to_string()));
        assert!(!paths.contains(&"src/tools/mod.rs:228".to_string()));
    }

    #[test]
    fn extract_paths_deduplicates() {
        let content = "See `src/server.rs` and also `src/server.rs` again.";
        let paths = extract_paths(content);
        assert_eq!(paths.len(), 1);
    }

    #[test]
    fn seed_anchors_only_for_existing_files() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(root.join("src/tools")).unwrap();
        std::fs::write(root.join("src/tools/mod.rs"), "fn main() {}").unwrap();

        let content = "Uses `src/tools/mod.rs` and `src/nonexistent.rs`.";
        let anchors = seed_anchors(root, content).unwrap();
        assert_eq!(anchors.anchors.len(), 1);
        assert_eq!(anchors.anchors[0].path, "src/tools/mod.rs");
        assert!(!anchors.anchors[0].hash.is_empty());
    }

    #[test]
    fn merge_preserves_user_added_paths() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/a.rs"), "a").unwrap();
        std::fs::write(root.join("src/b.rs"), "b").unwrap();
        std::fs::write(root.join("src/c.rs"), "c").unwrap();

        let existing = AnchorFile {
            anchors: vec![
                PathAnchor {
                    path: "src/a.rs".into(),
                    hash: "old_hash".into(),
                },
                PathAnchor {
                    path: "src/b.rs".into(),
                    hash: "user_added".into(),
                },
            ],
        };
        let new_seed = seed_anchors(root, "Uses `src/a.rs` and `src/c.rs`.").unwrap();
        let merged = merge_anchors(root, &existing, &new_seed).unwrap();

        let paths: Vec<&str> = merged.anchors.iter().map(|a| a.path.as_str()).collect();
        assert!(paths.contains(&"src/a.rs"));
        assert!(paths.contains(&"src/b.rs"));
        assert!(paths.contains(&"src/c.rs"));
        let a = merged
            .anchors
            .iter()
            .find(|a| a.path == "src/a.rs")
            .unwrap();
        assert_ne!(a.hash, "old_hash");
    }

    #[test]
    fn check_staleness_detects_changes() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/a.rs"), "version 1").unwrap();

        let anchors = seed_anchors(root, "Uses `src/a.rs`.").unwrap();

        // Fresh check
        let report = check_path_staleness(root, &anchors).unwrap();
        assert!(report.stale_files.is_empty());

        // Modify → changed
        std::fs::write(root.join("src/a.rs"), "version 2").unwrap();
        let report = check_path_staleness(root, &anchors).unwrap();
        assert_eq!(report.stale_files.len(), 1);
        assert_eq!(report.stale_files[0].status, AnchorStatus::Changed);

        // Delete → deleted
        std::fs::remove_file(root.join("src/a.rs")).unwrap();
        let report = check_path_staleness(root, &anchors).unwrap();
        assert_eq!(report.stale_files[0].status, AnchorStatus::Deleted);
    }

    #[test]
    fn check_staleness_all_fresh() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/a.rs"), "stable").unwrap();

        let anchors = seed_anchors(root, "Uses `src/a.rs`.").unwrap();
        let report = check_path_staleness(root, &anchors).unwrap();
        assert!(report.is_fresh());
    }

    // --- check_all_memories tests ---
    // These serve as a regression baseline for the let-else continue guard on
    // file_stem() added in commit f453270.

    /// A .md file with no matching .anchors.toml sidecar → appears in
    /// result["untracked"].
    #[test]
    fn check_all_memories_untracked() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        let memories_dir = root.join("memories");
        std::fs::create_dir_all(&memories_dir).unwrap();

        // Write a .md file but NO sidecar.
        std::fs::write(memories_dir.join("arch.md"), "# Arch").unwrap();

        let result = check_all_memories(root, &memories_dir).unwrap();

        let untracked = result["untracked"].as_array().unwrap();
        assert_eq!(untracked.len(), 1);
        assert_eq!(untracked[0].as_str().unwrap(), "arch");

        assert!(result["fresh"].as_array().unwrap().is_empty());
        assert!(result["stale"].as_array().unwrap().is_empty());
    }

    /// A .md file with a sidecar where all anchored paths are unchanged →
    /// appears in result["fresh"].
    #[test]
    fn check_all_memories_fresh() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        let memories_dir = root.join("memories");
        std::fs::create_dir_all(&memories_dir).unwrap();
        std::fs::create_dir_all(root.join("src")).unwrap();

        // Write a source file that the memory references.
        std::fs::write(root.join("src/lib.rs"), "stable content").unwrap();

        // Write the .md memory file.
        std::fs::write(memories_dir.join("overview.md"), "References `src/lib.rs`.").unwrap();

        // Build a sidecar with the current hash.
        let anchors = seed_anchors(root, "References `src/lib.rs`.").unwrap();
        let sidecar_path = anchor_path_for_topic(&memories_dir, "overview");
        write_anchor_file(&sidecar_path, &anchors).unwrap();

        let result = check_all_memories(root, &memories_dir).unwrap();

        let fresh = result["fresh"].as_array().unwrap();
        assert_eq!(fresh.len(), 1);
        assert_eq!(fresh[0].as_str().unwrap(), "overview");

        assert!(result["untracked"].as_array().unwrap().is_empty());
        assert!(result["stale"].as_array().unwrap().is_empty());
    }

    /// A .md file with a sidecar referencing a path that has been modified →
    /// appears in result["stale"] with the changed file listed.
    #[test]
    fn check_all_memories_stale() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        let memories_dir = root.join("memories");
        std::fs::create_dir_all(&memories_dir).unwrap();
        std::fs::create_dir_all(root.join("src")).unwrap();

        // Write a source file and seed anchors while it is at version 1.
        std::fs::write(root.join("src/lib.rs"), "version 1").unwrap();
        let anchors = seed_anchors(root, "References `src/lib.rs`.").unwrap();

        std::fs::write(memories_dir.join("overview.md"), "References `src/lib.rs`.").unwrap();
        let sidecar_path = anchor_path_for_topic(&memories_dir, "overview");
        write_anchor_file(&sidecar_path, &anchors).unwrap();

        // Mutate the anchored file so the hash diverges.
        std::fs::write(root.join("src/lib.rs"), "version 2").unwrap();

        let result = check_all_memories(root, &memories_dir).unwrap();

        let stale = result["stale"].as_array().unwrap();
        assert_eq!(stale.len(), 1);
        assert_eq!(stale[0]["topic"].as_str().unwrap(), "overview");
        let changed = stale[0]["changed_files"].as_array().unwrap();
        assert_eq!(changed.len(), 1);
        assert!(changed.iter().any(|v| v.as_str().unwrap() == "src/lib.rs"));

        assert!(result["fresh"].as_array().unwrap().is_empty());
        assert!(result["untracked"].as_array().unwrap().is_empty());
    }

    /// A nested topic (subdir/topic.md) with no sidecar → appears in
    /// result["untracked"] with the full relative path as the topic name.
    #[test]
    fn check_all_memories_nested_untracked() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        let memories_dir = root.join("memories");
        std::fs::create_dir_all(memories_dir.join("debugging")).unwrap();

        std::fs::write(memories_dir.join("debugging/async-patterns.md"), "# Async").unwrap();

        let result = check_all_memories(root, &memories_dir).unwrap();

        let untracked = result["untracked"].as_array().unwrap();
        assert_eq!(untracked.len(), 1);
        assert_eq!(untracked[0].as_str().unwrap(), "debugging/async-patterns");

        assert!(result["fresh"].as_array().unwrap().is_empty());
        assert!(result["stale"].as_array().unwrap().is_empty());
    }

    /// A nested topic with a valid sidecar whose anchored file is unchanged →
    /// appears in result["fresh"] with the full relative path as the topic name.
    #[test]
    fn check_all_memories_nested_fresh() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        let memories_dir = root.join("memories");
        std::fs::create_dir_all(memories_dir.join("debugging")).unwrap();
        std::fs::create_dir_all(root.join("src")).unwrap();

        std::fs::write(root.join("src/lib.rs"), "stable content").unwrap();
        std::fs::write(
            memories_dir.join("debugging/async-patterns.md"),
            "References `src/lib.rs`.",
        )
        .unwrap();

        let anchors = seed_anchors(root, "References `src/lib.rs`.").unwrap();
        let sidecar = anchor_path_for_topic(&memories_dir, "debugging/async-patterns");
        write_anchor_file(&sidecar, &anchors).unwrap();

        let result = check_all_memories(root, &memories_dir).unwrap();

        let fresh = result["fresh"].as_array().unwrap();
        assert_eq!(fresh.len(), 1);
        assert_eq!(fresh[0].as_str().unwrap(), "debugging/async-patterns");

        assert!(result["untracked"].as_array().unwrap().is_empty());
        assert!(result["stale"].as_array().unwrap().is_empty());
    }

    /// A nested topic with a sidecar referencing a path that has been modified →
    /// appears in result["stale"] with the full relative path as the topic name.
    #[test]
    fn check_all_memories_nested_stale() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        let memories_dir = root.join("memories");
        std::fs::create_dir_all(memories_dir.join("debugging")).unwrap();
        std::fs::create_dir_all(root.join("src")).unwrap();

        std::fs::write(root.join("src/lib.rs"), "version 1").unwrap();
        let anchors = seed_anchors(root, "References `src/lib.rs`.").unwrap();

        std::fs::write(
            memories_dir.join("debugging/async-patterns.md"),
            "References `src/lib.rs`.",
        )
        .unwrap();
        let sidecar = anchor_path_for_topic(&memories_dir, "debugging/async-patterns");
        write_anchor_file(&sidecar, &anchors).unwrap();

        // Mutate the anchored file so the hash diverges.
        std::fs::write(root.join("src/lib.rs"), "version 2").unwrap();

        let result = check_all_memories(root, &memories_dir).unwrap();

        let stale = result["stale"].as_array().unwrap();
        assert_eq!(stale.len(), 1);
        assert_eq!(
            stale[0]["topic"].as_str().unwrap(),
            "debugging/async-patterns"
        );
        let changed = stale[0]["changed_files"].as_array().unwrap();
        assert_eq!(changed.len(), 1);
        assert!(changed.iter().any(|v| v.as_str().unwrap() == "src/lib.rs"));

        assert!(result["fresh"].as_array().unwrap().is_empty());
        assert!(result["untracked"].as_array().unwrap().is_empty());
    }

    /// Non-`.md` files (e.g. dotfiles like `.hidden`) in the memories directory
    /// must be silently skipped by the `extension() == "md"` guard at the top of
    /// the loop. The valid `.md` file in the same directory must still appear as
    /// untracked.
    #[test]
    fn check_all_memories_skips_non_md_files() {
        let dir = tempdir().unwrap();
        let root = dir.path();
        let memories_dir = root.join("memories");
        std::fs::create_dir_all(&memories_dir).unwrap();

        // A normal memory file — no sidecar, so it will appear as untracked.
        std::fs::write(memories_dir.join("topics.md"), "# Topics").unwrap();

        // A dotfile: `.hidden` has no extension — Rust treats the leading dot as
        // part of the stem, not a separator, so `extension()` returns `None`.
        // The `extension() == "md"` guard at the top of the loop excludes it
        // before `file_stem()` is ever called.
        std::fs::write(memories_dir.join(".hidden"), "should be ignored").unwrap();

        // Must not panic — the extension guard silently skips non-.md entries.
        let result = check_all_memories(root, &memories_dir).unwrap();

        // The dotfile must not appear anywhere in the result.
        let untracked = result["untracked"].as_array().unwrap();
        let fresh = result["fresh"].as_array().unwrap();
        let stale = result["stale"].as_array().unwrap();
        assert!(
            !untracked
                .iter()
                .any(|v| v.as_str().unwrap_or("") == ".hidden"),
            "dotfile must not appear in untracked"
        );
        assert!(fresh.is_empty(), "dotfile must not appear in fresh");
        assert!(stale.is_empty(), "dotfile must not appear in stale");

        // The valid file must appear as untracked (no sidecar).
        assert_eq!(untracked.len(), 1);
        assert_eq!(untracked[0].as_str().unwrap(), "topics");
    }

    #[test]
    fn stale_file_serializes_to_json() {
        let sf = super::StaleFile {
            path: "src/foo.rs".to_string(),
            status: super::AnchorStatus::Changed,
        };
        let json = serde_json::to_value(&sf).unwrap();
        assert_eq!(json["path"], "src/foo.rs");
        assert_eq!(json["status"], "changed");

        let sf_deleted = super::StaleFile {
            path: "src/bar.rs".to_string(),
            status: super::AnchorStatus::Deleted,
        };
        let json = serde_json::to_value(&sf_deleted).unwrap();
        assert_eq!(json["status"], "deleted");
    }

    #[test]
    fn anchor_path_blocks_traversal() {
        let memories_dir = std::path::PathBuf::from("/tmp/test_memories");
        let path = anchor_path_for_topic(&memories_dir, "../../etc/passwd");
        assert!(
            path.starts_with(&memories_dir),
            "anchor path {:?} must be inside {:?}",
            path,
            memories_dir,
        );
    }
}