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 documentation root's lint configuration, which an instance receives
20/// managed.
21pub static MARKDOWNLINT: &[u8] = include_bytes!("../_docs/.markdownlint-cli2.jsonc");
22/// What a release says about itself, plus what it seeds and splices.
23///
24/// One root rather than a root per subdirectory: the projection
25/// declaration sits beside the seeds it describes, and a root per
26/// subdirectory would make the declaration a one-file exception to the
27/// payload inventory.
28pub static INSTANCE: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/instance");
29/// The method chapters and glossary.
30pub static METHOD: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/method");
31/// The cross-agent skills, one `SKILL.md` per directory.
32pub static SKILLS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/skills");
33/// The artifacts every skill shares, installed once outside the skill roots.
34pub static SKILL_SHARED: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/skill-shared");
35/// The comparison documents, which a stage carries as reference material.
36pub static COMPARISON_DOCS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/comparison-docs");
37/// The prior-art shelf, which a stage carries as reference material.
38pub static PRIOR_ART: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/reference/prior-art");
39/// The tracker-markup shelf, which the format chapter routes a reader to.
40pub static TRACKER_MARKUP: Dir<'static> =
41    include_dir!("$CARGO_MANIFEST_DIR/reference/tracker-markup");
42
43/// The combined license statement naming both halves.
44pub static LICENSE: &str = include_str!("../LICENSE");
45/// The MIT license covering the distribution.
46pub static LICENSE_MIT: &str = include_str!("../LICENSE-MIT");
47/// The CC BY 4.0 license covering the method.
48pub static LICENSE_CC_BY: &str = include_str!("../LICENSE-CC-BY-4.0");
49/// The attribution notice for every third-party source the payload derives from.
50pub static THIRD_PARTY_NOTICES: &str = include_str!("../THIRD_PARTY_NOTICES.md");
51/// The release notes, which a stage carries as this version's own history.
52pub static CHANGELOG: &str = include_str!("../CHANGELOG.md");
53
54/// Every embedded directory root paired with the authored path it came
55/// from. With [`EMBEDDED_FILES`] it is [`PAYLOAD_ROOTS`] in order: a unit test
56/// holds the union equal to the declaration, so a root embedded here but
57/// missing from the declaration — or the reverse — fails the build rather
58/// than shipping unscanned.
59const EMBEDDED_ROOTS: &[(&str, &Dir<'static>)] = &[
60    ("_docs/specs", &SPECS),
61    ("templates", &TEMPLATES),
62    ("instance", &INSTANCE),
63    ("method", &METHOD),
64    ("skills", &SKILLS),
65    ("skill-shared", &SKILL_SHARED),
66    ("comparison-docs", &COMPARISON_DOCS),
67    ("reference/prior-art", &PRIOR_ART),
68    ("reference/tracker-markup", &TRACKER_MARKUP),
69];
70
71/// Every payload root that is one file, paired with its bytes.
72///
73/// A directory static cannot hold a file that sits beside other authored
74/// content, such as a configuration at the top of the documentation root,
75/// so such a root is embedded by itself.
76const EMBEDDED_FILES: &[(&str, &[u8])] = &[("_docs/.markdownlint-cli2.jsonc", MARKDOWNLINT)];
77
78/// Every embedded root paired with the authored path it came from.
79///
80/// The candidate reads its sources through this, so a root added to the
81/// declaration reaches the projection without a second list.
82#[must_use]
83pub const fn roots() -> &'static [(&'static str, &'static Dir<'static>)] {
84    EMBEDDED_ROOTS
85}
86
87/// Every skill name, sorted; a name is the skill's directory.
88#[must_use]
89pub fn skill_names() -> Vec<&'static str> {
90    let mut names: Vec<&'static str> = SKILLS
91        .dirs()
92        .filter_map(|dir| dir.path().as_os_str().to_str())
93        .collect();
94    names.sort_unstable();
95    names
96}
97
98/// One skill's `SKILL.md` text, by skill name.
99#[must_use]
100pub fn skill(name: &str) -> Option<&'static str> {
101    SKILLS
102        .get_file(format!("{name}/SKILL.md"))
103        .and_then(include_dir::File::contents_utf8)
104}
105
106/// Every file of one installed skill package, as `(path relative to the
107/// package root, bytes)`, sorted by path.
108///
109/// A package is the unit the Agent Skills format and every documented host
110/// resolve against: one directory holding `SKILL.md` and supporting files
111/// beside it. The shared artifacts are authored once under `skill-shared/`
112/// and materialized here into every package, so a fix lands in one file and
113/// reaches every root the installer writes.
114#[must_use]
115pub fn skill_package(name: &str) -> Option<Vec<(String, &'static [u8])>> {
116    use crate::domain::paths::{SKILL_FILE, SKILL_REFERENCES_DIR};
117
118    let manual = SKILLS.get_file(format!("{name}/{SKILL_FILE}"))?;
119    let mut files = vec![(SKILL_FILE.to_string(), manual.contents())];
120    for (path, bytes) in shared_artifacts() {
121        files.push((format!("{SKILL_REFERENCES_DIR}/{path}"), bytes));
122    }
123    files.sort_by(|left, right| left.0.cmp(&right.0));
124    Some(files)
125}
126
127/// Every artifact the skills share, as `(path under the root, bytes)`,
128/// sorted by path.
129///
130/// This is the authored view. What lands is [`skill_package`], which copies
131/// each of these into every package as a reference relative to the skill's
132/// own root.
133#[must_use]
134pub fn shared_artifacts() -> Vec<(String, &'static [u8])> {
135    fn walk(dir: &Dir<'static>, out: &mut Vec<(String, &'static [u8])>) {
136        for file in dir.files() {
137            if let Some(path) = file.path().to_str() {
138                out.push((path.to_string(), file.contents()));
139            }
140        }
141        for sub in dir.dirs() {
142            walk(sub, out);
143        }
144    }
145    let mut out = Vec::new();
146    walk(&SKILL_SHARED, &mut out);
147    out.sort_by(|a, b| a.0.cmp(&b.0));
148    out
149}
150
151/// Resolve a payload source path — as a profile projection names it — to its
152/// embedded bytes.
153#[must_use]
154pub fn asset(source: &str) -> Option<&'static [u8]> {
155    EMBEDDED_FILES
156        .iter()
157        .find_map(|(path, bytes)| (*path == source).then_some(*bytes))
158        .or_else(|| {
159            EMBEDDED_ROOTS.iter().find_map(|(root, dir)| {
160                let rest = source.strip_prefix(root)?.strip_prefix('/')?;
161                dir.get_file(rest).map(include_dir::File::contents)
162            })
163        })
164}
165
166/// Every file under one embedded root, by the logical path that names it.
167///
168/// A root that is one file yields that file alone. The paths come back
169/// sorted, so a caller that copies them writes the same tree every time.
170#[must_use]
171pub fn assets_under(root: &str) -> Vec<(String, &'static [u8])> {
172    if let Some((path, bytes)) = EMBEDDED_FILES.iter().find(|(path, _)| *path == root) {
173        return vec![((*path).to_string(), *bytes)];
174    }
175    let Some((name, dir)) = EMBEDDED_ROOTS.iter().find(|(name, _)| *name == root) else {
176        return Vec::new();
177    };
178    let mut out = Vec::new();
179    collect_under(name, dir, &mut out);
180    out.sort_by(|a, b| a.0.cmp(&b.0));
181    out
182}
183
184fn collect_under(root: &str, dir: &'static Dir<'static>, out: &mut Vec<(String, &'static [u8])>) {
185    for file in dir.files() {
186        if let Some(rest) = file.path().to_str() {
187            out.push((format!("{root}/{rest}"), file.contents()));
188        }
189    }
190    for sub in dir.dirs() {
191        collect_under(root, sub, out);
192    }
193}
194
195/// Every `` ### `domain:rule` `` requirement address the embedded specs define.
196#[must_use]
197pub fn spec_rule_ids() -> BTreeSet<String> {
198    let mut ids = BTreeSet::new();
199    for file in SPECS.files() {
200        let Some(text) = file.contents_utf8() else {
201            continue;
202        };
203        ids.extend(rule_ids_in(text));
204    }
205    ids
206}
207
208/// The requirement addresses one spec document defines.
209pub fn rule_ids_in(text: &str) -> impl Iterator<Item = String> + '_ {
210    text.lines().filter_map(|line| {
211        let candidate = line.strip_prefix("### `")?;
212        let (id, _) = candidate.split_once('`')?;
213        let (domain, rule) = id.split_once(':')?;
214        let is_slug = |part: &str| {
215            !part.is_empty()
216                && part
217                    .bytes()
218                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
219        };
220        (is_slug(domain) && is_slug(rule)).then(|| id.to_string())
221    })
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227    use crate::domain::profile::ProfileId;
228    use crate::domain::rule_id::RuleId;
229
230    #[test]
231    fn rule_id_enum_matches_the_embedded_specs() {
232        let from_specs = spec_rule_ids();
233        let from_enum: BTreeSet<String> = RuleId::ALL
234            .iter()
235            .map(|rule| rule.as_str().to_string())
236            .collect();
237        assert_eq!(
238            from_specs, from_enum,
239            "RuleId and the specs disagree; update the enum and the specs together"
240        );
241    }
242
243    #[test]
244    fn the_embedded_roots_are_the_declared_payload_roots() {
245        let mut embedded: Vec<&str> = EMBEDDED_ROOTS
246            .iter()
247            .map(|(root, _)| *root)
248            .chain(EMBEDDED_FILES.iter().map(|(path, _)| *path))
249            .collect();
250        embedded.sort_unstable();
251        let mut declared = PAYLOAD_ROOTS.to_vec();
252        declared.sort_unstable();
253        assert_eq!(
254            embedded, declared,
255            "payload_roots.rs and the embedded statics disagree; a root missing from the declaration ships unscanned"
256        );
257    }
258
259    #[test]
260    fn a_single_file_root_resolves_through_both_readers() {
261        for (path, bytes) in EMBEDDED_FILES {
262            assert_eq!(asset(path), Some(*bytes), "{path}");
263            assert_eq!(assets_under(path), vec![((*path).to_string(), *bytes)]);
264        }
265        assert!(asset("_docs/.markdownlint-cli2.jsonc/x").is_none());
266    }
267
268    #[test]
269    fn every_profile_projection_resolves_to_an_embedded_asset() {
270        for id in [ProfileId::Codebase, ProfileId::KnowledgeBase] {
271            let profile = id.profile();
272            for entry in profile.managed.iter().chain(profile.adopted) {
273                assert!(
274                    asset(&entry.source).is_some(),
275                    "{id}: {} is not embedded",
276                    entry.source
277                );
278            }
279        }
280    }
281
282    #[test]
283    fn the_method_and_licenses_are_carried() {
284        assert!(METHOD.get_file("glossary.md").is_some());
285        assert!(METHOD.files().count() >= 15);
286        assert!(LICENSE.contains("LICENSE-MIT") && LICENSE.contains("LICENSE-CC-BY-4.0"));
287    }
288
289    #[test]
290    fn rule_id_parser_matches_heading_shape_only() {
291        let text = "### `a-b:c-d` — Title\n### `Bad:Id`\nplain ### `x:y`\n### `no-colon`\n";
292        let ids: Vec<String> = rule_ids_in(text).collect();
293        assert_eq!(ids, vec!["a-b:c-d".to_string()]);
294    }
295}