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
37/// Every embedded root paired with the authored path it came from, in
38/// [`PAYLOAD_ROOTS`] order. A unit test holds the two equal, so a root
39/// embedded here but missing from the declaration — or the reverse — fails
40/// the build rather than shipping unscanned.
41const EMBEDDED_ROOTS: &[(&str, &Dir<'static>)] = &[
42    ("_docs/specs", &SPECS),
43    ("templates", &TEMPLATES),
44    (".markdownlint", &MARKDOWNLINT),
45    ("instance/snippets", &SNIPPETS),
46    ("method", &METHOD),
47    ("skills", &SKILLS),
48    ("skill-shared", &SKILL_SHARED),
49];
50
51/// Every skill name, sorted; a name is the skill's directory.
52#[must_use]
53pub fn skill_names() -> Vec<&'static str> {
54    let mut names: Vec<&'static str> = SKILLS
55        .dirs()
56        .filter_map(|dir| dir.path().as_os_str().to_str())
57        .collect();
58    names.sort_unstable();
59    names
60}
61
62/// One skill's `SKILL.md` text, by skill name.
63#[must_use]
64pub fn skill(name: &str) -> Option<&'static str> {
65    SKILLS
66        .get_file(format!("{name}/SKILL.md"))
67        .and_then(include_dir::File::contents_utf8)
68}
69
70/// Every artifact the skills share, as `(path under the root, bytes)`,
71/// sorted by path.
72///
73/// These land once, outside the agent skill roots, because every skill names
74/// the same absolute path for them. A copy per skill would be one file to
75/// correct per agent root per skill; one copy is one.
76#[must_use]
77pub fn shared_artifacts() -> Vec<(String, &'static [u8])> {
78    fn walk(dir: &Dir<'static>, out: &mut Vec<(String, &'static [u8])>) {
79        for file in dir.files() {
80            if let Some(path) = file.path().to_str() {
81                out.push((path.to_string(), file.contents()));
82            }
83        }
84        for sub in dir.dirs() {
85            walk(sub, out);
86        }
87    }
88    let mut out = Vec::new();
89    walk(&SKILL_SHARED, &mut out);
90    out.sort_by(|a, b| a.0.cmp(&b.0));
91    out
92}
93
94/// Resolve a payload source path — as a profile projection names it — to its
95/// embedded bytes.
96#[must_use]
97pub fn asset(source: &str) -> Option<&'static [u8]> {
98    EMBEDDED_ROOTS.iter().find_map(|(root, dir)| {
99        let rest = source.strip_prefix(root)?.strip_prefix('/')?;
100        dir.get_file(rest).map(include_dir::File::contents)
101    })
102}
103
104/// Every `` ### `domain:rule` `` requirement address the embedded specs define.
105#[must_use]
106pub fn spec_rule_ids() -> BTreeSet<String> {
107    let mut ids = BTreeSet::new();
108    for file in SPECS.files() {
109        let Some(text) = file.contents_utf8() else {
110            continue;
111        };
112        ids.extend(rule_ids_in(text));
113    }
114    ids
115}
116
117/// The requirement addresses one spec document defines.
118pub fn rule_ids_in(text: &str) -> impl Iterator<Item = String> + '_ {
119    text.lines().filter_map(|line| {
120        let candidate = line.strip_prefix("### `")?;
121        let (id, _) = candidate.split_once('`')?;
122        let (domain, rule) = id.split_once(':')?;
123        let is_slug = |part: &str| {
124            !part.is_empty()
125                && part
126                    .bytes()
127                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
128        };
129        (is_slug(domain) && is_slug(rule)).then(|| id.to_string())
130    })
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use crate::domain::profile::ProfileId;
137    use crate::domain::rule_id::RuleId;
138
139    #[test]
140    fn rule_id_enum_matches_the_embedded_specs() {
141        let from_specs = spec_rule_ids();
142        let from_enum: BTreeSet<String> = RuleId::ALL
143            .iter()
144            .map(|rule| rule.as_str().to_string())
145            .collect();
146        assert_eq!(
147            from_specs, from_enum,
148            "RuleId and the specs disagree; update the enum and the specs together"
149        );
150    }
151
152    #[test]
153    fn the_embedded_roots_are_the_declared_payload_roots() {
154        let embedded: Vec<&str> = EMBEDDED_ROOTS.iter().map(|(root, _)| *root).collect();
155        assert_eq!(
156            embedded,
157            PAYLOAD_ROOTS.to_vec(),
158            "payload_roots.rs and the embedded statics disagree; a root missing from the declaration ships unscanned"
159        );
160    }
161
162    #[test]
163    fn every_profile_projection_resolves_to_an_embedded_asset() {
164        for id in [ProfileId::Codebase, ProfileId::KnowledgeBase] {
165            let profile = id.profile();
166            for entry in profile.managed.iter().chain(profile.adopted) {
167                assert!(
168                    asset(entry.source).is_some(),
169                    "{id}: {} is not embedded",
170                    entry.source
171                );
172            }
173        }
174    }
175
176    #[test]
177    fn the_method_and_licenses_are_carried() {
178        assert!(METHOD.get_file("glossary.md").is_some());
179        assert!(METHOD.files().count() >= 15);
180        assert!(LICENSE.contains("LICENSE-MIT") && LICENSE.contains("LICENSE-CC-BY-4.0"));
181    }
182
183    #[test]
184    fn rule_id_parser_matches_heading_shape_only() {
185        let text = "### `a-b:c-d` — Title\n### `Bad:Id`\nplain ### `x:y`\n### `no-colon`\n";
186        let ids: Vec<String> = rule_ids_in(text).collect();
187        assert_eq!(ids, vec!["a-b:c-d".to_string()]);
188    }
189}