nornir 0.4.32

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
//! Per-repo nornir layout and the source→output render pipeline.
//!
//! Every repo owned by nornir gets a `.nornir/` directory at its root:
//!
//! ```text
//! repo/
//! ├── .nornir/                  ← nornir's namespace
//! │   ├── README.md             ← SOURCE (you edit this)
//! │   ├── CHANGELOG.md          ← SOURCE (you edit this)
//! │   ├── assets/               ← TRACKED media (depgraph.svg, logos, figures)
//! │   ├── warehouse/            ← DATA ONLY: the Iceberg warehouse (gitignored)
//! │   ├── cache/                ← transient: images + the docs index (gitignored)
//! │   └── .gitignore            ← ignores cache/ + warehouse/
//! ├── README.md                 ← GENERATED — DO NOT EDIT (chmod -w)
//! ├── CHANGELOG.md              ← GENERATED — DO NOT EDIT (chmod -w)
//! ├── docs/                     ← GENERATED rendered docs (book.pdf/.md, …); tracked
//! └── ...
//! ```
//!
//! Rendered exports (`docs export` / `docs book`) write the *current* artifact
//! to `<repo>/docs/` and historize the bytes in the Iceberg `doc_exports`
//! table; `.nornir/warehouse/` is data-only.
//!
//! The source files use the same `<!-- nornir:gen:start:NAME -->` markers as
//! [`super::sections`] for dynamic fills (bench tables, callgraphs, ...).
//! Render writes the whole output file (not just marker regions) and prepends
//! a loud header so anyone opening the artifact knows where the truth lives.

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

use anyhow::{bail, Context, Result};
use serde::Deserialize;

use super::sections::{rewrite_str, Ctx, FileReport};

/// Header prepended to every generated output file. The leading newline keeps
/// the comment on its own line; the warning lands in line 1 of the artifact.
pub const GENERATED_HEADER_PREFIX: &str =
    "<!-- ⚠ GENERATED by nornir from .nornir/";
pub const GENERATED_HEADER_SUFFIX: &str = " — DO NOT EDIT this file -->\n\n";

/// File names nornir manages by default. Adding new ones is a single-line
/// change: extend this list and they automatically get init / render / check.
pub const MANAGED_DOCS: &[&str] = &["README.md", "CHANGELOG.md"];

/// Per-repo render configuration, read from `<repo>/.nornir/docs.toml`.
///
/// Controls *which artifact(s)* `nornir docs render` emits for this repo:
///
/// - `"markdown"` (alias `"md"`) — the managed top-level `README.md` /
///   `CHANGELOG.md`, rendered from their `.nornir/` sources (nornir's default
///   and historical behaviour).
/// - `"pdf"` — the whole-documentation **book** rendered to `docs/book.pdf`
///   (needs a nornir built with the `docs-export` feature).
/// - `"all"` — both of the above.
///
/// **Absent file ⇒ `["markdown"]`** — so existing repos are unchanged. A repo
/// that wants *only* a rendered PDF and keeps its markdown hand-edited sets:
///
/// ```toml
/// # <repo>/.nornir/docs.toml
/// outputs = ["pdf"]
/// ```
///
/// With `outputs = ["pdf"]`, `render` never writes any markdown into the repo —
/// it only (re)builds `docs/book.pdf` from the repo's doc set. This is the way
/// to add documentation rendering to a project whose `*.md` are authored by
/// hand and must not be overwritten.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct DocsRenderCfg {
    /// Artifact kinds to emit. See the type docs for accepted tokens.
    pub outputs: Vec<String>,
}

impl Default for DocsRenderCfg {
    fn default() -> Self {
        Self {
            outputs: vec!["markdown".to_string()],
        }
    }
}

impl DocsRenderCfg {
    /// Path to the config file: `<repo>/.nornir/docs.toml`.
    pub fn path(layout: &RepoLayout) -> PathBuf {
        layout.nornir_dir().join("docs.toml")
    }

    /// Load the config for `layout`'s repo. Returns the default
    /// (`["markdown"]`) when `.nornir/docs.toml` is absent.
    pub fn load(layout: &RepoLayout) -> Result<Self> {
        let p = Self::path(layout);
        if !p.exists() {
            return Ok(Self::default());
        }
        let text =
            std::fs::read_to_string(&p).with_context(|| format!("read {}", p.display()))?;
        toml::from_str(&text).with_context(|| format!("parse {}", p.display()))
    }

