wsb-daemon 0.248.6265

wsb's daemon: the workbench, the GitHub mirror's schedule and peer continuity, for every workspace on the machine
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
//! Markdown-based notes linked to workspace paths via their link graph.
//!
//! # Model
//! A "note" is any `.md` file anywhere in the workspace.  A note is
//! *linked* to a workspace path if and only if that workspace-relative path
//! string appears as a markdown link target somewhere in the file:
//!
//!   ```markdown
//!   See [src/main.rs](src/main.rs) for the entry point.
//!   ```
//!
//! No database table tracks this relationship — it is derived on demand by
//! scanning file content.
//!
//! # Default note location
//! When a new note is created for a given workspace path the target directory
//! is chosen as follows:
//!
//! * If the path lies inside a git submodule `<sub>/…`, the note is placed
//!   in `<sub>/docs/`.
//! * Otherwise it is placed in `docs/` at the workspace root.
//!
//! Both directories are created on demand.
use wsb::prelude::*;

use ignore::WalkBuilder;
use std::time::UNIX_EPOCH;

// ── Public types ─────────────────────────────────────────────────────────────

/// Metadata about a markdown note file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathNote {
    /// Workspace-relative path to this note file (e.g. `docs/src-main-rs.md`).
    pub path: String,
    /// Title from the first `# Heading` line, or the filename stem.
    pub title: String,
    /// All workspace-relative paths this note links to (extracted from `](…)` targets).
    pub links: Vec<String>,
    /// ISO-8601 last-modified timestamp.
    pub updated_at: String,
}

// ── Link extraction ───────────────────────────────────────────────────────────

/// Extract all `](target)` link targets from markdown content.
///
/// HTTP(S) URLs and pure fragment anchors (`#…`) are excluded.  Targets
/// beginning with `/` are treated as workspace-root-absolute paths: the
/// leading `/` is stripped so all returned targets are workspace-relative
/// (e.g. `](/capdag/src/main.rs)` → `"capdag/src/main.rs"`).
pub fn extract_link_targets(content: &str) -> Vec<String> {
    let bytes = content.as_bytes();
    let mut targets = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        // Locate `](`
        if i + 1 < bytes.len() && bytes[i] == b']' && bytes[i + 1] == b'(' {
            i += 2;
            let start = i;
            // Collect until `)`, `"`, ` `, or newline — these all terminate
            // the link target in CommonMark.
            while i < bytes.len()
                && bytes[i] != b')'
                && bytes[i] != b'"'
                && bytes[i] != b' '
                && bytes[i] != b'\n'
            {
                i += 1;
            }
            let target = &content[start..i];
            if !target.is_empty()
                && !target.starts_with("http://")
                && !target.starts_with("https://")
                && !target.starts_with('#')
            {
                // Strip leading `/` — workspace-root-absolute paths are
                // normalised to workspace-relative so all downstream code
                // works uniformly.
                let normalised = target.strip_prefix('/').unwrap_or(target);
                if !normalised.is_empty() {
                    targets.push(normalised.to_string());
                }
            }
        } else {
            i += 1;
        }
    }
    targets
}

/// Return `true` if `needle` (a workspace-relative path) is the target of at
/// least one markdown link in `content`.
///
/// Matches both `](needle)` and `](/needle)` (workspace-root-absolute form),
/// as well as the anchor and title variants of each.
pub fn note_mentions_path(content: &str, needle: &str) -> bool {
    // Check both the bare relative form `](needle` and the
    // workspace-root-absolute form `](/needle`.
    for prefix in [format!("]({needle}"), format!("](/{needle}")] {
        let mut start = 0;
        while let Some(pos) = content[start..].find(&prefix) {
            let abs = start + pos + prefix.len();
            match content.as_bytes().get(abs) {
                // Exact match or valid terminator — this is a real link to needle.
                Some(b')') | Some(b'#') | Some(b' ') | Some(b'"') | None => return true,
                _ => {}
            }
            start += pos + prefix.len();
        }
    }
    false
}

// ── Title extraction ──────────────────────────────────────────────────────────

