返回 CodeWhale
system.rs
根目录 / crates / skills / src / system.rs
1 //! System-skill installer: bundles first-party skills and auto-installs them
2 //! on first launch.
3
4 use std::fs;
5 use std::path::{Path, PathBuf};
6
7 use codewhale_runtime::config::{BundledSkillsConfig, BundledSkillsInstall, SkillsConfig};
8 use codewhale_skill_install::skill_parse::{self, normalize_skill_name_for_lookup};
9 use sha2::{Digest, Sha256};
10
11 #[cfg(test)]
12 const BUNDLED_SKILL_VERSION: &str = "27";
13
14 const SKILL_CREATOR_BODY: &str = include_str!("../assets/skills/skill-creator/SKILL.md");
15 const PLUGIN_CREATOR_BODY: &str = include_str!("../assets/skills/plugin-creator/SKILL.md");
16 const SKILL_INSTALLER_BODY: &str = include_str!("../assets/skills/skill-installer/SKILL.md");
17 const HELP_BODY: &str = include_str!("../assets/skills/help/SKILL.md");
18 const REVIEW_BODY: &str = include_str!("../assets/skills/review/SKILL.md");
19 const FORGET_BODY: &str = include_str!("../assets/skills/forget/SKILL.md");
20 /// `name sha256` lines for every body a bundled skill carried in canonical
21 /// history, plus bodies found installed in the field that no ref contains.
22 const SHIPPED_BODY_HASHES: &str = include_str!("system/shipped_hashes.txt");
23
24 fn body_sha256(body: &str) -> String {
25 digest_hex(&Sha256::digest(body.as_bytes()))
26 }
27
28 fn digest_hex(digest: &[u8]) -> String {
29 digest.iter().map(|byte| format!("{byte:02x}")).collect()
30 }
31
32 fn hash_is_listed(table: &str, name: &str, body: &str) -> bool {
33 let digest = body_sha256(body);
34 table
35 .lines()
36 .filter_map(|line| line.split_once(' '))
37 .any(|(skill, listed)| skill == name && listed == digest)
38 }
39
40 /// Whether `existing` is a body CodeWhale previously shipped for `name` (and
41 /// therefore safe to replace on upgrade) by listed SHA-256 hash.
42 fn is_superseded_shipped_body(name: &str, existing: &str) -> bool {
43 hash_is_listed(SHIPPED_BODY_HASHES, name, existing)
44 }
45
46 /// Bundled skills whose installed body is neither the current one nor any
47 /// shipped one: customized by the user or from a generation this build cannot
48 /// identify. The installer never refreshes these.
49 #[must_use]
50 pub fn unrecognized_system_skills(
51 skills_dir: &Path,
52 policy: &BundledSkillsConfig,
53 ) -> Vec<&'static str> {
54 BUNDLED_SKILLS
55 .iter()
56 .filter(|skill| bundled_enabled(policy, skill.name))
57 .filter(|skill| {
58 fs::symlink_metadata(
59 skills_dir
60 .join(".system")
61 .join(skill.name)
62 .join(".installed-from"),
63 )
64 .is_err()
65 })
66 .filter(|skill| {
67 codewhale_util::fs_confined::read_to_string(
68 skills_dir,
69 &skills_dir.join(".system").join(skill.name).join("SKILL.md"),
70 )
71 .is_ok_and(|existing| {
72 existing != skill.body && !is_superseded_shipped_body(skill.name, &existing)
73 })
74 })
75 .map(|skill| skill.name)
76 .collect()
77 }
78
79 struct BundledSkill {
80 name: &'static str,
81 body: &'static str,
82 introduced_in: u32,
83 }
84
85 /// Skills auto-installed for every user on fresh install / upgrade.
86 const BUNDLED_SKILLS: &[BundledSkill] = &[
87 BundledSkill {
88 name: "skill-creator",
89 body: SKILL_CREATOR_BODY,
90 introduced_in: 1,
91 },
92 BundledSkill {
93 name: "plugin-creator",
94 body: PLUGIN_CREATOR_BODY,
95 introduced_in: 3,
96 },
97 BundledSkill {
98 name: "skill-installer",
99 body: SKILL_INSTALLER_BODY,
100 introduced_in: 3,
101 },
102 BundledSkill {
103 name: "help",
104 body: HELP_BODY,
105 introduced_in: 7,
106 },
107 BundledSkill {
108 name: "review",
109 body: REVIEW_BODY,
110 introduced_in: 5,
111 },
112 BundledSkill {
113 name: "forget",
114 body: FORGET_BODY,
115 introduced_in: 12,
116 },
117 ];
118
119 /// Product-facing grouping for the bundled catalog.
120 ///
121 /// User and compatible skills remain outside these two buckets. The grouping
122 /// is deliberately attached to the shipped catalog instead of inferred from
123 /// arbitrary community metadata.
124 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
125 pub enum BundledSkillTier {
126 CoreAgentic,
127 FormatTooling,
128 }
129
130 impl BundledSkillTier {
131 #[must_use]
132 pub const fn label(self) -> &'static str {
133 match self {
134 Self::CoreAgentic => "core",
135 Self::FormatTooling => "tools",
136 }
137 }
138 }
139
140 /// Return the curated tier for a bundled skill name.
141 #[must_use]
142 pub fn bundled_skill_tier(name: &str) -> Option<BundledSkillTier> {
143 if !is_bundled_skill_name(name) {
144 return None;
145 }
146 let tier = match name {
147 "skill-creator" | "plugin-creator" | "skill-installer" | "help" => {
148 BundledSkillTier::FormatTooling
149 }
150 _ => BundledSkillTier::CoreAgentic,
151 };
152 Some(tier)
153 }
154
155 /// Canonical names of every skill in the shipped starter pack, in bundle order.
156 ///
157 /// Exposed so the catalog fixture matrix (#4698) can assert a *bijection*
158 /// between the checked-in fixture and the real bundle: a skill added or removed
159 /// without updating the fixture fails the build rather than silently changing
160 /// what every user gets installed.
161 #[must_use]
162 #[cfg(test)]
163 pub fn bundled_skill_names() -> Vec<&'static str> {
164 BUNDLED_SKILLS.iter().map(|skill| skill.name).collect()
165 }
166
167 #[must_use]
168 #[cfg(test)]
169 pub fn bundled_skill_generation() -> &'static str {
170 BUNDLED_SKILL_VERSION
171 }
172
173 const RETIRED_BUNDLED_SKILL_NAMES: &[&str] = &[
174 "agent-experience",
175 "batch",
176 "best-of-n",
177 "contributor-onboarding",
178 "cordis-composition-reference",
179 "cordis-plugin-development",
180 "dataviz",
181 "debug",
182 "delegate",
183 "dependency-update",
184 "document",
185 "documents",
186 "docx",
187 "editing-cordis-compositions",
188 "feedback",
189 "feishu",
190 "fleet-manager",
191 "flights",
192 "frontend-design",
193 "github",
194 "gmail",
195 "google-calendar",
196 "handoff",
197 "health",
198 "image-search",
199 "implement",
200 "interview",
201 "mcp-builder",
202 "mcp-discovery",
203 "money",
204 "pdf",
205 "personal-goals",
206 "photos",
207 "plan",
208 "podcast",
209 "pptx",
210 "presentations",
211 "release",
212 "research",
213 "security-review",
214 "shopping",
215 "simplify",
216 "social-media",
217 "spotify",
218 "spreadsheets",
219 "test",
220 "tts",
221 "v4-best-practices",
222 "verify",
223 "webapp-testing",
224 "xlsx",
225 ];
226
227 pub(super) fn retired_bundled_skill_name(name: &str) -> Option<&'static str> {
228 let name = normalize_skill_name_for_lookup(name);
229 RETIRED_BUNDLED_SKILL_NAMES
230 .iter()
231 .copied()
232 .find(|retired| *retired == name)
233 }
234
235 fn shipped_by(name: &str, generation: u32) -> bool {
236 if let Some(starter) = BUNDLED_SKILLS.iter().find(|skill| skill.name == name) {
237 return generation >= starter.introduced_in;
238 }
239 let introduced = match name {
240 "delegate" => 2,
241 "feishu" | "v4-best-practices" | "documents" | "mcp-builder" | "pdf" | "presentations"
242 | "spreadsheets" => 3,
243 "fleet-manager" => 4,
244 "batch" | "dataviz" | "debug" | "dependency-update" | "document" | "docx"
245 | "frontend-design" | "implement" | "interview" | "plan" | "pptx" | "release"
246 | "research" | "security-review" | "simplify" | "test" | "verify" | "webapp-testing"
247 | "xlsx" => 5,
248 "best-of-n" => 6,
249 "contributor-onboarding" => 8,
250 "handoff" => 9,
251 "mcp-discovery" => 10,
252 "feedback" | "social-media" | "health" | "flights" | "github" | "gmail"
253 | "google-calendar" | "image-search" | "money" | "personal-goals" | "photos"
254 | "podcast" | "shopping" | "spotify" | "tts" => 12,
255 "agent-experience"
256 | "cordis-composition-reference"
257 | "cordis-plugin-development"
258 | "editing-cordis-compositions" => 21,
259 _ => return false,
260 };
261 generation >= introduced
262 }
263
264 fn retired_bundled_body_matches(retired: &str, body: &str) -> bool {
265 is_superseded_shipped_body(retired, body)
266 }
267
268 pub(super) fn legacy_receipt_paths(root: &Path, name: &str) -> Vec<PathBuf> {
269 starter::legacy_receipt_paths(root, name)
270 }
271
272 fn retired_bundled_copy_matches_shipped(owned: &Path, copy: &Path, retired: &str) -> bool {
273 if !starter::legacy_generation(owned).is_some_and(|generation| shipped_by(retired, generation))
274 || !starter::legacy_tree_is_shipped(owned, retired).unwrap_or(false)
275 {
276 return false;
277 }
278 let Ok(body) = codewhale_util::fs_confined::read_to_string(owned, copy) else {
279 return false;
280 };
281 if !retired_bundled_body_matches(retired, &body) {
282 return false;
283 }
284 let Ok((parsed, _)) = skill_parse::parse_verified_content(copy, &body) else {
285 return false;
286 };
287 retired_bundled_skill_name(&parsed.name) == Some(retired)
288 }
289
290 fn retired_listed(names: &Option<Vec<String>>, retired: &str) -> bool {
291 names
292 .iter()
293 .flatten()
294 .any(|entry| retired_bundled_skill_name(entry) == Some(retired))
295 }
296
297 #[must_use]
298 pub fn retired_bundled_copy_disabled(
299 policy: &BundledSkillsConfig,
300 path: &Path,
301 name: &str,
302 owned: &Path,
303 ) -> bool {
304 retired_bundled_skill_name(name).is_some_and(|retired| {
305 let expected = owned.join(retired).join("SKILL.md");
306 retired_listed(&policy.disabled, retired)
307 && fs::symlink_metadata(owned.join(retired).join(".installed-from")).is_err()
308 && super::roots::paths_refer_to_same_dir(path, &expected)
309 && retired_bundled_copy_matches_shipped(owned, &expected, retired)
310 })
311 }
312
313 /// Whether a skill name matches one of the bundled first-party skills.
314 ///
315 /// Used by `/skills` to distinguish user-created skills (which should be
316 /// surfaced prominently) from the always-installed bundle (which can be
317 /// rendered compactly when many skills are present).
318 ///
319 /// Prefer [`is_exact_bundled_skill`] when classifying audit rows — name-only
320 /// matches can collide with user overrides of the same command name.
321 #[must_use]
322 pub fn is_bundled_skill_name(name: &str) -> bool {
323 BUNDLED_SKILLS.iter().any(|s| s.name == name)
324 }
325
326 /// True when `name` is a bundled skill **and** `skill_md_content` exactly
327 /// matches the shipped asset body (byte-for-byte).
328 ///
329 /// Used by the skill audit inventory so a user-edited copy of a bundled name
330 /// is not misclassified as built-in.
331 #[must_use]
332 pub fn is_exact_bundled_skill(name: &str, skill_md_content: &str) -> bool {
333 BUNDLED_SKILLS
334 .iter()
335 .any(|s| s.name == name && s.body == skill_md_content)
336 }
337
338 mod starter;
339 pub use starter::install_system_skills;
340
341 pub fn canonical_bundled_skill_name(name: &str) -> Option<&'static str> {
342 static CANONICAL: std::sync::LazyLock<std::collections::HashMap<&'static str, &'static str>> =
343 std::sync::LazyLock::new(|| {
344 BUNDLED_SKILLS
345 .iter()
346 .map(|skill| {
347 let canonical =
348 skill_parse::parse_verified_content(Path::new("SKILL.md"), skill.body)
349 .ok()
350 .and_then(|(parsed, _)| {
351 parsed.aliases.into_iter().find_map(|alias| {
352 BUNDLED_SKILLS
353 .iter()
354 .find(|entry| entry.name == alias)
355 .map(|entry| entry.name)
356 })
357 })
358 .unwrap_or(skill.name);
359 (skill.name, canonical)
360 })
361 .collect()
362 });
363 CANONICAL
364 .get(normalize_skill_name_for_lookup(name).as_str())
365 .copied()
366 }
367
368 fn listed(names: &Option<Vec<String>>, name: &str) -> bool {
369 let canonical = canonical_bundled_skill_name(name);
370 canonical.is_some()
371 && names
372 .iter()
373 .flatten()
374 .any(|entry| canonical_bundled_skill_name(entry) == canonical)
375 }
376
377 pub(super) fn bundled_enabled(policy: &BundledSkillsConfig, name: &str) -> bool {
378 !listed(&policy.disabled, name)
379 && (policy.selected.as_ref().is_none_or(Vec::is_empty) || listed(&policy.selected, name))
380 }
381
382 pub(super) fn bundled_disabled_reason(
383 policy: &BundledSkillsConfig,
384 name: &str,
385 ) -> Option<&'static str> {
386 if !is_bundled_skill_name(name) || bundled_enabled(policy, name) {
387 return None;
388 }
389 if listed(&policy.disabled, name) {
390 Some("disabled in [skills.bundled] disabled")
391 } else {
392 Some("not in [skills.bundled] selected")
393 }
394 }
395
396 pub(super) fn bundled_explicit_only(policy: &BundledSkillsConfig, name: &str) -> bool {
397 bundled_enabled(policy, name) && listed(&policy.explicit_only, name)
398 }
399
400 fn read_bundled_copy_body(path: &Path, name: &str, owned: &Path) -> Option<String> {
401 let expected = owned.join(".system").join(name).join("SKILL.md");
402 if !is_bundled_skill_name(name)
403 || !super::roots::paths_refer_to_same_dir(path, &expected)
404 || fs::symlink_metadata(owned.join(".system").join(name).join(".installed-from")).is_ok()
405 {
406 return None;
407 }
408 let body = codewhale_util::fs_confined::read_to_string(owned, &expected).ok()?;
409 (is_exact_bundled_skill(name, &body) || is_superseded_shipped_body(name, &body)).then_some(body)
410 }
411
412 pub fn is_bundled_copy(path: &Path, name: &str, owned: &Path) -> bool {
413 read_bundled_copy_body(path, name, owned).is_some()
414 }
415
416 pub fn verified_bundled_skill_dir(path: &Path, name: &str, owned: &Path) -> Option<PathBuf> {
417 let owned = fs::canonicalize(owned).ok()?;
418 read_bundled_copy_body(path, name, &owned)?;
419 Some(owned.join(".system").join(name))
420 }
421
422 #[derive(Debug, serde::Serialize)]
423 pub struct BundledSkillStatus {
424 pub name: &'static str,
425 pub path: std::path::PathBuf,
426 pub reason: String,
427 }
428
429 #[derive(Debug, serde::Serialize)]
430 pub struct BundledSkillsStatus {
431 pub install: BundledSkillsInstall,
432 pub marker_generation: Option<String>,
433 pub installed: usize,
434 pub selected_missing: Vec<&'static str>,
435 pub disabled: Vec<&'static str>,
436 pub explicit_only: Vec<&'static str>,
437 pub shadowed: Vec<&'static str>,
438 pub unknown: Vec<String>,
439 pub retired: Vec<String>,
440 pub ignored: Vec<String>,
441 pub skills: Vec<BundledSkillStatus>,
442 }
443
444 impl BundledSkillsStatus {
445 pub fn summary(&self) -> String {
446 format!(
447 "Bundled skills: install={}, generation={}, installed={}, selected missing={}, disabled={}, explicit-only={}, shadowed={}",
448 match self.install {
449 BundledSkillsInstall::Auto => "auto",
450 BundledSkillsInstall::All => "all",
451 BundledSkillsInstall::None => "none",
452 },
453 self.marker_generation
454 .as_deref()
455 .unwrap_or("missing or invalid"),
456 self.installed,
457 self.selected_missing.len(),
458 self.disabled.len(),
459 self.explicit_only.len(),
460 self.shadowed.len()
461 )
462 }
463
464 pub fn inspection(&self) -> Vec<String> {
465 let mut lines = vec![self.summary()];
466 if !self.unknown.is_empty() {
467 lines.push(format!(
468 "Unknown bundled names: {}",
469 self.unknown.join(", ")
470 ));
471 }
472 if !self.retired.is_empty() {
473 lines.push(format!("No longer bundled: {}", self.retired.join(", ")));
474 }
475 if !self.ignored.is_empty() {
476 lines.push(format!(
477 "Ignored explicit_only entries: {}",
478 self.ignored.join(", ")
479 ));
480 }
481 lines.extend(
482 self.skills
483 .iter()
484 .map(|row| format!("{}: {} ({})", row.name, row.reason, row.path.display())),
485 );
486 lines
487 }
488 }
489
490 pub fn bundled_skills_status(
491 config: &SkillsConfig,
492 registry: &super::SkillRegistry,
493 ) -> Option<BundledSkillsStatus> {
494 let owned = codewhale_runtime::config::owned_skills_dir()?;
495 let policy = &config.bundled;
496 let marker_generation = starter::installed_fingerprint(&owned).ok().flatten();
497 let mut status = BundledSkillsStatus {
498 install: policy.install.unwrap_or_default(),
499 marker_generation,
500 installed: 0,
501 selected_missing: vec![],
502 disabled: vec![],
503 explicit_only: vec![],
504 shadowed: vec![],
505 unknown: vec![],
506 retired: vec![],
507 ignored: vec![],
508 skills: vec![],
509 };
510 for (field, names) in [
511 ("selected", &policy.selected),
512 ("disabled", &policy.disabled),
513 ("explicit_only", &policy.explicit_only),
514 ] {
515 for name in names.iter().flatten() {
516 if let Some(retired) = retired_bundled_skill_name(name) {
517 let copy = owned.join(retired).join("SKILL.md");
518 let installed = fs::metadata(&copy).is_ok_and(|meta| meta.is_file());
519 let has_marker =
520 fs::symlink_metadata(owned.join(retired).join(".installed-from")).is_ok();
521 let matches_shipped =
522 installed && retired_bundled_copy_matches_shipped(&owned, &copy, retired);
523 let hidden = retired_listed(&policy.disabled, retired)
524 && installed
525 && !has_marker
526 && matches_shipped;
527 let state = match (field, installed) {
528 ("disabled", true) if has_marker => format!(
529 "installed copy at {} has .installed-from and stays active",
530 copy.display()
531 ),
532 ("disabled", true) if !matches_shipped => format!(
533 "copy at {} was customized or renamed and stays active",
534 copy.display()
535 ),
536 ("disabled", true) => format!("installed copy at {} is hidden", copy.display()),
537 ("disabled", false) => {
538 "no copy installed; this entry can be removed".to_string()
539 }
540 (_, true) if hidden => "hidden by disabled".to_string(),
541 (_, true) => format!(
542 "this entry has no effect; the copy at {} loads as a user skill",
543 copy.display()
544 ),
545 (_, false) => "no copy installed; this entry can be removed".to_string(),
546 };
547 status.retired.push(format!("{field}={retired} ({state})"));
548 } else if canonical_bundled_skill_name(name).is_none() {
549 status
550 .unknown
551 .push(format!("{field}={}", name.escape_debug()));
552 } else if field == "explicit_only" && !bundled_enabled(policy, name) {
553 status.ignored.push(name.escape_debug().to_string());
554 }
555 }
556 }
557 for skill in BUNDLED_SKILLS {
558 let path = owned.join(".system").join(skill.name).join("SKILL.md");
559 let installed = codewhale_util::fs_confined::read_to_string(&owned, &path).is_ok();
560 status.installed += usize::from(installed);
561 let selected = registry
562 .skills
563 .iter()
564 .find(|entry| entry.name == skill.name);
565 let shadowed =
566 selected.filter(|entry| !super::roots::paths_refer_to_same_dir(&entry.path, &path));
567 let reason = if !bundled_enabled(policy, skill.name) {
568 status.disabled.push(skill.name);
569 let reason = if listed(&policy.disabled, skill.name) {
570 "disabled by config"
571 } else {
572 "not selected by config"
573 };
574 if installed && !is_bundled_copy(&path, skill.name, &owned) {
575 format!("manual or managed copy unaffected; bundled name {reason}")
576 } else if let Some(selected) = shadowed {
577 format!("{reason}; active copy at {}", selected.path.display())
578 } else {
579 reason.to_string()
580 }
581 } else if let Some(selected) = shadowed {
582 status.shadowed.push(skill.name);
583 format!("shadowed by {}", selected.path.display())
584 } else if !installed {
585 status.selected_missing.push(skill.name);
586 "selected but not installed".to_string()
587 } else if !is_bundled_copy(&path, skill.name, &owned) {
588 "manual or managed copy preserved".to_string()
589 } else if bundled_explicit_only(policy, skill.name) {
590 status.explicit_only.push(skill.name);
591 "explicit-only by config".to_string()
592 } else {
593 "installed".to_string()
594 };
595 status.skills.push(BundledSkillStatus {
596 name: skill.name,
597 path,
598 reason,
599 });
600 }
601 Some(status)
602 }
603
604 #[cfg(test)]
605 mod tests;
606
606 lines RUST