1use std::collections::BTreeSet;
10use std::path::Path;
11
12use include_dir::{Dir, include_dir};
13
14pub use crate::payload_roots::PAYLOAD_ROOTS;
15
16pub static SPECS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/_docs/specs");
18pub static TEMPLATES: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/templates");
20pub static MARKDOWNLINT: &[u8] = include_bytes!("../_docs/.markdownlint-cli2.jsonc");
23pub static INSTANCE: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/instance");
30pub static METHOD: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/method");
32pub static SKILLS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/skills");
34pub static SKILL_SHARED: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/skill-shared");
36pub static COMPARISON_DOCS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/comparison-docs");
38pub static PRIOR_ART: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/reference/prior-art");
40pub static TRACKER_MARKUP: Dir<'static> =
42 include_dir!("$CARGO_MANIFEST_DIR/reference/tracker-markup");
43
44pub static LICENSE: &str = include_str!("../LICENSE");
46pub static LICENSE_MIT: &str = include_str!("../LICENSE-MIT");
48pub static LICENSE_CC_BY: &str = include_str!("../LICENSE-CC-BY-4.0");
50pub static THIRD_PARTY_NOTICES: &str = include_str!("../THIRD_PARTY_NOTICES.md");
52pub static CHANGELOG: &str = include_str!("../CHANGELOG.md");
54
55const EMBEDDED_ROOTS: &[(&str, &Dir<'static>)] = &[
61 ("_docs/specs", &SPECS),
62 ("templates", &TEMPLATES),
63 ("instance", &INSTANCE),
64 ("method", &METHOD),
65 ("skills", &SKILLS),
66 ("skill-shared", &SKILL_SHARED),
67 ("comparison-docs", &COMPARISON_DOCS),
68 ("reference/prior-art", &PRIOR_ART),
69 ("reference/tracker-markup", &TRACKER_MARKUP),
70];
71
72const EMBEDDED_FILES: &[(&str, &[u8])] = &[("_docs/.markdownlint-cli2.jsonc", MARKDOWNLINT)];
78
79#[must_use]
84pub const fn roots() -> &'static [(&'static str, &'static Dir<'static>)] {
85 EMBEDDED_ROOTS
86}
87
88#[must_use]
90pub fn skill_names() -> Vec<&'static str> {
91 let mut names: Vec<&'static str> = SKILLS
92 .dirs()
93 .filter_map(|dir| dir.path().as_os_str().to_str())
94 .collect();
95 names.sort_unstable();
96 names
97}
98
99#[must_use]
101pub fn skill(name: &str) -> Option<&'static str> {
102 SKILLS
103 .get_file(format!("{name}/SKILL.md"))
104 .and_then(include_dir::File::contents_utf8)
105}
106
107#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
109pub enum PackageError {
110 #[error("the payload carries no skill named {0}")]
112 Unknown(String),
113 #[error(
115 "{skill}: {path} is claimed by the skill and by the shared source; author it once (skill-format:shared-content-is-authored-once)"
116 )]
117 Collision {
118 skill: String,
120 path: String,
122 },
123 #[error(
125 "{skill}: {path} is neither SKILL.md nor a file under references/ (skill-format:a-package-holds-the-manual-and-its-references)"
126 )]
127 Unlisted {
128 skill: String,
130 path: String,
132 },
133}
134
135pub fn skill_package(name: &str) -> Result<Vec<(String, &'static [u8])>, PackageError> {
150 let dir = SKILLS
151 .get_dir(name)
152 .ok_or_else(|| PackageError::Unknown(name.to_string()))?;
153 compose_package(name, dir, &SKILL_SHARED)
154}
155
156pub fn compose_package(
170 name: &str,
171 skill: &'static Dir<'static>,
172 shared: &'static Dir<'static>,
173) -> Result<Vec<(String, &'static [u8])>, PackageError> {
174 use crate::domain::paths::{SKILL_FILE, SKILL_REFERENCES_DIR};
175
176 let mut files = Vec::new();
177 for (relative, bytes) in files_relative_to(skill) {
178 let allowed = relative == SKILL_FILE
179 || relative
180 .strip_prefix(&format!("{SKILL_REFERENCES_DIR}/"))
181 .is_some_and(|file| !file.is_empty() && !file.contains('/'));
182 if !allowed {
183 return Err(PackageError::Unlisted {
184 skill: name.to_string(),
185 path: relative,
186 });
187 }
188 files.push((relative, bytes));
189 }
190 if !files.iter().any(|(path, _)| path == SKILL_FILE) {
191 return Err(PackageError::Unknown(name.to_string()));
192 }
193 for (path, bytes) in files_relative_to(shared) {
194 let relative = format!("{SKILL_REFERENCES_DIR}/{path}");
195 if files.iter().any(|(claimed, _)| *claimed == relative) {
196 return Err(PackageError::Collision {
197 skill: name.to_string(),
198 path: relative,
199 });
200 }
201 files.push((relative, bytes));
202 }
203 files.sort_by(|left, right| left.0.cmp(&right.0));
204 Ok(files)
205}
206
207fn files_relative_to(dir: &'static Dir<'static>) -> Vec<(String, &'static [u8])> {
209 fn walk(base: &Path, dir: &'static Dir<'static>, out: &mut Vec<(String, &'static [u8])>) {
210 for file in dir.files() {
211 let relative = file
212 .path()
213 .strip_prefix(base)
214 .unwrap_or_else(|_| file.path());
215 if let Some(relative) = relative.to_str() {
216 out.push((relative.to_string(), file.contents()));
217 }
218 }
219 for sub in dir.dirs() {
220 walk(base, sub, out);
221 }
222 }
223 let mut out = Vec::new();
224 walk(dir.path(), dir, &mut out);
225 out
226}
227
228#[must_use]
235pub fn shared_artifacts() -> Vec<(String, &'static [u8])> {
236 let mut out = files_relative_to(&SKILL_SHARED);
237 out.sort_by(|a, b| a.0.cmp(&b.0));
238 out
239}
240
241#[must_use]
244pub fn asset(source: &str) -> Option<&'static [u8]> {
245 EMBEDDED_FILES
246 .iter()
247 .find_map(|(path, bytes)| (*path == source).then_some(*bytes))
248 .or_else(|| {
249 EMBEDDED_ROOTS.iter().find_map(|(root, dir)| {
250 let rest = source.strip_prefix(root)?.strip_prefix('/')?;
251 dir.get_file(rest).map(include_dir::File::contents)
252 })
253 })
254}
255
256#[must_use]
261pub fn assets_under(root: &str) -> Vec<(String, &'static [u8])> {
262 if let Some((path, bytes)) = EMBEDDED_FILES.iter().find(|(path, _)| *path == root) {
263 return vec![((*path).to_string(), *bytes)];
264 }
265 let Some((name, dir)) = EMBEDDED_ROOTS.iter().find(|(name, _)| *name == root) else {
266 return Vec::new();
267 };
268 let mut out = Vec::new();
269 collect_under(name, dir, &mut out);
270 out.sort_by(|a, b| a.0.cmp(&b.0));
271 out
272}
273
274fn collect_under(root: &str, dir: &'static Dir<'static>, out: &mut Vec<(String, &'static [u8])>) {
275 for file in dir.files() {
276 if let Some(rest) = file.path().to_str() {
277 out.push((format!("{root}/{rest}"), file.contents()));
278 }
279 }
280 for sub in dir.dirs() {
281 collect_under(root, sub, out);
282 }
283}
284
285#[must_use]
287pub fn spec_rule_ids() -> BTreeSet<String> {
288 let mut ids = BTreeSet::new();
289 for file in SPECS.files() {
290 let Some(text) = file.contents_utf8() else {
291 continue;
292 };
293 ids.extend(rule_ids_in(text));
294 }
295 ids
296}
297
298pub fn spec_texts() -> impl Iterator<Item = &'static str> {
300 SPECS.files().filter_map(include_dir::File::contents_utf8)
301}
302
303pub fn rule_ids_in(text: &str) -> impl Iterator<Item = String> + '_ {
305 text.lines().filter_map(|line| {
306 let candidate = line.strip_prefix("### `")?;
307 let (id, _) = candidate.split_once('`')?;
308 let (domain, rule) = id.split_once(':')?;
309 let is_slug = |part: &str| {
310 !part.is_empty()
311 && part
312 .bytes()
313 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
314 };
315 (is_slug(domain) && is_slug(rule)).then(|| id.to_string())
316 })
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322 use crate::domain::profile::ProfileId;
323 use crate::domain::rule_id::RuleId;
324
325 #[test]
326 fn rule_id_enum_matches_the_embedded_specs() {
327 let from_specs = spec_rule_ids();
328 let from_enum: BTreeSet<String> = RuleId::ALL
329 .iter()
330 .map(|rule| rule.as_str().to_string())
331 .collect();
332 assert_eq!(
333 from_specs, from_enum,
334 "RuleId and the specs disagree; update the enum and the specs together"
335 );
336 }
337
338 #[test]
339 fn the_embedded_roots_are_the_declared_payload_roots() {
340 let mut embedded: Vec<&str> = EMBEDDED_ROOTS
341 .iter()
342 .map(|(root, _)| *root)
343 .chain(EMBEDDED_FILES.iter().map(|(path, _)| *path))
344 .collect();
345 embedded.sort_unstable();
346 let mut declared = PAYLOAD_ROOTS.to_vec();
347 declared.sort_unstable();
348 assert_eq!(
349 embedded, declared,
350 "payload_roots.rs and the embedded statics disagree; a root missing from the declaration ships unscanned"
351 );
352 }
353
354 #[test]
355 fn a_single_file_root_resolves_through_both_readers() {
356 for (path, bytes) in EMBEDDED_FILES {
357 assert_eq!(asset(path), Some(*bytes), "{path}");
358 assert_eq!(assets_under(path), vec![((*path).to_string(), *bytes)]);
359 }
360 assert!(asset("_docs/.markdownlint-cli2.jsonc/x").is_none());
361 }
362
363 #[test]
364 fn every_profile_projection_resolves_to_an_embedded_asset() {
365 for id in [ProfileId::Codebase, ProfileId::KnowledgeBase] {
366 let profile = id.profile();
367 for entry in profile.managed.iter().chain(profile.adopted) {
368 assert!(
369 asset(&entry.source).is_some(),
370 "{id}: {} is not embedded",
371 entry.source
372 );
373 }
374 }
375 }
376
377 #[test]
378 fn the_method_and_licenses_are_carried() {
379 assert!(METHOD.get_file("glossary.md").is_some());
380 assert!(METHOD.files().count() >= 15);
381 assert!(LICENSE.contains("LICENSE-MIT") && LICENSE.contains("LICENSE-CC-BY-4.0"));
382 }
383
384 use include_dir::{DirEntry, File};
385
386 static SHARED: Dir<'static> = Dir::new(
387 "",
388 &[DirEntry::File(File::new("plan-gate.md", b"shared gate"))],
389 );
390 static OWN_REFERENCE: Dir<'static> = Dir::new(
391 "demo",
392 &[
393 DirEntry::File(File::new("demo/SKILL.md", b"manual")),
394 DirEntry::Dir(Dir::new(
395 "demo/references",
396 &[DirEntry::File(File::new(
397 "demo/references/land.md",
398 b"task",
399 ))],
400 )),
401 ],
402 );
403 static CLAIMED_TWICE: Dir<'static> = Dir::new(
404 "demo",
405 &[
406 DirEntry::File(File::new("demo/SKILL.md", b"manual")),
407 DirEntry::Dir(Dir::new(
408 "demo/references",
409 &[DirEntry::File(File::new(
410 "demo/references/plan-gate.md",
411 b"a copy",
412 ))],
413 )),
414 ],
415 );
416 static UNLISTED: Dir<'static> = Dir::new(
417 "demo",
418 &[
419 DirEntry::File(File::new("demo/SKILL.md", b"manual")),
420 DirEntry::Dir(Dir::new(
421 "demo/scripts",
422 &[DirEntry::File(File::new("demo/scripts/check.sh", b"echo"))],
423 )),
424 ],
425 );
426
427 #[test]
429 fn a_skill_reference_lands_beside_the_shared_artifacts() {
430 let package = compose_package("demo", &OWN_REFERENCE, &SHARED).unwrap();
431 let paths: Vec<&str> = package.iter().map(|(path, _)| path.as_str()).collect();
432 assert_eq!(
433 paths,
434 ["SKILL.md", "references/land.md", "references/plan-gate.md"]
435 );
436 }
437
438 #[test]
440 fn a_name_both_sources_claim_fails_the_package() {
441 let error = compose_package("demo", &CLAIMED_TWICE, &SHARED).unwrap_err();
442 assert_eq!(
443 error,
444 PackageError::Collision {
445 skill: "demo".to_string(),
446 path: "references/plan-gate.md".to_string(),
447 }
448 );
449 assert!(
450 error
451 .to_string()
452 .contains("skill-format:shared-content-is-authored-once")
453 );
454 }
455
456 #[test]
458 fn a_file_outside_the_allowlist_fails_the_package() {
459 let error = compose_package("demo", &UNLISTED, &SHARED).unwrap_err();
460 assert_eq!(
461 error,
462 PackageError::Unlisted {
463 skill: "demo".to_string(),
464 path: "scripts/check.sh".to_string(),
465 }
466 );
467 }
468
469 #[test]
470 fn a_name_the_payload_lacks_is_unknown() {
471 assert_eq!(
472 skill_package("no-such-skill"),
473 Err(PackageError::Unknown("no-such-skill".to_string()))
474 );
475 }
476
477 #[test]
478 fn rule_id_parser_matches_heading_shape_only() {
479 let text = "### `a-b:c-d` — Title\n### `Bad:Id`\nplain ### `x:y`\n### `no-colon`\n";
480 let ids: Vec<String> = rule_ids_in(text).collect();
481 assert_eq!(ids, vec!["a-b:c-d".to_string()]);
482 }
483}