    /// Whether the managed markdown artifacts should be (re)rendered.
    pub fn wants_markdown(&self) -> bool {
        self.outputs
            .iter()
            .any(|o| matches!(o.to_ascii_lowercase().as_str(), "markdown" | "md" | "all"))
    }

    /// Whether the PDF documentation book should be rendered.
    pub fn wants_pdf(&self) -> bool {
        self.outputs
            .iter()
            .any(|o| matches!(o.to_ascii_lowercase().as_str(), "pdf" | "all"))
    }
}

/// Layout of nornir-owned paths under one repo.
#[derive(Debug, Clone)]
pub struct RepoLayout {
    pub repo_root: PathBuf,
}

impl RepoLayout {
    pub fn new(repo_root: impl Into<PathBuf>) -> Self {
        Self {
            repo_root: repo_root.into(),
        }
    }

    /// `<repo>/.nornir/`
    pub fn nornir_dir(&self) -> PathBuf {
        self.repo_root.join(".nornir")
    }
    /// `<repo>/.nornir/warehouse/`
    pub fn warehouse_dir(&self) -> PathBuf {
        self.nornir_dir().join("warehouse")
    }
    /// `<repo>/.nornir/cache/`
    pub fn cache_dir(&self) -> PathBuf {
        self.nornir_dir().join("cache")
    }
    /// Image-cache subdir used by [`super::export`].
    pub fn image_cache_dir(&self) -> PathBuf {
        self.cache_dir().join("images")
    }
    /// Source path for one managed doc, e.g. `.nornir/README.md`.
    pub fn source_of(&self, doc_name: &str) -> PathBuf {
        self.nornir_dir().join(doc_name)
    }
    /// Output (artifact) path for one managed doc, e.g. `README.md`.
    pub fn output_of(&self, doc_name: &str) -> PathBuf {
        self.repo_root.join(doc_name)
    }
    /// `<repo>/docs/` — the canonical, git-tracked output directory for
    /// nornir-rendered documents (README/book PDF/HTML/MD). README links here.
    pub fn docs_dir(&self) -> PathBuf {
        self.repo_root.join("docs")
    }
    /// Path of a rendered export under `docs/`, e.g. `docs/book.pdf`. Stable
    /// (version-free) so links from the README don't churn per release.
    pub fn export_path(&self, doc_name: &str, ext: &str) -> PathBuf {
        self.docs_dir().join(format!("{doc_name}.{ext}"))
    }
}

/// Per-file render outcome.
#[derive(Debug)]
pub struct RenderReport {
    pub doc_name: String,
    pub source: PathBuf,
    pub output: PathBuf,
    pub sections: Vec<String>,
    pub changed: bool,
    pub bytes: usize,
}

/// Render a single managed doc: read source → fill markers → prepend warning
/// → atomically write output → restore read-only bit if file was previously
/// locked. Returns `Ok(None)` when no source exists for that doc (so a repo
/// can opt into only README and not CHANGELOG, etc.).
pub fn render_doc(layout: &RepoLayout, doc_name: &str, ctx: &Ctx) -> Result<Option<RenderReport>> {
    let src = layout.source_of(doc_name);
    if !src.exists() {
        return Ok(None);
    }
    let raw = std::fs::read_to_string(&src)
        .with_context(|| format!("read {}", src.display()))?;
    let (filled, sections) = rewrite_str(&raw, ctx)?;
    let header = format!("{GENERATED_HEADER_PREFIX}{doc_name}{GENERATED_HEADER_SUFFIX}");
    let mut output = String::with_capacity(header.len() + filled.len());
    output.push_str(&header);
    output.push_str(&filled);

    let dst = layout.output_of(doc_name);
    let prev = std::fs::read_to_string(&dst).ok();
    let changed = prev.as_deref() != Some(output.as_str());
    if changed {
        write_atomic(&dst, &output)?;
    }
    Ok(Some(RenderReport {
        doc_name: doc_name.to_string(),
        source: src,
        output: dst,
        sections,
        changed,
        bytes: output.len(),
    }))
}

/// Render every managed doc found under `.nornir/`.
pub fn render_all(layout: &RepoLayout, ctx: &Ctx) -> Result<Vec<RenderReport>> {
    let mut reports = Vec::new();
    for &doc in MANAGED_DOCS {
        if let Some(r) = render_doc(layout, doc, ctx)? {
            reports.push(r);
        }
    }
    Ok(reports)
}