/// Extract a display title from note content.
///
/// Returns the first non-empty ATX heading (`# …`) if one exists, otherwise
/// the filename stem.
pub fn extract_title(content: &str, path: &str) -> String {
    for line in content.lines() {
        if line.starts_with('#') {
            let trimmed = line.trim_start_matches('#').trim();
            if !trimmed.is_empty() {
                return trimmed.to_string();
            }
        }
    }
    Path::new(path)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or(path)
        .to_string()
}

// ── mtime helper ─────────────────────────────────────────────────────────────

fn mtime_iso(meta: &std::fs::Metadata) -> String {
    meta.modified()
        .ok()
        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
        .and_then(|d| chrono::DateTime::from_timestamp(d.as_secs() as i64, 0))
        .map(|dt| dt.format("%Y-%m-%dT%H:%M:%SZ").to_string())
        .unwrap_or_default()
}

// ── Note builder ─────────────────────────────────────────────────────────────

/// Derive the implicit owner of a note from its path.
///
/// Any `.md` file under `<owner>/docs/` is implicitly about `<owner>` — the
/// directory whose `docs/` folder it lives in.  Notes at the root `docs/`
/// level have no implicit owner (they belong to the workspace root "").
///
/// Returns the implicit owner path, or `None` for root-level notes.
pub fn implicit_owner(note_path: &str) -> Option<String> {
    let p = Path::new(note_path);
    let mut components: Vec<_> = p.components().collect();
    // Must have at least 3 components: <owner>/<docs>/<file.md>
    if components.len() < 3 {
        return None;
    }
    // Second-to-last component must be "docs"
    let docs_component = components[components.len() - 2];
    if docs_component.as_os_str() != "docs" {
        return None;
    }
    // Everything before "docs" is the owner path
    components.truncate(components.len() - 2);
    let owner: PathBuf = components.iter().collect();
    // `/` on every platform: the owner is a workspace-relative name the page
    // matches against, and on Windows the path's own spelling is `a\b`.
    let s = wsb::platform::slash_path(&owner);
    if s.is_empty() {
        None
    } else {
        Some(s)
    }
}

fn make_path_note(rel_path: &str, content: &str, meta: &std::fs::Metadata) -> PathNote {
    let mut links = extract_link_targets(content);
    // A note in <owner>/docs/ is implicitly linked to <owner>, even if the
    // author wrote no explicit markdown links. This makes hand-authored docs
    // show up as notes on the owner node without requiring any special syntax.
    if let Some(owner) = implicit_owner(rel_path) {
        if !links.contains(&owner) {
            links.push(owner);
        }
    }
    PathNote {
        path: rel_path.to_string(),
        title: extract_title(content, rel_path),
        links,
        updated_at: mtime_iso(meta),
    }
}

// ── Workspace walk ────────────────────────────────────────────────────────────

/// Walk all `.md` files in `workspace_root` respecting `.gitignore`, and
/// invoke `cb(rel_path, content, metadata)` for each one.
///
/// `cb` returning `false` stops the walk early.
fn walk_markdown_files(
    workspace_root: &Path,
    mut cb: impl FnMut(&str, &str, &std::fs::Metadata) -> Result<bool>,
) -> Result<()> {
    let walker = WalkBuilder::new(workspace_root)
        .standard_filters(true)
        .build();

    for entry in walker {
        let entry = entry.context("directory walk error")?;
        if !entry.file_type().map(|ft| ft.is_file()).unwrap_or(false) {
            continue;
        }
        let path = entry.path();
        // Only consider markdown files.
        match path.extension().and_then(|e| e.to_str()) {
            Some("md") | Some("MD") | Some("markdown") => {}
            _ => continue,
        }
        // A note is named by its workspace-relative path, with `/` on every
        // platform, as the notes a page links to are written.
        let rel = wsb::platform::slash_path(
            path.strip_prefix(workspace_root)
                .context("walk returned path outside workspace root")?,
        );
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("failed to read {}", path.display()))?;
        let meta = path
            .metadata()
            .with_context(|| format!("failed to stat {}", path.display()))?;
        if !cb(&rel, &content, &meta)? {
            break;
        }
    }
    Ok(())
}

