Skip to main content

spec_driven_docs/domain/
profile.rs

1//! Installation profiles: what a target repository receives.
2//!
3//! A profile declares the documentation root and the payload projection —
4//! which payload files land managed and which land adopted, and where.
5//! The declaration is data the release carries, so an engine can read what
6//! any release it can fetch lands rather than only what it was compiled
7//! with. Copying bytes and recording hashes is the installer's work.
8
9use std::fmt;
10use std::sync::LazyLock;
11
12use camino::Utf8PathBuf;
13use clap::ValueEnum;
14use serde::{Deserialize, Serialize};
15
16pub use crate::domain::projection::Projection;
17use crate::domain::projection::{DECLARATION_PATH, Declaration};
18
19/// The two installable profiles.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, ValueEnum, Serialize, Deserialize)]
21#[value(rename_all = "kebab-case")]
22#[serde(rename_all = "kebab-case")]
23pub enum ProfileId {
24    /// A codebase whose records live under `docs/`.
25    Codebase,
26    /// A knowledge base whose records live under `_docs/`.
27    KnowledgeBase,
28}
29
30/// Every profile, in declaration order.
31pub const EVERY_PROFILE: [ProfileId; 2] = [ProfileId::Codebase, ProfileId::KnowledgeBase];
32
33impl ProfileId {
34    /// Every profile, in declaration order.
35    pub fn every() -> impl Iterator<Item = Self> {
36        EVERY_PROFILE.into_iter()
37    }
38
39    /// This binary's own release, as this profile.
40    ///
41    /// A verb that lands another release reads that release's declaration
42    /// instead, through [`crate::domain::projection::Declaration::profile`].
43    #[must_use]
44    pub fn profile(self) -> &'static Profile<'static> {
45        match self {
46            Self::Codebase => &CODEBASE,
47            Self::KnowledgeBase => &KNOWLEDGE_BASE,
48        }
49    }
50
51    /// The kebab-case name used on the command line and in the manifest.
52    #[must_use]
53    pub const fn as_str(self) -> &'static str {
54        match self {
55            Self::Codebase => "codebase",
56            Self::KnowledgeBase => "knowledge-base",
57        }
58    }
59}
60
61impl fmt::Display for ProfileId {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        f.write_str(self.as_str())
64    }
65}
66
67/// Where an instance keeps the documents the gates read.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
69pub enum DocsRoot {
70    /// `docs/` — the codebase convention.
71    #[serde(rename = "docs")]
72    Docs,
73    /// `_docs/` — the knowledge-base convention.
74    #[serde(rename = "_docs")]
75    UnderscoreDocs,
76}
77
78impl DocsRoot {
79    /// The directory name.
80    #[must_use]
81    pub const fn as_str(self) -> &'static str {
82        match self {
83            Self::Docs => "docs",
84            Self::UnderscoreDocs => "_docs",
85        }
86    }
87}
88
89impl fmt::Display for DocsRoot {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.write_str(self.as_str())
92    }
93}
94
95/// The placeholder that names the instance's documentation root.
96///
97/// A destination template, an adopted seed, a wiring pattern, and the
98/// `AGENTS.md` snippet all name the root by it, and [`render_root`] is the
99/// one place that substitutes it.
100#[allow(
101    clippy::literal_string_with_formatting_args,
102    reason = "the braces are the template placeholder, not a formatting argument"
103)]
104pub const DOCS_ROOT_PLACEHOLDER: &str = "{docs_root}";
105
106/// Substitute the documentation root for every placeholder in `text`.
107#[must_use]
108pub fn render_root(text: &str, docs_root: &str) -> String {
109    text.replace(DOCS_ROOT_PLACEHOLDER, docs_root)
110}
111
112/// Substitute the profile's documentation root into a destination template.
113#[must_use]
114pub fn resolve_destination(destination: &str, docs_root: DocsRoot) -> Utf8PathBuf {
115    Utf8PathBuf::from(render_root(destination, docs_root.as_str()))
116}
117
118/// What one profile installs, as one declaration describes it.
119#[derive(Debug, Clone, Copy)]
120pub struct Profile<'a> {
121    /// The profile this view belongs to.
122    pub id: ProfileId,
123    /// The documentation root the instance uses.
124    pub docs_root: DocsRoot,
125    /// Byte projections the canon keeps owning.
126    pub managed: &'a [Projection],
127    /// Seeds the instance owns from the moment they land.
128    pub adopted: &'a [Projection],
129}
130
131/// What this binary's own release declares.
132///
133/// The bytes are embedded, so a declaration that does not parse is a defect
134/// in the build rather than a state a command can meet. The canon suite
135/// parses the same file, so the failure lands in the test run.
136#[expect(
137    clippy::expect_used,
138    reason = "the declaration is compiled in; a parse failure is a build defect the canon suite catches first"
139)]
140pub static DECLARATION: LazyLock<Declaration> = LazyLock::new(|| {
141    let bytes = crate::embedded::asset(DECLARATION_PATH)
142        .expect("the payload carries instance/projection.toml");
143    Declaration::parse(bytes).expect("the embedded projection declaration parses")
144});
145
146static CODEBASE: LazyLock<Profile<'static>> = LazyLock::new(|| profile_of(ProfileId::Codebase));
147static KNOWLEDGE_BASE: LazyLock<Profile<'static>> =
148    LazyLock::new(|| profile_of(ProfileId::KnowledgeBase));
149
150/// One profile of this binary's own release.
151#[expect(
152    clippy::expect_used,
153    reason = "a profile the declaration omits is the same build defect as a declaration that does not parse"
154)]
155fn profile_of(id: ProfileId) -> Profile<'static> {
156    DECLARATION
157        .profile(id)
158        .expect("the embedded declaration offers every profile")
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    #[test]
166    fn profiles_bind_their_roots() {
167        assert_eq!(ProfileId::Codebase.profile().docs_root, DocsRoot::Docs);
168        assert_eq!(
169            ProfileId::KnowledgeBase.profile().docs_root,
170            DocsRoot::UnderscoreDocs
171        );
172    }
173
174    #[test]
175    fn destinations_resolve_per_root() {
176        assert_eq!(
177            resolve_destination("{docs_root}/specs/SPEC-distribution.md", DocsRoot::Docs),
178            Utf8PathBuf::from("docs/specs/SPEC-distribution.md")
179        );
180        assert_eq!(
181            resolve_destination(".spec-driven-docs/config.yaml", DocsRoot::UnderscoreDocs),
182            Utf8PathBuf::from(".spec-driven-docs/config.yaml")
183        );
184    }
185
186    #[test]
187    fn rendering_replaces_every_placeholder_and_nothing_else() {
188        assert_eq!(
189            render_root(
190                "see {docs_root}/specs/ and {docs_root}/guides/, not {writing_style} or {docs}",
191                "docs"
192            ),
193            "see docs/specs/ and docs/guides/, not {writing_style} or {docs}"
194        );
195        assert_eq!(render_root("no placeholder", "_docs"), "no placeholder");
196    }
197
198    #[test]
199    fn serde_uses_the_kebab_names() {
200        assert_eq!(
201            serde_json::to_string(&ProfileId::KnowledgeBase).unwrap(),
202            "\"knowledge-base\""
203        );
204        assert_eq!(
205            serde_json::to_string(&DocsRoot::UnderscoreDocs).unwrap(),
206            "\"_docs\""
207        );
208    }
209
210    #[test]
211    fn every_destination_lies_under_the_instance_or_the_documentation_root() {
212        let profile = ProfileId::KnowledgeBase.profile();
213        for entry in profile.managed {
214            assert!(
215                entry
216                    .destination
217                    .starts_with(&format!("{DOCS_ROOT_PLACEHOLDER}/"))
218                    || entry
219                        .destination
220                        .starts_with(&format!("{}/", crate::domain::paths::INSTANCE_DIR)),
221                "{} is neither under the instance directory nor rooted at the documentation root",
222                entry.destination
223            );
224        }
225        for entry in profile.adopted {
226            // The declaration and the root lint seed are the adopted files
227            // outside the corpus: they configure tools rather than being
228            // documentation, so no documentation root names them.
229            if entry.destination == crate::domain::paths::CONFIG_PATH || entry.yield_set().is_some()
230            {
231                continue;
232            }
233            assert!(
234                entry.destination.starts_with("{docs_root}/"),
235                "{} is not rooted",
236                entry.destination
237            );
238        }
239    }
240}