/// Fill `<!-- nornir:gen:* -->` markers **in place** for every non-managed
/// `.nornir/*.md` source (e.g. `design.md`, `plan.md`, `benching.md`).
///
/// Why this exists: [`render_doc`] only rewrites the *managed* docs
/// (`README.md` / `CHANGELOG.md`), reading `.nornir/<doc>.md` as a template and
/// writing the filled result to `<repo>/<doc>.md`. Every other `.nornir/*.md`
/// (design notes, plans, …) has **no separate output** — it *is* the published
/// file (Codeberg/GitHub render it directly). Those sources were only ever
/// marker-expanded transiently inside the PDF/book pipeline ([`super::book`]),
/// so their `nornir:gen:*` blocks — notably `depgraph` — stayed **empty on
/// disk** and were invisible when the file was viewed directly. This populates
/// them in place so the rendered dependency graph (and any other gen section)
/// is actually present in the source markdown.
///
/// Managed-doc sources are skipped here: they are templates whose empty markers
/// are intentional (they get filled into the root output, not the source).
///
/// Returns the report for each `.nornir/*.md` that carried markers.
pub fn render_sources_in_place(layout: &RepoLayout, ctx: &Ctx) -> Result<Vec<FileReport>> {
    use super::sections::assemble_file;
    let dir = layout.nornir_dir();
    let mut reports = Vec::new();
    let Ok(rd) = std::fs::read_dir(&dir) else {
        return Ok(reports);
    };
    let mut paths: Vec<PathBuf> = rd
        .flatten()
        .map(|e| e.path())
        .filter(|p| {
            p.is_file()
                && p.extension()
                    .and_then(|e| e.to_str())
                    .map(|e| e.eq_ignore_ascii_case("md"))
                    .unwrap_or(false)
        })
        .filter(|p| {
            // Skip the managed-doc *templates* — their markers fill into the
            // root output, not the source.
            let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
            !MANAGED_DOCS.contains(&name)
        })
        .collect();
    paths.sort();
    for path in paths {
        // `assemble_file` is a no-op (changed:false, empty sections) for files
        // that carry no `nornir:gen` markers, so hand-authored notes without
        // markers are left byte-for-byte untouched.
        let report = assemble_file(&path, ctx)
            .with_context(|| format!("assemble {}", path.display()))?;
        // Only surface files that actually carried marker sections.
        if !report.sections.is_empty() {
            reports.push(report);
        }
    }
    Ok(reports)
}

/// In-memory dry-run of [`render_doc`] — bails if rendering would change
/// the output file. Use as a CI gate.
pub fn check_doc(layout: &RepoLayout, doc_name: &str, ctx: &Ctx) -> Result<Option<bool>> {
    let src = layout.source_of(doc_name);
    if !src.exists() {
        return Ok(None);
    }
    let raw = std::fs::read_to_string(&src)?;
    let (filled, _) = rewrite_str(&raw, ctx)?;
    let header = format!("{GENERATED_HEADER_PREFIX}{doc_name}{GENERATED_HEADER_SUFFIX}");
    let expected = format!("{header}{filled}");
    let dst = layout.output_of(doc_name);
    let prev = std::fs::read_to_string(&dst).unwrap_or_default();
    if prev != expected {
        bail!(
            "{} is out of date with {} — run `nornir docs render <repo>` to regenerate",
            dst.display(),
            src.display()
        );
    }
    Ok(Some(true))
}

/// Check every managed doc.
pub fn check_all(layout: &RepoLayout, ctx: &Ctx) -> Result<()> {
    for &doc in MANAGED_DOCS {
        check_doc(layout, doc, ctx)?;
    }
    Ok(())
}