// ── Public query API ──────────────────────────────────────────────────────────

/// List all notes (`.md` files) in `workspace_root` that are associated with
/// `linked_path` — either via an explicit markdown link in their content, or
/// because they live in `<linked_path>/docs/` (implicit ownership).
pub fn list_path_notes(workspace_root: &Path, linked_path: &str) -> Result<Vec<PathNote>> {
    let mut notes = Vec::new();
    walk_markdown_files(workspace_root, |rel, content, meta| {
        let matches = note_mentions_path(content, linked_path)
            || implicit_owner(rel).as_deref() == Some(linked_path);
        if matches {
            notes.push(make_path_note(rel, content, meta));
        }
        Ok(true)
    })?;
    notes.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(notes)
}

/// List every `.md` file in `workspace_root`, with their extracted link
/// targets.  Used at startup to seed per-path badge counts.
pub fn list_all_notes(workspace_root: &Path) -> Result<Vec<PathNote>> {
    let mut notes = Vec::new();
    walk_markdown_files(workspace_root, |rel, content, meta| {
        notes.push(make_path_note(rel, content, meta));
        Ok(true)
    })?;
    notes.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(notes)
}

// ── Note creation ─────────────────────────────────────────────────────────────

/// Determine which `docs/` directory a new note for `linked_path` should live
/// in, given the set of known submodule paths (workspace-relative, e.g.
/// `["wsb", "wrapper"]`).
///
/// Rules:
/// 1. If `linked_path` starts with a submodule prefix `<sub>/`, the note goes
///    into `<sub>/docs/`.
/// 2. Otherwise it goes into the root `docs/`.
pub fn docs_dir_for_path<'a>(linked_path: &str, submodule_paths: &'a [String]) -> &'a str {
    // Submodules nest, so several of them can contain one path; the note
    // belongs to the innermost — the repository the file is actually committed
    // in. Taking the first match would file a note about
    // `capdag/capdag-rs/src/lib.rs` under `capdag`, in a repository that does
    // not hold the file.
    let mut owner: Option<&'a str> = None;
    for sub in submodule_paths {
        let prefix = format!("{sub}/");
        if linked_path.starts_with(&prefix) || linked_path == sub.as_str() {
            if owner.is_none_or(|current| sub.len() > current.len()) {
                owner = Some(sub.as_str());
            }
        }
    }
    owner.unwrap_or("")
}

/// Create a new note for `linked_path`.
///
/// * `workspace_root`: absolute path to the workspace root.
/// * `linked_path`: workspace-relative path the note should link to.
/// * `submodule_paths`: workspace-relative paths of all known submodules (used
///   to choose the `docs/` directory).
///
/// The note file is written to:
/// * `<workspace_root>/<submodule>/docs/<slug>.md`  — if inside a submodule
/// * `<workspace_root>/docs/<slug>.md`              — otherwise
///
/// The initial content is the sentence that IS the note:
///   ```text
///   Note on [src/main.rs](src/main.rs)
///   ```
pub fn create_path_note(
    workspace_root: &Path,
    linked_path: &str,
    submodule_paths: &[String],
) -> Result<PathNote> {
    let sub = docs_dir_for_path(linked_path, submodule_paths);
    let docs_dir = if sub.is_empty() {
        workspace_root.join("docs")
    } else {
        workspace_root.join(sub).join("docs")
    };
    std::fs::create_dir_all(&docs_dir)
        .with_context(|| format!("failed to create docs dir {}", docs_dir.display()))?;

    let slug = path_to_slug(linked_path);
    let (filename, abs_path) = unique_filename(&docs_dir, &slug);

    let content = format!("Note on [{linked_path}]({linked_path})\n");
    std::fs::write(&abs_path, &content)
        .with_context(|| format!("failed to write note {}", abs_path.display()))?;

    let meta = abs_path
        .metadata()
        .with_context(|| format!("failed to stat {}", abs_path.display()))?;

    let rel_path = if sub.is_empty() {
        format!("docs/{filename}")
    } else {
        format!("{sub}/docs/{filename}")
    };

    Ok(make_path_note(&rel_path, &content, &meta))
}

