Skip to main content

spec_driven_docs/services/
assess.rs

1//! Classify a target repository before anything lands.
2//!
3//! The assessment is read-only evidence plus one classification computed
4//! from it by an explicit rule: `greenfield` when the project has written
5//! no durable documentation beyond root metadata, `brownfield` when a
6//! documentation root or a methodology marker shows a settled corpus, and
7//! `needs-decision` when documents sit outside any recognized home. The
8//! rule lives here so a routing skill reads a verdict it can cite instead
9//! of judging "little docs" by feel.
10
11use std::collections::BTreeMap;
12
13use camino::{Utf8Path, Utf8PathBuf};
14use serde::Serialize;
15
16use crate::domain::profile::{ProfileId, resolve_destination};
17use crate::error::AppError;
18use crate::gates::PRUNED_DIRS;
19use crate::services::status::{StatusReport, status};
20
21/// The directory names a documentation corpus conventionally lives under.
22const DOC_ROOTS: &[&str] = &["docs", "_docs", "doc", "documentation"];
23
24/// Root-level files and directories that mark an existing documentation
25/// methodology, whatever it is.
26const ROOT_MARKERS: &[&str] = &[
27    "specs",
28    "decisions",
29    "adr",
30    "adrs",
31    "mkdocs.yml",
32    "docusaurus.config.js",
33    "docusaurus.config.ts",
34    "conf.py",
35];
36
37/// Extensions a durable document conventionally carries.
38const DOC_EXTENSIONS: &[&str] = &["md", "markdown", "adoc", "rst", "org"];
39
40/// Root-level filename stems that are metadata, not a documentation corpus.
41const ROOT_METADATA: &[&str] = &[
42    "readme",
43    "license",
44    "licence",
45    "contributing",
46    "changelog",
47    "agents",
48    "claude",
49    "code_of_conduct",
50];
51
52/// What the target is, for routing.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
54#[serde(rename_all = "kebab-case")]
55pub enum Classification {
56    /// No durable documentation beyond root metadata: land an instance.
57    Greenfield,
58    /// A settled corpus or a methodology marker: migrate, not just land.
59    Brownfield,
60    /// Documents outside any recognized home: the operator decides.
61    NeedsDecision,
62}
63
64impl Classification {
65    /// The kebab-case verdict word, as the JSON serializes it.
66    #[must_use]
67    pub const fn as_str(self) -> &'static str {
68        match self {
69            Self::Greenfield => "greenfield",
70            Self::Brownfield => "brownfield",
71            Self::NeedsDecision => "needs-decision",
72        }
73    }
74}
75
76/// The document inventory the classification is computed from.
77#[derive(Debug, Serialize)]
78pub struct Documents {
79    /// How many document files the walk found.
80    pub count: usize,
81    /// Every document path, relative to the target, sorted.
82    pub paths: Vec<Utf8PathBuf>,
83}
84
85/// The whole assessment: evidence first, one verdict from it.
86#[derive(Debug, Serialize)]
87pub struct AssessReport {
88    /// The shape version of this document.
89    pub schema: &'static str,
90    /// The assessed repository.
91    pub target: Utf8PathBuf,
92    /// The verdict the evidence below produces.
93    pub classification: Classification,
94    /// The instance report, verbatim from `sdd status`.
95    pub instance: StatusReport,
96    /// Documentation roots found at the target's top level.
97    pub doc_roots: Vec<String>,
98    /// The documentation roots holding any entry at all — the evidence the
99    /// brownfield verdict reads, whatever format or link shape the entries
100    /// have.
101    pub populated_doc_roots: Vec<String>,
102    /// The document inventory.
103    pub documents: Documents,
104    /// Methodology markers found, as target-relative paths.
105    pub methodology_markers: Vec<String>,
106    /// Per profile, the install destinations that already exist.
107    pub collisions: BTreeMap<String, Vec<String>>,
108    /// Where the docs scratch resolved to. Relative to the target, unless
109    /// the declaration itself names a path outside it.
110    pub docs_scratch: Utf8PathBuf,
111    /// Whether that directory is there.
112    pub docs_scratch_present: bool,
113}
114
115/// The directory name a target with no instance and no variable is checked
116/// for. This is a discovery candidate, never the rule: the rule is the
117/// declared value, and this exists because a target being classified has
118/// declared nothing yet. `paths::docs_root` discovers the same way.
119const DOCS_SCRATCH_CANDIDATE: &str = ".docs-scratch";
120
121/// Where the target keeps material that is not a statement yet.
122///
123/// `named` is what the variable carries, supplied by the caller. The
124/// variable wins, then the instance record, then the candidate above.
125fn docs_scratch(target: &Utf8Path, named: Option<Utf8PathBuf>) -> Utf8PathBuf {
126    let ctx = crate::gates::GateCtx::new(target);
127    crate::gates::paths::docs_scratch_with(&ctx, named)
128        .unwrap_or_else(|| Utf8PathBuf::from(DOCS_SCRATCH_CANDIDATE))
129}
130
131/// The docs scratch the walk prunes, relative to `target`, where it sits
132/// inside it.
133pub(crate) fn scratch_within(target: &Utf8Path, named: Option<Utf8PathBuf>) -> Option<Utf8PathBuf> {
134    let scratch = normalized(&target.join(docs_scratch(target, named)));
135    scratch
136        .strip_prefix(normalized(target))
137        .ok()
138        .filter(|relative| !relative.as_str().is_empty())
139        .map(Utf8Path::to_path_buf)
140}
141
142/// Assess `target`, reading and never writing.
143///
144/// # Errors
145///
146/// [`AppError::Usage`] when the target exists and is not a directory,
147/// [`AppError::ManifestInvalid`] when an instance manifest exists but
148/// cannot be trusted — a broken instance must not silently classify — and
149/// [`AppError::Io`] for metadata failures and walk errors.
150pub fn assess(target: &Utf8Path) -> Result<AssessReport, AppError> {
151    assess_with(target, crate::gates::paths::docs_scratch_variable())
152}
153
154/// Assess `target` with the docs-scratch variable's value supplied.
155///
156/// The environment is read at one boundary and passed in, so every case is
157/// reachable from a test. This crate forbids unsafe code, and setting a
158/// variable is unsafe from the 2024 edition on, so a test that could not
159/// inject would read the developer's own shell instead.
160///
161/// # Errors
162///
163/// See [`assess`].
164pub fn assess_with(
165    target: &Utf8Path,
166    named: Option<Utf8PathBuf>,
167) -> Result<AssessReport, AppError> {
168    // A file target would walk as its own single entry and read as an
169    // empty repository; refuse it instead, on proven metadata only. An
170    // absent path falls through to the walk, whose I/O error names it,
171    // and a metadata failure is an I/O result, never a usage mistake.
172    match std::fs::metadata(target) {
173        Ok(metadata) if !metadata.is_dir() => {
174            return Err(AppError::Usage(format!(
175                "target is not a directory: {target}"
176            )));
177        }
178        Ok(_) => {}
179        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
180        Err(error) => return Err(AppError::Io(error)),
181    }
182    let instance = status(target)?;
183    let corpus = corpus(target, named)?;
184    let collisions = collisions(target, &crate::domain::profile::DECLARATION)?;
185    let docs_scratch_present = target.join(&corpus.scratch).is_dir();
186    let classification = corpus.verdict();
187    let paths = corpus.documents;
188
189    Ok(AssessReport {
190        schema: "sdd.assess/2",
191        target: target.to_owned(),
192        classification,
193        instance,
194        doc_roots: corpus.doc_roots,
195        populated_doc_roots: corpus.populated_doc_roots,
196        documents: Documents {
197            count: paths.len(),
198            paths,
199        },
200        methodology_markers: corpus.methodology_markers,
201        collisions,
202        docs_scratch: corpus.scratch,
203        docs_scratch_present,
204    })
205}
206
207/// The evidence the verdict reads, and nothing about the instance.
208pub(crate) struct CorpusEvidence {
209    /// Documentation roots found at the target's top level.
210    pub(crate) doc_roots: Vec<String>,
211    /// The documentation roots holding any entry at all.
212    pub(crate) populated_doc_roots: Vec<String>,
213    /// Every document path, relative to the target, sorted.
214    pub(crate) documents: Vec<Utf8PathBuf>,
215    /// Methodology markers found, as target-relative paths.
216    pub(crate) methodology_markers: Vec<String>,
217    /// Where the docs scratch resolved to.
218    pub(crate) scratch: Utf8PathBuf,
219}
220
221impl CorpusEvidence {
222    /// The one rule that turns the evidence into a verdict.
223    ///
224    /// A populated documentation root is a corpus whatever format it uses:
225    /// a tree of .adoc or .rst files under docs/ is exactly as settled as
226    /// one of markdown, and a verdict that missed it would land seeds
227    /// beside it. Documents beyond root metadata with no such home are the
228    /// operator's to place.
229    pub(crate) fn verdict(&self) -> Classification {
230        if !self.populated_doc_roots.is_empty() || !self.methodology_markers.is_empty() {
231            Classification::Brownfield
232        } else if self.documents.iter().any(|path| !is_root_metadata(path)) {
233            Classification::NeedsDecision
234        } else {
235            Classification::Greenfield
236        }
237    }
238}
239
240/// Read the corpus evidence of `target`, with the docs-scratch variable's
241/// value supplied.
242///
243/// # Errors
244///
245/// [`AppError::Io`] for metadata failures and walk errors.
246pub(crate) fn corpus(
247    target: &Utf8Path,
248    named: Option<Utf8PathBuf>,
249) -> Result<CorpusEvidence, AppError> {
250    // `is_dir` follows a link and reads false through a broken one, so a
251    // symlink is recognized on its own: a root the project points
252    // elsewhere is evidence whether or not the destination resolves.
253    let doc_roots: Vec<String> = DOC_ROOTS
254        .iter()
255        .filter(|root| {
256            let root = target.join(root);
257            root.is_dir() || root.is_symlink()
258        })
259        .map(|root| (*root).to_string())
260        .collect();
261    let scratch = docs_scratch(target, named);
262    let walked = walk(target, &scratch)?;
263    let methodology_markers = markers(target, &doc_roots)?;
264    // A root that is itself a symlink is evidence without being followed:
265    // the walk does not traverse links, so the link's presence is what
266    // there is to read.
267    let populated_doc_roots: Vec<String> = doc_roots
268        .iter()
269        .filter(|root| walked.populated_roots.contains(*root) || target.join(root).is_symlink())
270        .cloned()
271        .collect();
272    Ok(CorpusEvidence {
273        doc_roots,
274        populated_doc_roots,
275        documents: walked.documents,
276        methodology_markers,
277        scratch,
278    })
279}
280
281/// A path with `.` dropped and every resolvable `..` collapsed.
282///
283/// Lexical rather than `canonicalize`: a declared scratch that does not
284/// exist yet still has to compare equal to the walked entry once it does,
285/// and canonicalizing an absent path fails.
286fn normalized(path: &Utf8Path) -> Utf8PathBuf {
287    let mut out = Utf8PathBuf::new();
288    for component in path.components() {
289        match component {
290            camino::Utf8Component::CurDir => {}
291            camino::Utf8Component::ParentDir => {
292                if matches!(
293                    out.components().next_back(),
294                    Some(camino::Utf8Component::Normal(_))
295                ) {
296                    out.pop();
297                } else {
298                    out.push("..");
299                }
300            }
301            other => out.push(other.as_str()),
302        }
303    }
304    out
305}
306
307/// What one walk over the target observed.
308struct Walked {
309    /// Every document file, relative to the target, sorted.
310    documents: Vec<Utf8PathBuf>,
311    /// The top-level directory names holding any entry at all.
312    populated_roots: Vec<String>,
313}
314
315/// Walk `target` once, with the pruned directories, the docs scratch, and
316/// the instance's own tree skipped. Symlinks are evidence and are not
317/// followed: a link named like a document still marks its directory as
318/// populated.
319///
320/// The docs scratch is skipped by path rather than by name, so a scratch
321/// that sits beside the checkout prunes nothing and a scratch inside it
322/// prunes only itself. Without that, staged rewrites would come back as
323/// documents to migrate on the next run.
324fn walk(target: &Utf8Path, scratch: &Utf8Path) -> Result<Walked, AppError> {
325    let mut documents = Vec::new();
326    let mut populated_roots = Vec::new();
327    // The comparison is lexical, so both sides are normalized first. A
328    // variable carries whatever the operator's shell holds, and `a/../a`
329    // names the same directory as `a` while comparing unequal. Reported
330    // present and then not pruned is the worst of both answers.
331    let scratch_path = normalized(&target.join(scratch));
332    let walker = walkdir::WalkDir::new(target).into_iter().filter_entry(|e| {
333        let name = e.file_name().to_string_lossy();
334        !(e.depth() > 0
335            && e.file_type().is_dir()
336            && (PRUNED_DIRS.contains(&name.as_ref())
337                || name == crate::domain::paths::INSTANCE_DIR
338                || e.path()
339                    .to_str()
340                    .is_some_and(|path| normalized(Utf8Path::new(path)) == scratch_path)))
341    });
342    for entry in walker {
343        let entry = entry.map_err(|source| AppError::Io(std::io::Error::from(source)))?;
344        if entry.file_type().is_dir() {
345            continue;
346        }
347        let Some(path) = entry.path().to_str() else {
348            continue;
349        };
350        let relative = Utf8Path::new(path)
351            .strip_prefix(target)
352            .unwrap_or_else(|_| Utf8Path::new(path));
353        if let Some(root) = relative.components().next() {
354            let root = root.as_str().to_string();
355            if relative.components().nth(1).is_some() && !populated_roots.contains(&root) {
356                populated_roots.push(root);
357            }
358        }
359        if entry.file_type().is_file()
360            && relative.extension().is_some_and(|extension| {
361                DOC_EXTENSIONS
362                    .iter()
363                    .any(|known| extension.eq_ignore_ascii_case(known))
364            })
365        {
366            documents.push(relative.to_owned());
367        }
368    }
369    documents.sort();
370    Ok(Walked {
371        documents,
372        populated_roots,
373    })
374}
375
376/// Whether `path` is root-level project metadata rather than a corpus.
377pub(crate) fn is_root_metadata(path: &Utf8Path) -> bool {
378    if path
379        .parent()
380        .is_some_and(|parent| !parent.as_str().is_empty())
381    {
382        return false;
383    }
384    let Some(stem) = path.file_stem() else {
385        return false;
386    };
387    let stem = stem.to_ascii_lowercase();
388    // Exact stems only: `README.architecture.md` is a document wearing a
389    // metadata prefix, and an allowlist that took every dotted suffix
390    // would classify it away.
391    ROOT_METADATA.iter().any(|metadata| stem == *metadata)
392}
393
394/// Whether a repository-relative path is a document the walk would count:
395/// a file with a document extension, under no pruned directory and outside
396/// the instance's own tree.
397pub(crate) fn is_document_path(path: &Utf8Path) -> bool {
398    let pruned = path.parent().is_some_and(|parent| {
399        parent.components().any(|part| {
400            PRUNED_DIRS.contains(&part.as_str())
401                || part.as_str() == crate::domain::paths::INSTANCE_DIR
402        })
403    });
404    !pruned
405        && path.extension().is_some_and(|extension| {
406            DOC_EXTENSIONS
407                .iter()
408                .any(|known| extension.eq_ignore_ascii_case(known))
409        })
410}
411
412/// Whether an entry sits at `path`, broken symlinks included.
413///
414/// `symlink_metadata` rather than `exists`: a broken symlink named
415/// `mkdocs.yml` is still the project saying it documents itself there.
416/// Absence is the only failure that reads as absence; any other metadata
417/// error propagates, because evidence that cannot be read must never
418/// count as evidence that is not there.
419fn entry_present(path: &Utf8Path) -> Result<bool, AppError> {
420    match path.symlink_metadata() {
421        Ok(_) => Ok(true),
422        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
423        Err(error) => Err(AppError::Io(error)),
424    }
425}
426
427/// The methodology markers present: root markers, and the conventional
428/// zone directories under each detected documentation root.
429fn markers(target: &Utf8Path, doc_roots: &[String]) -> Result<Vec<String>, AppError> {
430    let mut found = Vec::new();
431    for marker in ROOT_MARKERS {
432        if entry_present(&target.join(marker))? {
433            found.push((*marker).to_string());
434        }
435    }
436    for root in doc_roots {
437        for zone in ["specs", "decisions", "adr", "adrs", "conf.py"] {
438            let candidate = format!("{root}/{zone}");
439            if entry_present(&target.join(&candidate))? {
440                found.push(candidate);
441            }
442        }
443    }
444    Ok(found)
445}
446
447/// Per profile, the install destinations already present at the target.
448fn collisions(
449    target: &Utf8Path,
450    released: &crate::domain::projection::Declaration,
451) -> Result<BTreeMap<String, Vec<String>>, AppError> {
452    let mut collisions = BTreeMap::new();
453    for id in ProfileId::every() {
454        let Some(profile) = released.profile(id) else {
455            continue;
456        };
457        let mut existing = Vec::new();
458        for projection in profile.managed.iter().chain(profile.adopted) {
459            let destination = resolve_destination(&projection.destination, profile.docs_root);
460            if entry_present(&target.join(&destination))? {
461                existing.push(destination.to_string());
462            }
463        }
464        collisions.insert(id.as_str().to_string(), existing);
465    }
466    Ok(collisions)
467}
468
469#[cfg(test)]
470mod tests {
471    #![allow(
472        clippy::unwrap_used,
473        reason = "a test panics as its failure signal, not as control flow"
474    )]
475
476    use super::*;
477
478    fn utf8(dir: &tempfile::TempDir) -> Utf8PathBuf {
479        Utf8PathBuf::from(dir.path().to_str().unwrap())
480    }
481
482    fn write(root: &Utf8Path, relative: &str) {
483        let path = root.join(relative);
484        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
485        std::fs::write(path, "content\n").unwrap();
486    }
487
488    #[test]
489    fn root_metadata_is_recognized_case_insensitively_and_only_at_root() {
490        assert!(is_root_metadata(Utf8Path::new("README.md")));
491        assert!(is_root_metadata(Utf8Path::new("readme.md")));
492        assert!(is_root_metadata(Utf8Path::new("code_of_conduct.md")));
493        assert!(is_root_metadata(Utf8Path::new("CONTRIBUTING.md")));
494        assert!(is_root_metadata(Utf8Path::new("AGENTS.md")));
495        assert!(!is_root_metadata(Utf8Path::new("notes.md")));
496        assert!(!is_root_metadata(Utf8Path::new("sub/README.md")));
497    }
498
499    #[test]
500    fn an_empty_target_classifies_greenfield() {
501        let dir = tempfile::tempdir().unwrap();
502        let root = utf8(&dir);
503        write(&root, "README.md");
504        write(&root, "CHANGELOG.md");
505        let report = assess_with(&root, None).unwrap();
506        assert_eq!(report.classification, Classification::Greenfield);
507        assert_eq!(report.documents.count, 2);
508    }
509
510    /// A populated documentation root is a corpus whatever format it uses.
511    #[test]
512    fn a_non_markdown_corpus_under_a_doc_root_classifies_brownfield() {
513        let dir = tempfile::tempdir().unwrap();
514        let root = utf8(&dir);
515        write(&root, "docs/guide.adoc");
516        let report = assess_with(&root, None).unwrap();
517        assert_eq!(report.classification, Classification::Brownfield);
518    }
519
520    /// A symlink named like a document marks its root populated without
521    /// being followed.
522    #[test]
523    fn a_symlinked_document_under_a_doc_root_classifies_brownfield() {
524        let dir = tempfile::tempdir().unwrap();
525        let root = utf8(&dir);
526        write(&root, "elsewhere.md");
527        std::fs::create_dir_all(root.join("docs")).unwrap();
528        std::os::unix::fs::symlink(root.join("elsewhere.md"), root.join("docs/architecture.md"))
529            .unwrap();
530        let report = assess_with(&root, None).unwrap();
531        assert_eq!(report.classification, Classification::Brownfield);
532        assert_eq!(report.populated_doc_roots, vec!["docs".to_string()]);
533    }
534
535    /// A broken documentation-root symlink is still a root, and still
536    /// populated: the project pointed its docs somewhere, and where does
537    /// not matter to the verdict.
538    #[test]
539    fn a_broken_doc_root_symlink_classifies_brownfield() {
540        let dir = tempfile::tempdir().unwrap();
541        let root = utf8(&dir);
542        std::os::unix::fs::symlink(root.join("no-such-corpus"), root.join("docs")).unwrap();
543        let report = assess_with(&root, None).unwrap();
544        assert_eq!(report.doc_roots, vec!["docs".to_string()]);
545        assert_eq!(report.populated_doc_roots, vec!["docs".to_string()]);
546        assert_eq!(report.classification, Classification::Brownfield);
547    }
548
549    /// A broken marker symlink still marks: the project pointed its
550    /// configuration somewhere, and where does not matter to the verdict.
551    #[test]
552    fn a_broken_marker_symlink_still_classifies_brownfield() {
553        let dir = tempfile::tempdir().unwrap();
554        let root = utf8(&dir);
555        std::os::unix::fs::symlink(root.join("no-such-config"), root.join("mkdocs.yml")).unwrap();
556        let report = assess_with(&root, None).unwrap();
557        assert_eq!(report.methodology_markers, vec!["mkdocs.yml".to_string()]);
558        assert_eq!(report.classification, Classification::Brownfield);
559    }
560
561    /// A broken symlink at a projected destination is a collision: the
562    /// path is occupied whatever it points at.
563    #[test]
564    fn a_broken_destination_symlink_reads_as_a_collision() {
565        let dir = tempfile::tempdir().unwrap();
566        let root = utf8(&dir);
567        std::fs::create_dir_all(root.join("docs/specs")).unwrap();
568        std::os::unix::fs::symlink(
569            root.join("gone.md"),
570            root.join("docs/specs/SPEC-docs-format.md"),
571        )
572        .unwrap();
573        let report = assess_with(&root, None).unwrap();
574        assert!(
575            report.collisions["codebase"]
576                .iter()
577                .any(|path| path == "docs/specs/SPEC-docs-format.md")
578        );
579    }
580
581    /// Evidence that cannot be read is an error, never absence: the
582    /// helper itself is exercised, because a whole-assess call would trip
583    /// over the walk before the marker probe runs.
584    #[test]
585    fn an_unreadable_entry_propagates_as_io_rather_than_absence() {
586        use std::os::unix::fs::PermissionsExt;
587        let dir = tempfile::tempdir().unwrap();
588        let root = utf8(&dir);
589        std::fs::create_dir_all(root.join("locked")).unwrap();
590        std::fs::write(root.join("locked/mkdocs.yml"), "site_name: x\n").unwrap();
591        std::fs::set_permissions(root.join("locked"), std::fs::Permissions::from_mode(0o000))
592            .unwrap();
593        let result = entry_present(&root.join("locked/mkdocs.yml"));
594        std::fs::set_permissions(root.join("locked"), std::fs::Permissions::from_mode(0o755))
595            .unwrap();
596        if nix_is_root() {
597            // Mode 000 stays readable to a privileged runner; the case
598            // this test constructs does not exist there.
599            return;
600        }
601        match result {
602            Err(AppError::Io(_)) => {}
603            other => panic!("expected an I/O error, got {other:?}"),
604        }
605    }
606
607    /// Whether the suite runs privileged, where mode 000 stays readable.
608    fn nix_is_root() -> bool {
609        std::fs::read_dir("/root").is_ok()
610    }
611
612    /// A file target is a usage error, not an empty repository.
613    #[test]
614    fn a_file_target_refuses_instead_of_classifying() {
615        let dir = tempfile::tempdir().unwrap();
616        let root = utf8(&dir);
617        write(&root, "just-a-file.md");
618        let error = assess_with(&root.join("just-a-file.md"), None).unwrap_err();
619        assert!(matches!(error, AppError::Usage(_)), "{error}");
620    }
621
622    /// A documentation root that is itself a symlink is evidence without
623    /// being followed.
624    #[test]
625    fn a_symlinked_doc_root_classifies_brownfield() {
626        let dir = tempfile::tempdir().unwrap();
627        let root = utf8(&dir);
628        std::fs::create_dir_all(root.join("external-corpus")).unwrap();
629        std::fs::write(root.join("external-corpus/guide.txt"), "prose\n").unwrap();
630        std::os::unix::fs::symlink(root.join("external-corpus"), root.join("docs")).unwrap();
631        let report = assess_with(&root, None).unwrap();
632        assert_eq!(report.classification, Classification::Brownfield);
633        assert_eq!(report.populated_doc_roots, vec!["docs".to_string()]);
634    }
635
636    /// The allowlist takes exact stems only.
637    #[test]
638    fn a_dotted_metadata_prefix_is_not_metadata() {
639        assert!(!is_root_metadata(Utf8Path::new("README.architecture.md")));
640        let dir = tempfile::tempdir().unwrap();
641        let root = utf8(&dir);
642        write(&root, "README.architecture.md");
643        let report = assess_with(&root, None).unwrap();
644        assert_eq!(report.classification, Classification::NeedsDecision);
645    }
646
647    #[test]
648    fn a_corpus_under_a_doc_root_classifies_brownfield() {
649        let dir = tempfile::tempdir().unwrap();
650        let root = utf8(&dir);
651        write(&root, "docs/architecture.md");
652        let report = assess_with(&root, None).unwrap();
653        assert_eq!(report.classification, Classification::Brownfield);
654        assert_eq!(report.doc_roots, vec!["docs".to_string()]);
655        assert_eq!(
656            report.documents.paths,
657            vec![Utf8PathBuf::from("docs/architecture.md")]
658        );
659    }
660
661    #[test]
662    fn a_methodology_marker_alone_classifies_brownfield() {
663        let dir = tempfile::tempdir().unwrap();
664        let root = utf8(&dir);
665        write(&root, "README.md");
666        write(&root, "mkdocs.yml");
667        let report = assess_with(&root, None).unwrap();
668        assert_eq!(report.classification, Classification::Brownfield);
669        assert_eq!(report.methodology_markers, vec!["mkdocs.yml".to_string()]);
670    }
671
672    #[test]
673    fn scattered_markdown_classifies_needs_decision() {
674        let dir = tempfile::tempdir().unwrap();
675        let root = utf8(&dir);
676        write(&root, "notes/design.md");
677        let report = assess_with(&root, None).unwrap();
678        assert_eq!(report.classification, Classification::NeedsDecision);
679    }
680
681    #[test]
682    fn the_docs_scratch_and_pruned_directories_stay_out_of_the_inventory() {
683        let dir = tempfile::tempdir().unwrap();
684        let root = utf8(&dir);
685        write(&root, ".docs-scratch/notes.md");
686        write(&root, "target/build.md");
687        write(&root, "node_modules/pkg/README.md");
688        let report = assess_with(&root, None).unwrap();
689        assert_eq!(report.classification, Classification::Greenfield);
690        assert_eq!(report.documents.count, 0);
691        assert!(report.docs_scratch_present);
692        assert_eq!(report.docs_scratch, DOCS_SCRATCH_CANDIDATE);
693    }
694
695    /// The walk prunes the scratch the project declared, wherever that is,
696    /// and the discovery candidate stops applying once one is declared.
697    #[test]
698    fn the_walk_prunes_the_declared_scratch_and_nothing_else() {
699        let dir = tempfile::tempdir().unwrap();
700        let root = utf8(&dir);
701        write(&root, "staging/rewrite.md");
702        write(&root, ".docs-scratch/notes.md");
703        let walked = walk(&root, Utf8Path::new("staging")).unwrap();
704        assert_eq!(
705            walked.documents,
706            vec![Utf8PathBuf::from(".docs-scratch/notes.md")]
707        );
708    }
709
710    /// A scratch beside the checkout prunes nothing inside it.
711    #[test]
712    fn a_docs_scratch_outside_the_target_prunes_nothing() {
713        let dir = tempfile::tempdir().unwrap();
714        let root = utf8(&dir);
715        write(&root, "notes/design.md");
716        write(&root, ".docs-scratch/kept.md");
717        let walked = walk(&root, Utf8Path::new("../beside")).unwrap();
718        assert_eq!(walked.documents.len(), 2);
719    }
720}