Skip to main content

spec_driven_docs/
embedded.rs

1//! Compile-time embedded assets: the payload and the method, in the binary.
2//!
3//! Every `include_dir!`/`include_str!` in the crate lives here, and each
4//! embeds from its canonical authored path, so the repository file and the
5//! shipped copy cannot diverge — the build reads the real thing. This module
6//! only holds bytes and typed accessors; deciding where an asset lands in an
7//! instance is the profiles' and installer's business.
8
9use std::collections::BTreeSet;
10
11use include_dir::{Dir, include_dir};
12
13pub use crate::payload_roots::PAYLOAD_ROOTS;
14
15/// The spec seeds an instance adopts, and the canon-only specs beside them.
16pub static SPECS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/_docs/specs");
17/// The stable document templates.
18pub static TEMPLATES: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/templates");
19/// The markdownlint configurations the instance receives managed.
20pub static MARKDOWNLINT: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/.markdownlint");
21/// Integration snippets a consumer copies into their own files.
22pub static SNIPPETS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/instance/snippets");
23/// The method chapters and glossary.
24pub static METHOD: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/method");
25/// The cross-agent skills, one `SKILL.md` per directory.
26pub static SKILLS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/skills");
27/// The artifacts every skill shares, installed once outside the skill roots.
28pub static SKILL_SHARED: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/skill-shared");
29
30/// The combined license statement naming both halves.
31pub static LICENSE: &str = include_str!("../LICENSE");
32/// The MIT license covering the distribution.
33pub static LICENSE_MIT: &str = include_str!("../LICENSE-MIT");
34/// The CC BY 4.0 license covering the method.
35pub static LICENSE_CC_BY: &str = include_str!("../LICENSE-CC-BY-4.0");
36/// The attribution notice for every third-party source the payload derives from.
37pub static THIRD_PARTY_NOTICES: &str = include_str!("../THIRD_PARTY_NOTICES.md");
38
39/// Every embedded root paired with the authored path it came from, in
40/// [`PAYLOAD_ROOTS`] order. A unit test holds the two equal, so a root
41/// embedded here but missing from the declaration — or the reverse — fails
42/// the build rather than shipping unscanned.
43const EMBEDDED_ROOTS: &[(&str, &Dir<'static>)] = &[
44    ("_docs/specs", &SPECS),
45    ("templates", &TEMPLATES),
46    (".markdownlint", &MARKDOWNLINT),
47    ("instance/snippets", &SNIPPETS),
48    ("method", &METHOD),
49    ("skills", &SKILLS),
50    ("skill-shared", &SKILL_SHARED),
51];
52
53/// Every skill name, sorted; a name is the skill's directory.
54#[must_use]
55pub fn skill_names() -> Vec<&'static str> {
56    let mut names: Vec<&'static str> = SKILLS
57        .dirs()
58        .filter_map(|dir| dir.path().as_os_str().to_str())
59        .collect();
60    names.sort_unstable();
61    names
62}
63
64/// One skill's `SKILL.md` text, by skill name.
65#[must_use]
66pub fn skill(name: &str) -> Option<&'static str> {
67    SKILLS
68        .get_file(format!("{name}/SKILL.md"))
69        .and_then(include_dir::File::contents_utf8)
70}
71
72/// Every artifact the skills share, as `(path under the root, bytes)`,
73/// sorted by path.
74///
75/// These land once, outside the agent skill roots, because every skill names
76/// the same absolute path for them. A copy per skill would be one file to
77/// correct per agent root per skill; one copy is one.
78#[must_use]
79pub fn shared_artifacts() -> Vec<(String, &'static [u8])> {
80    fn walk(dir: &Dir<'static>, out: &mut Vec<(String, &'static [u8])>) {
81        for file in dir.files() {
82            if let Some(path) = file.path().to_str() {
83                out.push((path.to_string(), file.contents()));
84            }
85        }
86        for sub in dir.dirs() {
87            walk(sub, out);
88        }
89    }
90    let mut out = Vec::new();
91    walk(&SKILL_SHARED, &mut out);
92    out.sort_by(|a, b| a.0.cmp(&b.0));
93    out
94}
95
96/// Resolve a payload source path — as a profile projection names it — to its
97/// embedded bytes.
98#[must_use]
99pub fn asset(source: &str) -> Option<&'static [u8]> {
100    EMBEDDED_ROOTS.iter().find_map(|(root, dir)| {
101        let rest = source.strip_prefix(root)?.strip_prefix('/')?;
102        dir.get_file(rest).map(include_dir::File::contents)
103    })
104}
105
106/// Every `` ### `domain:rule` `` requirement address the embedded specs define.
107#[must_use]
108pub fn spec_rule_ids() -> BTreeSet<String> {
109    let mut ids = BTreeSet::new();
110    for file in SPECS.files() {
111        let Some(text) = file.contents_utf8() else {
112            continue;
113        };
114        ids.extend(rule_ids_in(text));
115    }
116    ids
117}
118
119/// The requirement addresses one spec document defines.
120pub fn rule_ids_in(text: &str) -> impl Iterator<Item = String> + '_ {
121    text.lines().filter_map(|line| {
122        let candidate = line.strip_prefix("### `")?;
123        let (id, _) = candidate.split_once('`')?;
124        let (domain, rule) = id.split_once(':')?;
125        let is_slug = |part: &str| {
126            !part.is_empty()
127                && part
128                    .bytes()
129                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
130        };
131        (is_slug(domain) && is_slug(rule)).then(|| id.to_string())
132    })
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use crate::domain::profile::ProfileId;
139    use crate::domain::rule_id::RuleId;
140
141    #[test]
142    fn rule_id_enum_matches_the_embedded_specs() {
143        let from_specs = spec_rule_ids();
144        let from_enum: BTreeSet<String> = RuleId::ALL
145            .iter()
146            .map(|rule| rule.as_str().to_string())
147            .collect();
148        assert_eq!(
149            from_specs, from_enum,
150            "RuleId and the specs disagree; update the enum and the specs together"
151        );
152    }
153
154    #[test]
155    fn the_embedded_roots_are_the_declared_payload_roots() {
156        let embedded: Vec<&str> = EMBEDDED_ROOTS.iter().map(|(root, _)| *root).collect();
157        assert_eq!(
158            embedded,
159            PAYLOAD_ROOTS.to_vec(),
160            "payload_roots.rs and the embedded statics disagree; a root missing from the declaration ships unscanned"
161        );
162    }
163
164    #[test]
165    fn every_profile_projection_resolves_to_an_embedded_asset() {
166        for id in [ProfileId::Codebase, ProfileId::KnowledgeBase] {
167            let profile = id.profile();
168            for entry in profile.managed.iter().chain(profile.adopted) {
169                assert!(
170                    asset(entry.source).is_some(),
171                    "{id}: {} is not embedded",
172                    entry.source
173                );
174            }
175        }
176    }
177
178    #[test]
179    fn the_method_and_licenses_are_carried() {
180        assert!(METHOD.get_file("glossary.md").is_some());
181        assert!(METHOD.files().count() >= 15);
182        assert!(LICENSE.contains("LICENSE-MIT") && LICENSE.contains("LICENSE-CC-BY-4.0"));
183    }
184
185    #[test]
186    fn rule_id_parser_matches_heading_shape_only() {
187        let text = "### `a-b:c-d` — Title\n### `Bad:Id`\nplain ### `x:y`\n### `no-colon`\n";
188        let ids: Vec<String> = rule_ids_in(text).collect();
189        assert_eq!(ids, vec!["a-b:c-d".to_string()]);
190    }
191}