// ── Slug helpers ──────────────────────────────────────────────────────────────

/// Convert a workspace-relative path to a filesystem-safe slug for use as a
/// note filename (without the `.md` extension).
///
/// `/` and `\` become `-`; every character that is not alphanumeric, `-`, `_`,
/// or `.` is removed; leading/trailing `-` are stripped.
fn path_to_slug(path: &str) -> String {
    let s = path
        .replace(['/', '\\'], "-")
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_' || *c == '.')
        .collect::<String>();
    s.trim_matches('-').to_string()
}

/// Return a `(filename, absolute_path)` pair where `filename` (`<slug>.md` or
/// `<slug>-N.md`) does not collide with an existing file in `dir`.
fn unique_filename(dir: &Path, slug: &str) -> (String, PathBuf) {
    let base = format!("{slug}.md");
    let candidate = dir.join(&base);
    if !candidate.exists() {
        return (base, candidate);
    }
    let mut n: u32 = 1;
    loop {
        let name = format!("{slug}-{n}.md");
        let p = dir.join(&name);
        if !p.exists() {
            return (name, p);
        }
        n += 1;
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    // ── extract_link_targets ─────────────────────────────────────────────────

    #[test]
    fn extract_link_targets_returns_relative_paths() {
        let content = "See [main](src/main.rs) and [lib](src/lib.rs) for details.";
        let targets = extract_link_targets(content);
        assert_eq!(targets, vec!["src/main.rs", "src/lib.rs"]);
    }

    #[test]
    fn extract_link_targets_normalises_root_absolute_paths() {
        // Leading `/` is stripped — workspace-root-absolute and workspace-relative
        // forms must resolve to the same target string.
        let content = "See [capdag](/capdag/src/main.rs) and [wsb](wsb/src/lib.rs).";
        let targets = extract_link_targets(content);
        assert_eq!(targets, vec!["capdag/src/main.rs", "wsb/src/lib.rs"]);
    }

    #[test]
    fn extract_link_targets_excludes_bare_root_slash() {
        // `](/)` is the workspace root itself — strip the `/`, leaving `""`,
        // which is empty and should be excluded.
        let content = "See [root](/).";
        let targets = extract_link_targets(content);
        assert!(targets.is_empty(), "got: {targets:?}");
    }

    #[test]
    fn extract_link_targets_excludes_http_urls() {
        let content = "Visit [site](https://example.com) or [docs](http://docs.rs).";
        let targets = extract_link_targets(content);
        assert!(targets.is_empty(), "got: {targets:?}");
    }

    #[test]
    fn extract_link_targets_excludes_fragment_anchors() {
        let content = "See [section](#heading) or [sub](doc.md#sub).";
        let targets = extract_link_targets(content);
        // fragment-only is excluded; path#anchor is included (it's still a file reference)
        assert!(!targets.contains(&"#heading".to_string()));
        assert!(
            targets.contains(&"doc.md#sub".to_string()) || targets.contains(&"doc.md".to_string()),
            "expected doc.md reference, got: {targets:?}"
        );
    }

    #[test]
    fn extract_link_targets_handles_link_with_title() {
        // CommonMark: `[text](target "title")`
        let content = r#"[click](src/main.rs "go here")"#;
        let targets = extract_link_targets(content);
        assert_eq!(targets, vec!["src/main.rs"]);
    }

    #[test]
    fn extract_link_targets_empty_on_plain_text() {
        let content = "No links here at all.";
        assert!(extract_link_targets(content).is_empty());
    }

    // ── note_mentions_path ───────────────────────────────────────────────────

    #[test]
    fn note_mentions_path_exact_match() {
        let content = "Note on [src/main.rs](src/main.rs)\n";
        assert!(note_mentions_path(content, "src/main.rs"));
    }

    #[test]
    fn note_mentions_path_with_anchor() {
        let content = "See [header](src/main.rs#header) here.";
        assert!(note_mentions_path(content, "src/main.rs"));
    }

    #[test]
    fn note_mentions_path_with_title() {
        let content = r#"[x](src/main.rs "title")"#;
        assert!(note_mentions_path(content, "src/main.rs"));
    }

    #[test]
    fn note_mentions_path_matches_root_absolute_form() {
        // The user writes `](/capdag/src/main.rs)` — must match `capdag/src/main.rs`.
        let content = "See [capdag main](/capdag/src/main.rs) for details.";
        assert!(note_mentions_path(content, "capdag/src/main.rs"));
    }

    #[test]
    fn note_mentions_path_root_absolute_with_anchor() {
        let content = "See [header](/capdag/src/main.rs#init) here.";
        assert!(note_mentions_path(content, "capdag/src/main.rs"));
    }

    #[test]
    fn note_mentions_path_root_absolute_no_false_positive_on_prefix() {
        // `](/capdag/src/main.rs.bak)` must NOT match `capdag/src/main.rs`.
        let content = "Note on [backup](/capdag/src/main.rs.bak)\n";
        assert!(!note_mentions_path(content, "capdag/src/main.rs"));
    }

    #[test]
    fn note_mentions_path_no_false_positive_on_prefix() {
        // "src/main.rs" must NOT match a link to "src/main.rs.bak"
        let content = "Note on [backup](src/main.rs.bak)\n";
        assert!(!note_mentions_path(content, "src/main.rs"));
    }

    #[test]
    fn note_mentions_path_no_match_on_unrelated_content() {
        let content = "Nothing about src/main.rs here.\n";
        assert!(!note_mentions_path(content, "src/main.rs"));
    }

    // ── implicit_owner ───────────────────────────────────────────────────────

    #[test]
    fn implicit_owner_returns_parent_of_docs_dir() {
        assert_eq!(
            implicit_owner("capdag/docs/overview.md").as_deref(),
            Some("capdag")
        );
        assert_eq!(
            implicit_owner("capdag-dot-com/docs/api.md").as_deref(),
            Some("capdag-dot-com")
        );
        assert_eq!(implicit_owner("a/b/docs/file.md").as_deref(), Some("a/b"));
    }

    #[test]
    fn implicit_owner_returns_none_for_root_docs() {
        // docs/file.md — lives in the workspace root docs/, owner is root ""
        assert_eq!(implicit_owner("docs/overview.md"), None);
    }

    #[test]
    fn implicit_owner_returns_none_for_non_docs_path() {
        assert_eq!(implicit_owner("capdag/src/main.rs"), None);
        assert_eq!(implicit_owner("README.md"), None);
    }

    #[test]
    fn make_path_note_adds_implicit_owner_link_when_no_explicit_link() {
        use std::fs;
        let temp = TempDir::new().unwrap();
        let docs = temp.path().join("capdag/docs");
        fs::create_dir_all(&docs).unwrap();
        fs::write(docs.join("spec.md"), "# Spec\nPure prose, no links.\n").unwrap();

        let notes = list_all_notes(temp.path()).unwrap();
        assert_eq!(notes.len(), 1);
        assert!(
            notes[0].links.contains(&"capdag".to_string()),
            "implicit owner link missing, got: {:?}",
            notes[0].links
        );
    }

    #[test]
    fn make_path_note_does_not_duplicate_explicit_link_to_owner() {
        use std::fs;
        let temp = TempDir::new().unwrap();
        let docs = temp.path().join("capdag/docs");
        fs::create_dir_all(&docs).unwrap();
        // Already has an explicit link to capdag
        fs::write(docs.join("note.md"), "Note on [capdag](capdag)\n").unwrap();

        let notes = list_all_notes(temp.path()).unwrap();
        assert_eq!(
            notes[0].links.iter().filter(|l| *l == "capdag").count(),
            1,
            "duplicate implicit link, got: {:?}",
            notes[0].links
        );
    }

    #[test]
    fn list_path_notes_finds_notes_without_explicit_link_via_implicit_owner() {
        use std::fs;
        let temp = TempDir::new().unwrap();
        let docs = temp.path().join("capdag/docs");
        fs::create_dir_all(&docs).unwrap();
        // Pure prose — no markdown link to capdag at all
        fs::write(
            docs.join("01-OVERVIEW.md"),
            "# Overview\nThis is the capdag spec.\n",
        )
        .unwrap();

        let notes = list_path_notes(temp.path(), "capdag").unwrap();
        assert_eq!(
            notes.len(),
            1,
            "expected note via implicit owner, got: {notes:?}"
        );
        assert_eq!(notes[0].path, "capdag/docs/01-OVERVIEW.md");
    }

    #[test]
    fn list_path_notes_does_not_match_sibling_docs_dirs() {
        use std::fs;
        let temp = TempDir::new().unwrap();
        fs::create_dir_all(temp.path().join("capdag/docs")).unwrap();
        fs::create_dir_all(temp.path().join("candlecartridge/docs")).unwrap();
        fs::write(temp.path().join("capdag/docs/spec.md"), "# Spec\n").unwrap();
        fs::write(
            temp.path().join("candlecartridge/docs/guide.md"),
            "# Guide\n",
        )
        .unwrap();

        let capdag_notes = list_path_notes(temp.path(), "capdag").unwrap();
        assert_eq!(capdag_notes.len(), 1);
        assert_eq!(capdag_notes[0].path, "capdag/docs/spec.md");

        let cc_notes = list_path_notes(temp.path(), "candlecartridge").unwrap();
        assert_eq!(cc_notes.len(), 1);
        assert_eq!(cc_notes[0].path, "candlecartridge/docs/guide.md");
    }

    // ── extract_title ────────────────────────────────────────────────────────

    #[test]
    fn extract_title_uses_first_heading() {
        let content = "# My Note\nsome content";
        assert_eq!(extract_title(content, "slug.md"), "My Note");
    }

    #[test]
    fn extract_title_uses_h2_when_no_h1() {
        let content = "## Section\nsome content";
        assert_eq!(extract_title(content, "slug.md"), "Section");
    }

    #[test]
    fn extract_title_falls_back_to_filename_stem() {
        let content = "Just prose, no heading.";
        assert_eq!(extract_title(content, "docs/src-main-rs.md"), "src-main-rs");
    }

    #[test]
    fn extract_title_skips_empty_headings() {
        let content = "#\n## Real Heading\ncontent";
        assert_eq!(extract_title(content, "x.md"), "Real Heading");
    }

    // ── path_to_slug ─────────────────────────────────────────────────────────

    #[test]
    fn path_to_slug_converts_slashes_to_dashes() {
        assert_eq!(path_to_slug("src/web/mod.rs"), "src-web-mod.rs");
    }

    #[test]
    fn path_to_slug_strips_leading_trailing_dashes() {
        assert_eq!(path_to_slug("/src/main.rs"), "src-main.rs");
    }

    #[test]
    fn path_to_slug_removes_special_chars() {
        assert_eq!(path_to_slug("src/foo bar.rs"), "src-foobar.rs");
    }

    // ── docs_dir_for_path ────────────────────────────────────────────────────

    #[test]
    fn docs_dir_for_path_root_when_no_submodule_matches() {
        let subs = vec!["wsb".to_string(), "wrapper".to_string()];
        assert_eq!(docs_dir_for_path("README.md", &subs), "");
        assert_eq!(docs_dir_for_path("docs/guide.md", &subs), "");
    }

    #[test]
    fn docs_dir_for_path_returns_submodule_for_nested_path() {
        let subs = vec!["wsb".to_string(), "wrapper".to_string()];
        assert_eq!(docs_dir_for_path("wsb/src/main.rs", &subs), "wsb");
        assert_eq!(
            docs_dir_for_path("wrapper/Sources/Foo.swift", &subs),
            "wrapper"
        );
    }

    /// TEST9616: a note about a file in a nested submodule is filed in that
    /// submodule, not in an ancestor that happens to be listed first. The
    /// ancestor does not hold the file, so the note would sit in a repository
    /// where nothing links to it.
    #[test]
    fn test9616_the_innermost_submodule_owns_the_note() {
        let subs = vec![
            "capdag".to_string(),
            "capdag/capdag-rs".to_string(),
            "capdag/capdag-rs/vendor/dep".to_string(),
        ];

        assert_eq!(docs_dir_for_path("capdag/README.md", &subs), "capdag");
        assert_eq!(
            docs_dir_for_path("capdag/capdag-rs/src/lib.rs", &subs),
            "capdag/capdag-rs"
        );
        assert_eq!(
            docs_dir_for_path("capdag/capdag-rs/vendor/dep/src/lib.rs", &subs),
            "capdag/capdag-rs/vendor/dep"
        );
        assert_eq!(
            docs_dir_for_path("capdag/capdag-rs", &subs),
            "capdag/capdag-rs"
        );
    }

    #[test]
    fn docs_dir_for_path_exact_submodule_path() {
        let subs = vec!["wsb".to_string()];
        assert_eq!(docs_dir_for_path("wsb", &subs), "wsb");
    }

    // ── list_path_notes ──────────────────────────────────────────────────────

    #[test]
    fn list_path_notes_finds_notes_linking_to_path() {
        let temp = TempDir::new().unwrap();
        let docs = temp.path().join("docs");
        fs::create_dir_all(&docs).unwrap();

        // This note links to src/main.rs
        fs::write(
            docs.join("note-on-main.md"),
            "Note on [src/main.rs](src/main.rs)\n",
        )
        .unwrap();
        // This note does NOT link to src/main.rs
        fs::write(docs.join("other.md"), "Note on [src/lib.rs](src/lib.rs)\n").unwrap();

        let notes = list_path_notes(temp.path(), "src/main.rs").unwrap();
        assert_eq!(notes.len(), 1, "expected 1 note, got: {notes:?}");
        assert_eq!(notes[0].path, "docs/note-on-main.md");
    }

    #[test]
    fn list_path_notes_returns_empty_when_no_notes_match() {
        let temp = TempDir::new().unwrap();
        let docs = temp.path().join("docs");
        fs::create_dir_all(&docs).unwrap();
        fs::write(docs.join("other.md"), "# Unrelated\nNo links here.\n").unwrap();

        let notes = list_path_notes(temp.path(), "src/main.rs").unwrap();
        assert!(notes.is_empty());
    }

    #[test]
    fn list_path_notes_scans_across_subdirectories() {
        let temp = TempDir::new().unwrap();
        fs::create_dir_all(temp.path().join("docs")).unwrap();
        fs::create_dir_all(temp.path().join("wsb/docs")).unwrap();

        fs::write(
            temp.path().join("docs/root-note.md"),
            "Note on [README.md](README.md)\n",
        )
        .unwrap();
        fs::write(
            temp.path().join("wsb/docs/sub-note.md"),
            "Note on [README.md](README.md)\n",
        )
        .unwrap();

        let notes = list_path_notes(temp.path(), "README.md").unwrap();
        assert_eq!(notes.len(), 2, "expected 2 notes, got: {notes:?}");
        let paths: Vec<&str> = notes.iter().map(|n| n.path.as_str()).collect();
        assert!(paths.contains(&"docs/root-note.md"), "paths: {paths:?}");
        assert!(paths.contains(&"wsb/docs/sub-note.md"), "paths: {paths:?}");
    }

    #[test]
    fn list_path_notes_no_false_positive_on_path_prefix() {
        let temp = TempDir::new().unwrap();
        let docs = temp.path().join("docs");
        fs::create_dir_all(&docs).unwrap();
        // Links to "src/main.rs.bak" — must NOT match "src/main.rs"
        fs::write(docs.join("note.md"), "Note on [backup](src/main.rs.bak)\n").unwrap();

        let notes = list_path_notes(temp.path(), "src/main.rs").unwrap();
        assert!(notes.is_empty(), "got: {notes:?}");
    }

    // ── list_all_notes ───────────────────────────────────────────────────────

    #[test]
    fn list_all_notes_returns_every_md_file_with_links() {
        let temp = TempDir::new().unwrap();
        let docs = temp.path().join("docs");
        fs::create_dir_all(&docs).unwrap();
        fs::write(docs.join("a.md"), "Note on [src/main.rs](src/main.rs)\n").unwrap();
        fs::write(docs.join("b.md"), "# Standalone\nNo links.\n").unwrap();

        let notes = list_all_notes(temp.path()).unwrap();
        assert_eq!(notes.len(), 2);
        let a = notes.iter().find(|n| n.path.ends_with("a.md")).unwrap();
        assert_eq!(a.links, vec!["src/main.rs"]);
        let b = notes.iter().find(|n| n.path.ends_with("b.md")).unwrap();
        assert!(b.links.is_empty());
    }

    // ── create_path_note ─────────────────────────────────────────────────────

    #[test]
    fn create_path_note_writes_to_root_docs_when_no_submodule_matches() {
        let temp = TempDir::new().unwrap();
        let note = create_path_note(temp.path(), "README.md", &[]).unwrap();

        assert!(note.path.starts_with("docs/"), "got: {}", note.path);
        let abs = temp.path().join(&note.path);
        assert!(abs.exists(), "file not found at {}", abs.display());
        let content = fs::read_to_string(&abs).unwrap();
        assert!(content.contains("](README.md)"), "content: {content}");
    }

    #[test]
    fn create_path_note_writes_to_submodule_docs_when_path_is_inside_submodule() {
        let temp = TempDir::new().unwrap();
        // Pretend "wsb" is a submodule.
        fs::create_dir_all(temp.path().join("wsb/src")).unwrap();
        let subs = vec!["wsb".to_string()];
        let note = create_path_note(temp.path(), "wsb/src/main.rs", &subs).unwrap();

        assert!(note.path.starts_with("wsb/docs/"), "got: {}", note.path);
        let abs = temp.path().join(&note.path);
        assert!(abs.exists());
        let content = fs::read_to_string(&abs).unwrap();
        assert!(content.contains("](wsb/src/main.rs)"), "content: {content}");
    }

    #[test]
    fn create_path_note_creates_docs_dir_if_missing() {
        let temp = TempDir::new().unwrap();
        // docs/ does not exist yet
        assert!(!temp.path().join("docs").exists());
        create_path_note(temp.path(), "src/lib.rs", &[]).unwrap();
        assert!(temp.path().join("docs").exists());
    }

    #[test]
    fn create_path_note_avoids_filename_collision() {
        let temp = TempDir::new().unwrap();
        let docs = temp.path().join("docs");
        fs::create_dir_all(&docs).unwrap();

        // Pre-create the slug file so the second call must find an alternate name.
        let slug = path_to_slug("src/main.rs");
        fs::write(docs.join(format!("{slug}.md")), "existing\n").unwrap();

        let note = create_path_note(temp.path(), "src/main.rs", &[]).unwrap();
        assert!(
            note.path.ends_with("-1.md"),
            "expected -1 suffix, got {}",
            note.path
        );
    }

    #[test]
    fn create_path_note_initial_content_links_back_to_path() {
        let temp = TempDir::new().unwrap();
        let note = create_path_note(temp.path(), "wsb/src/web/mod.rs", &[]).unwrap();
        let abs = temp.path().join(&note.path);
        let content = fs::read_to_string(abs).unwrap();
        assert_eq!(
            content,
            "Note on [wsb/src/web/mod.rs](wsb/src/web/mod.rs)\n"
        );
    }

    #[test]
    fn created_note_is_immediately_found_by_list_path_notes() {
        let temp = TempDir::new().unwrap();
        create_path_note(temp.path(), "src/main.rs", &[]).unwrap();

        let found = list_path_notes(temp.path(), "src/main.rs").unwrap();
        assert_eq!(found.len(), 1, "expected 1, got: {found:?}");
        assert!(note_mentions_path(
            &format!("Note on [src/main.rs](src/main.rs)\n"),
            "src/main.rs"
        ));
    }
}