/// Scaffold `.nornir/` for a repo:
///   - create `.nornir/`, `.nornir/cache/`, `.nornir/warehouse/`
///   - migrate any existing top-level managed docs (README.md, CHANGELOG.md)
///     into `.nornir/` as the source
///   - if no managed doc exists, write a minimal scaffold for README.md
///   - write `.nornir/.gitignore` (ignores cache/)
///
/// Returns the list of source files now present in `.nornir/`.
pub fn init_repo(layout: &RepoLayout) -> Result<Vec<PathBuf>> {
    std::fs::create_dir_all(layout.nornir_dir())?;
    std::fs::create_dir_all(layout.cache_dir())?;
    std::fs::create_dir_all(layout.warehouse_dir())?;
    std::fs::create_dir_all(layout.image_cache_dir())?;

    let gi = layout.nornir_dir().join(".gitignore");
    if !gi.exists() {
        std::fs::write(&gi, "cache/\n")?;
    }

    let mut sources = Vec::new();
    let mut had_any = false;
    for &doc in MANAGED_DOCS {
        let src = layout.source_of(doc);
        let dst = layout.output_of(doc);
        if src.exists() {
            sources.push(src);
            had_any = true;
            continue;
        }
        if dst.exists() {
            // Migrate the existing artifact into .nornir/ as the source.
            // The artifact will be re-rendered (with the GENERATED warning)
            // on the next `nornir docs render`.
            let existing = std::fs::read_to_string(&dst)
                .with_context(|| format!("read {}", dst.display()))?;
            // Strip any pre-existing GENERATED header so a re-init is a no-op.
            let cleaned = strip_generated_header(&existing);
            std::fs::write(&src, cleaned)
                .with_context(|| format!("write {}", src.display()))?;
            sources.push(src);
            had_any = true;
        }
    }
    if !had_any {
        // No README anywhere — scaffold a starter.
        let starter = scaffold_readme(&layout.repo_root);
        let src = layout.source_of("README.md");
        std::fs::write(&src, starter)?;
        sources.push(src);
    }
    Ok(sources)
}

/// Strip a pre-existing GENERATED-by-nornir header (if any) from the start
/// of `text`. Idempotent.
fn strip_generated_header(text: &str) -> String {
    if let Some(rest) = text.strip_prefix(GENERATED_HEADER_PREFIX) {
        // Find the matching suffix `-->` and the following blank line.
        if let Some(end) = rest.find("-->") {
            let after = &rest[end + 3..];
            let after = after.trim_start_matches(['\n', '\r']);
            return after.to_string();
        }
    }
    text.to_string()
}

fn scaffold_readme(repo_root: &Path) -> String {
    let name = repo_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("project");
    format!(
        r#"# {name}

> One-line description of {name}.

<!-- Headline: paste your single most meaningful benchmark number here, e.g.
     **9,950 MB/s decompress · 32 cores**. The full table renders below. -->

<!-- Write any intro prose here. Anything outside the marker blocks below
     is preserved verbatim on every render. -->

## Benchmarks

<!-- The `benches` renderer pivots the latest run into a table and bolds the
     winning cell per row (e.g. ours vs a legacy tool). Direction is inferred
     from the metric unit (`_mbs` higher-better, `_ms` lower-better); override
     odd cases with `benches best=metric:low`. -->
<!-- nornir:gen:start:benches -->
<!-- nornir:gen:end:benches -->

## Tests

<!-- Unit / integration / doc tests, enumerated from source via syn. -->
<!-- nornir:gen:start:tests -->
<!-- nornir:gen:end:tests -->

## Dependency graph

<!-- nornir:gen:start:depgraph -->
<!-- nornir:gen:end:depgraph -->

## License

MIT OR Apache-2.0.
"#
    )
}

/// Write `content` to `dst` atomically (write to tmp, fsync, rename),
/// honouring a previous read-only bit by clearing it before write and
/// restoring it after.
fn write_atomic(dst: &Path, content: &str) -> Result<()> {
    use std::io::Write;
    if let Some(parent) = dst.parent() {
        std::fs::create_dir_all(parent)?;
    }
    // Capture & clear any read-only bit so we can overwrite.
    let prev_readonly = match std::fs::metadata(dst) {
        Ok(m) => {
            let ro = m.permissions().readonly();
            if ro {
                let mut p = m.permissions();
                #[allow(clippy::permissions_set_readonly_false)]
                p.set_readonly(false);
                std::fs::set_permissions(dst, p)?;
            }
            ro
        }
        Err(_) => false,
    };

    let tmp = dst.with_extension(format!(
        "{}.nornir-tmp",
        dst.extension()
            .and_then(|e| e.to_str())
            .unwrap_or("tmp")
    ));
    {
        let mut f = std::fs::File::create(&tmp)
            .with_context(|| format!("create {}", tmp.display()))?;
        f.write_all(content.as_bytes())?;
        f.sync_all().ok();
    }
    std::fs::rename(&tmp, dst)
        .with_context(|| format!("rename {} -> {}", tmp.display(), dst.display()))?;

    if prev_readonly {
        let mut p = std::fs::metadata(dst)?.permissions();
        p.set_readonly(true);
        std::fs::set_permissions(dst, p)?;
    }
    Ok(())
}

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

    fn layout() -> (TempDir, RepoLayout) {
        let t = TempDir::new().unwrap();
        let l = RepoLayout::new(t.path());
        (t, l)
    }

    #[test]
    fn init_creates_skeleton_when_empty() {
        let (_t, l) = layout();
        let srcs = init_repo(&l).unwrap();
        assert!(l.nornir_dir().exists());
        assert!(l.cache_dir().exists());
        assert!(l.warehouse_dir().exists());
        assert!(l.nornir_dir().join(".gitignore").exists());
        assert_eq!(srcs.len(), 1);
        assert!(srcs[0].ends_with("README.md"));
        let scaffold = std::fs::read_to_string(&srcs[0]).unwrap();
        assert!(scaffold.contains("nornir:gen:start:benches"));
        assert!(scaffold.contains("nornir:gen:start:tests"));
        assert!(scaffold.contains("nornir:gen:start:depgraph"));
    }

    /// Inject a known dep-graph (a crate `widget_lib` that depends on `serde`)
    /// and assert `render_sources_in_place` fills the `depgraph` marker in
    /// `.nornir/design.md` with that crate's name + dependency — proving the
    /// marker is populated on disk, NOT left empty. (This is the I1 regression
    /// guard: the design-doc depgraph used to render only inside the PDF book,
    /// leaving the source file's marker blank.)
    #[test]
    fn render_sources_in_place_fills_depgraph_marker() {
        let (t, l) = layout();
        let root = t.path();
        // A real (minimal) cargo crate so `cargo metadata` yields a known graph:
        // node `widget_lib`, edge widget_lib -.-> serde.
        std::fs::write(
            root.join("Cargo.toml"),
            "[package]\nname = \"widget_lib\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n\
             [dependencies]\nserde = \"1\"\n",
        )
        .unwrap();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/lib.rs"), "pub fn noop() {}\n").unwrap();

        // A design doc whose depgraph marker is EMPTY (the broken state).
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        let design = l.nornir_dir().join("design.md");
        std::fs::write(
            &design,
            "# Design\n\nintro\n\n\
             <!-- nornir:gen:start:depgraph -->\n<!-- nornir:gen:end:depgraph -->\n\noutro\n",
        )
        .unwrap();
        // Precondition: nothing between the markers yet.
        let before = std::fs::read_to_string(&design).unwrap();
        assert!(
            before.contains(
                "<!-- nornir:gen:start:depgraph -->\n<!-- nornir:gen:end:depgraph -->"
            ),
            "fixture should start with an empty depgraph marker"
        );

        // Inject-assert at the data layer the renderer reads: the extracted
        // graph carries the exact node + edge we set up.
        let g = crate::introspect::depgraph::extract(root).expect("extract graph");
        assert!(
            g.nodes.iter().any(|n| n == "widget_lib"),
            "extracted graph must contain the workspace crate; got {:?}",
            g.nodes
        );
        assert!(
            g.edges
                .iter()
                .any(|e| e.from == "widget_lib" && e.to == "serde"),
            "extracted graph must contain the widget_lib -> serde edge; got {:?}",
            g.edges
        );

        let ctx = Ctx::new(root, root, None);
        let reports = render_sources_in_place(&l, &ctx).expect("render in place");

        // It reported design.md and rewrote it.
        let r = reports
            .iter()
            .find(|r| r.path.ends_with("design.md"))
            .expect("design.md reported");
        assert!(r.changed, "design.md should have changed");
        assert_eq!(r.sections, vec!["depgraph".to_string()]);

        // The on-disk marker is now NON-empty.
        let after = std::fs::read_to_string(&design).unwrap();
        let start = after.find("nornir:gen:start:depgraph").unwrap();
        let end = after.find("nornir:gen:end:depgraph").unwrap();
        let body = after[start..end].trim();
        assert!(body.len() > 40, "depgraph body should be non-trivial: {body:?}");

        // The injected crate + dependency must be present in the *rendered*
        // graph. Two render backends:
        //   * docs-export: the marker is an image ref and the crate names live
        //     in the generated SVG asset (typst box labels).
        //   * default:     the marker holds the inline SVG graph (crate names
        //                  survive as literal <text> labels).
        #[cfg(feature = "docs-export")]
        {
            // design.md lives under `.nornir/`, so the link must be
            // doc-relative (`assets/depgraph.svg`), NOT the repo-root-relative
            // `.nornir/assets/...` (which a git host would 404 from inside
            // `.nornir/`).
            assert!(
                body.contains("![workspace dependency graph](assets/depgraph.svg)"),
                "depgraph link must be relative to the .nornir/ doc; got: {body}"
            );
            assert!(
                !body.contains(".nornir/assets/depgraph.svg"),
                "link must not be repo-root-relative inside .nornir/; got: {body}"
            );
            // typst renders label text as glyph-outline <path>s (no literal crate
            // strings survive), so we assert the SVG is a valid, non-trivial
            // rendering whose geometry reflects THIS graph: an empty graph
            // renders a much smaller SVG. This proves the marker is backed by a
            // real, populated render — not an empty placeholder.
            let svg = std::fs::read_to_string(root.join(".nornir/assets/depgraph.svg"))
                .expect("depgraph.svg written");
            assert!(svg.starts_with("<svg"), "asset must be an SVG");
            assert!(svg.contains("</svg>"));
            let empty_svg = crate::docs::svg::render_graph_svg(&crate::introspect::Graph::default())
                .expect("render empty");
            // Two boxes + an edge ⇒ strictly more drawing than an empty graph.
            assert!(
                svg.len() > empty_svg.len() + 200,
                "rendered SVG ({} bytes) should be larger than an empty-graph SVG ({} bytes)",
                svg.len(),
                empty_svg.len()
            );
            // One <path> group per drawn glyph/shape — a 2-node, 1-edge graph
            // draws many; an empty graph draws (near) none.
            assert!(
                svg.matches("<path").count() >= 10,
                "expected glyph/shape geometry for 2 labelled nodes; got {} <path>s",
                svg.matches("<path").count()
            );
        }
        #[cfg(not(feature = "docs-export"))]
        {
            assert!(
                body.contains("widget_lib"),
                "inline depgraph must name the workspace crate; got: {body}"
            );
            assert!(
                body.contains("serde"),
                "inline depgraph must show the injected dependency; got: {body}"
            );
        }

        // The surrounding prose is preserved.
        assert!(after.contains("# Design"));
        assert!(after.contains("outro"));
    }

    /// A `.nornir/*.md` source with no `nornir:gen` markers is left untouched
    /// (no churn) and not reported.
    #[test]
    fn render_sources_in_place_skips_markerless_files() {
        let (t, l) = layout();
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        let notes = l.nornir_dir().join("notes.md");
        let original = "# Notes\n\njust prose, no markers\n";
        std::fs::write(&notes, original).unwrap();

        let ctx = Ctx::new(t.path(), t.path(), None);
        let reports = render_sources_in_place(&l, &ctx).unwrap();

        assert!(reports.iter().all(|r| !r.path.ends_with("notes.md")));
        assert_eq!(std::fs::read_to_string(&notes).unwrap(), original);
    }

    /// Managed-doc *templates* (`.nornir/README.md`) are skipped by
    /// `render_sources_in_place` — their markers fill into the root output, not
    /// the source — so the template's empty markers are preserved.
    #[test]
    fn render_sources_in_place_skips_managed_templates() {
        let (t, l) = layout();
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        let readme_src = l.nornir_dir().join("README.md");
        let tpl =
            "# X\n\n<!-- nornir:gen:start:depgraph -->\n<!-- nornir:gen:end:depgraph -->\n";
        std::fs::write(&readme_src, tpl).unwrap();

        let ctx = Ctx::new(t.path(), t.path(), None);
        let reports = render_sources_in_place(&l, &ctx).unwrap();

        assert!(reports.iter().all(|r| !r.path.ends_with("README.md")));
        assert_eq!(std::fs::read_to_string(&readme_src).unwrap(), tpl);
    }

    #[test]
    fn init_migrates_existing_readme() {
        let (t, l) = layout();
        std::fs::write(t.path().join("README.md"), "# already here\n\nbody\n").unwrap();
        let srcs = init_repo(&l).unwrap();
        assert_eq!(srcs.len(), 1);
        let s = std::fs::read_to_string(&srcs[0]).unwrap();
        assert!(s.contains("# already here"));
    }

    #[test]
    fn init_strips_old_header_on_remigrate() {
        let (t, l) = layout();
        let body = "# x\n\nbody\n";
        let with_header = format!(
            "{}README.md{}{}",
            GENERATED_HEADER_PREFIX, GENERATED_HEADER_SUFFIX, body
        );
        std::fs::write(t.path().join("README.md"), &with_header).unwrap();
        init_repo(&l).unwrap();
        let s = std::fs::read_to_string(l.source_of("README.md")).unwrap();
        assert!(!s.contains("GENERATED"));
        assert!(s.starts_with("# x"));
    }

    #[test]
    fn render_writes_header_and_preserves_source() {
        let (t, l) = layout();
        let src = l.source_of("README.md");
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        std::fs::write(&src, "# title\n\nhello\n").unwrap();
        let ctx = Ctx::new(t.path(), t.path(), None);
        let r = render_doc(&l, "README.md", &ctx).unwrap().unwrap();
        assert!(r.changed);
        let out = std::fs::read_to_string(&r.output).unwrap();
        assert!(out.starts_with(GENERATED_HEADER_PREFIX));
        assert!(out.contains("# title"));
    }

    #[test]
    fn render_is_idempotent() {
        let (t, l) = layout();
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        std::fs::write(l.source_of("README.md"), "# x\n").unwrap();
        let ctx = Ctx::new(t.path(), t.path(), None);
        let r1 = render_doc(&l, "README.md", &ctx).unwrap().unwrap();
        assert!(r1.changed);
        let r2 = render_doc(&l, "README.md", &ctx).unwrap().unwrap();
        assert!(!r2.changed);
    }

    #[test]
    fn check_fails_on_drift() {
        let (t, l) = layout();
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        std::fs::write(l.source_of("README.md"), "# original\n").unwrap();
        let ctx = Ctx::new(t.path(), t.path(), None);
        render_doc(&l, "README.md", &ctx).unwrap();
        // Mutate source so the output is now stale.
        std::fs::write(l.source_of("README.md"), "# changed\n").unwrap();
        assert!(check_doc(&l, "README.md", &ctx).is_err());
    }

    #[test]
    fn render_respects_readonly_bit() {
        let (t, l) = layout();
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        std::fs::write(l.source_of("README.md"), "# v1\n").unwrap();
        let ctx = Ctx::new(t.path(), t.path(), None);
        render_doc(&l, "README.md", &ctx).unwrap();
        // Lock the output, then mutate source and re-render. write_atomic
        // should clear+restore the bit.
        let out = l.output_of("README.md");
        let mut p = std::fs::metadata(&out).unwrap().permissions();
        p.set_readonly(true);
        std::fs::set_permissions(&out, p).unwrap();
        std::fs::write(l.source_of("README.md"), "# v2\n").unwrap();
        render_doc(&l, "README.md", &ctx).unwrap();
        let new = std::fs::read_to_string(&out).unwrap();
        assert!(new.contains("# v2"));
        assert!(std::fs::metadata(&out).unwrap().permissions().readonly());
    }

    #[test]
    fn docs_render_cfg_defaults_to_markdown() {
        let (_t, l) = layout();
        let cfg = DocsRenderCfg::load(&l).unwrap();
        assert!(cfg.wants_markdown());
        assert!(!cfg.wants_pdf());
    }

    #[test]
    fn docs_render_cfg_pdf_only_skips_markdown() {
        let (_t, l) = layout();
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        std::fs::write(DocsRenderCfg::path(&l), "outputs = [\"pdf\"]\n").unwrap();
        let cfg = DocsRenderCfg::load(&l).unwrap();
        assert!(cfg.wants_pdf());
        assert!(!cfg.wants_markdown());
    }

    #[test]
    fn docs_render_cfg_all_wants_both() {
        let (_t, l) = layout();
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        std::fs::write(DocsRenderCfg::path(&l), "outputs = [\"all\"]\n").unwrap();
        let cfg = DocsRenderCfg::load(&l).unwrap();
        assert!(cfg.wants_pdf());
        assert!(cfg.wants_markdown());
    }
}