//! Shipping the agent assets with the binary. //! //! The skill documents live in `assets/` in this repo and are embedded with //! `include_str!` rather than copied by an install script, because `cargo install` //! places binaries and nothing else. Embedding means a document can never be a //! different version from the binary it describes, and there is no second file to //! lose track of. //! //! `SKILLS` is every skill the binary carries, and `install-skill` writes all of them. //! One document teaches the CLI and the others teach a job done with it; a person who //! has learned the invocation should not have to learn a new name for each document //! added later, or the new one silently never arrives. //! //! The machinery is written once for both kinds of asset this repo will ship. The tool //! file for opencode is executable code needing Bun, so it gets its own command and its //! own root, but the compare-and-refuse logic is the same and lives here. use std::io; use std::path::{Path, PathBuf}; use anyhow::{Result, anyhow}; /// One thing the binary carries and can write into a user's agent configuration. pub struct Asset { /// How it is addressed on the command line. For a skill this is also its directory /// and its frontmatter `name:`, which both agents require to agree. pub name: &'static str, /// What it is called in messages, e.g. `skill`. pub what: &'static str, /// Where it goes under its root, e.g. `worklane/SKILL.md`. pub relative: &'static str, pub content: &'static str, } /// The skill that teaches the CLI, as of the commit this binary was built from. pub const SKILL: Asset = Asset { name: "worklane", what: "skill", relative: "worklane/SKILL.md", content: include_str!("../assets/SKILL.md"), }; /// The skill that reviews a finished ticket against the code that claims to close it. /// /// A document of its own rather than a section of `SKILL`, because it is loaded for a /// different job: the CLI skill is wanted for anything touching a ticket, and this is /// wanted only when a review is asked for. One document holding both would be loaded /// constantly to say nothing, and the frontmatter description, which is the whole of /// what decides the loading, cannot describe two jobs without fitting neither. pub const REVIEW_SKILL: Asset = Asset { name: "worklane-review", what: "skill", relative: "worklane-review/SKILL.md", content: include_str!("../assets/REVIEW.md"), }; /// The skill that grooms the board as a whole rather than a ticket at a time. /// /// Its own document for the reason `REVIEW_SKILL` is: it is wanted for questions about /// the backlog as a body of work, and loading it for every ticket touched would be a /// description that fits nothing. It is also the document where the destructive edits /// live, since every job in it writes to many tickets at once. pub const PLAN_SKILL: Asset = Asset { name: "worklane-plan", what: "skill", relative: "worklane-plan/SKILL.md", content: include_str!("../assets/PLAN.md"), }; /// Every skill this binary carries, in the order they install. /// /// A `static` rather than a `const` so the slice borrowed from it outlives the /// statement that took it: a `const` is inlined at each use and the borrow dies there. pub static SKILLS: [Asset; 3] = [SKILL, REVIEW_SKILL, PLAN_SKILL]; /// The skill a name on the command line asks for. pub fn skill_named(name: &str) -> Result<&'static Asset> { SKILLS .iter() .find(|asset| asset.name == name) .ok_or_else(|| anyhow!("no skill named {name:?}. This binary ships {}", skill_names())) } /// The names, for the errors that have to say what there is to choose from. pub fn skill_names() -> String { SKILLS .iter() .map(|asset| asset.name) .collect::>() .join(", ") } /// Where a skill has to sit to be found, for both agents worklane is used from. /// /// One path serves both. Claude Code reads `~/.claude/skills//SKILL.md`, and /// opencode loads that same directory as an external skill source, alongside its own /// `~/.config/opencode/skill/`. Checked against opencode 1.15.10, whose built-in /// `customize-opencode` skill documents it and whose `opencode debug skill` lists the /// documents found there. Writing both paths would be two copies of one document, free /// to drift apart, for no gain. pub fn skills_root() -> Result { let home = std::env::var_os("HOME").ok_or_else(|| { anyhow!("cannot tell where your skills live because HOME is not set in the environment") })?; Ok(Path::new(&home).join(".claude/skills")) } #[derive(Debug, PartialEq, Eq)] pub enum Outcome { Written(PathBuf), /// Already byte-identical, so writing it again would be a no-op. Unchanged(PathBuf), /// Present but different, and no `--force`. Refused rather than overwritten: it /// may have been edited on purpose, and silently discarding that is worse than /// stopping. Refused(PathBuf), } impl Asset { pub fn path(&self, root: &Path) -> PathBuf { root.join(self.relative) } /// Write the asset under `root`, unless what is there is the same or was changed. /// /// The root is passed in rather than looked up, so a test can install into a /// temporary directory instead of the home of whoever runs the suite. pub fn install(&self, root: &Path, force: bool) -> io::Result { let path = self.path(root); // A read error is not treated as "absent": the write below reports it, with // the real reason, rather than this guessing that the file is missing. match std::fs::read_to_string(&path) { Ok(existing) if existing == self.content => return Ok(Outcome::Unchanged(path)), Ok(_) if !force => return Ok(Outcome::Refused(path)), _ => {} } if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } std::fs::write(&path, self.content)?; Ok(Outcome::Written(path)) } } /// The `name:` and `description:` from the YAML frontmatter. /// /// Used by the tests that guard the shipping mechanism, which is the only thing that /// needs it: both agents decide whether to load a document from these two fields, and /// a document missing them is ignored in silence. #[cfg_attr(not(test), allow(dead_code))] fn frontmatter_field(text: &str, key: &str) -> Option { let body = text.strip_prefix("---\n")?; let end = body.find("\n---")?; body[..end] .lines() .find_map(|line| line.strip_prefix(&format!("{key}:"))) .map(|value| value.trim().to_string()) } #[cfg(test)] mod tests { use super::*; fn root() -> tempfile::TempDir { tempfile::tempdir().unwrap() } #[test] fn the_skill_installs_into_a_directory_that_does_not_exist_yet() { let root = root(); let path = SKILL.path(root.path()); assert_eq!(SKILL.install(root.path(), false).unwrap(), Outcome::Written(path.clone())); assert_eq!(std::fs::read_to_string(&path).unwrap(), SKILL.content); } /// Installing twice is a no-op rather than a rewrite, so the mtime of an /// up-to-date copy does not move. #[test] fn a_second_install_reports_the_copy_unchanged() { let root = root(); SKILL.install(root.path(), false).unwrap(); assert_eq!( SKILL.install(root.path(), false).unwrap(), Outcome::Unchanged(SKILL.path(root.path())) ); } /// The case worth being careful about: an edited copy is someone's work. #[test] fn a_modified_copy_is_refused_and_left_alone() { let root = root(); let path = SKILL.path(root.path()); SKILL.install(root.path(), false).unwrap(); std::fs::write(&path, "hand written\n").unwrap(); assert_eq!(SKILL.install(root.path(), false).unwrap(), Outcome::Refused(path.clone())); assert_eq!(std::fs::read_to_string(&path).unwrap(), "hand written\n"); assert_eq!(SKILL.install(root.path(), true).unwrap(), Outcome::Written(path.clone())); assert_eq!(std::fs::read_to_string(&path).unwrap(), SKILL.content); } #[test] fn every_skill_lands_where_both_agents_look_for_it() { let root = skills_root().unwrap(); assert!(root.ends_with(".claude/skills"), "{}", root.display()); for asset in &SKILLS { let path = asset.path(&root); assert!( path.ends_with(format!(".claude/skills/{}/SKILL.md", asset.name)), "{}", path.display() ); } } /// Two documents that install to one path means the second silently replaces the /// first, and only whichever is listed last is ever read. A copy-pasted `relative` /// is exactly how that happens. #[test] fn no_two_shipped_skills_share_a_name_or_a_path() { for (index, asset) in SKILLS.iter().enumerate() { for other in &SKILLS[index + 1..] { assert_ne!(asset.name, other.name); assert_ne!(asset.relative, other.relative); } } } #[test] fn every_embedded_skill_has_usable_frontmatter() { // Guards the whole shipping mechanism: without frontmatter, or under a name // that does not match its directory, both agents ignore the document and // nothing else would notice. for asset in &SKILLS { assert_eq!( frontmatter_field(asset.content, "name").as_deref(), Some(asset.name), "the frontmatter name has to match the directory it installs into" ); let description = frontmatter_field(asset.content, "description").unwrap_or_else(|| { panic!("{} ships without a description to trigger on", asset.name) }); assert!( description.len() > 80, "{}: the description is what decides whether the skill loads at all", asset.name ); } } /// Every code span and fenced-block line, which is where commands live. /// /// Prose has to be excluded: the document opens by calling worklane a kanban /// board, and treating that sentence as a command makes the check useless. fn code_snippets(text: &str) -> Vec { let mut snippets = Vec::new(); let mut fenced = false; for line in text.lines() { if line.trim_start().starts_with("```") { fenced = !fenced; continue; } if fenced { snippets.push(line.to_string()); continue; } // Inline spans: the odd-numbered pieces between backticks. for (index, piece) in line.split('`').enumerate() { if index % 2 == 1 { snippets.push(piece.to_string()); } } } snippets } #[test] fn no_embedded_skill_names_a_command_that_does_not_exist() { // Taken from clap rather than written out here. A hand-maintained list is the // very drift this test exists to catch. use clap::CommandFactory; let mut known: Vec = crate::Cli::command() .get_subcommands() .map(|c| c.get_name().to_string()) .collect(); known.push("--help".to_string()); known.push("--version".to_string()); let mut total = 0; for asset in &SKILLS { let mut checked = 0; for snippet in code_snippets(asset.content) { let mut words = snippet.split_whitespace(); // Only a snippet that *starts* with worklane is a command being shown. if words.next() != Some("worklane") { continue; } let Some(candidate) = words.next() else { continue; }; // A flag before the subcommand, as in the `mv -- -leading-title` example. if candidate.starts_with("--") && !known.iter().any(|k| k == candidate) { continue; } checked += 1; assert!( known.iter().any(|k| k == candidate), "{} shows `worklane {candidate}`, which is not a subcommand", asset.name ); } // A skill that shows no command at all is either not about worklane or has // had its examples emptied out, and either way the check above passed on // nothing. assert!(checked > 0, "{} shows no worklane command at all", asset.name); total += checked; } assert!(total > 8, "expected the skills to show commands, checked only {total}"); } /// Subcommands the skill has no business teaching: the board is interactive and /// belongs to a person, `install-skill` is how the document arrived, and `help` /// is clap's own. const NOT_FOR_AGENTS: [&str; 3] = ["tui", "install-skill", "help"]; /// The converse, and the one that goes stale on its own: a *new* subcommand absent /// from the skill is invisible to an agent, and nothing else would notice. /// /// `SKILL` alone, deliberately. It is the document that owns the CLI surface, and /// the others teach one job with the handful of commands that job uses. Requiring /// every subcommand of each of them would fill a review document with campaigns /// and `init` to satisfy a test. #[test] fn every_agent_facing_subcommand_is_documented() { use clap::CommandFactory; for command in crate::Cli::command().get_subcommands() { let name = command.get_name(); if NOT_FOR_AGENTS.contains(&name) { continue; } assert!( SKILL.content.contains(&format!("worklane {name}")), "the skill never mentions `worklane {name}`, so an agent will not know it exists" ); } } /// The facts an agent cannot infer from the help output and would get wrong. #[test] fn the_embedded_skill_documents_what_the_help_does_not() { for required in [ "committed", "as you work it", "UUID prefix", "leading hyphen", "Search the backlog before filing", ] { assert!( SKILL.content.contains(required), "the skill no longer mentions {required:?}" ); } } /// The rules that keep a grooming sweep from being a silent rewrite of the board. /// /// Every one of these is a line an edit could drop while leaving a document that /// still reads like a plan: `set --tags` replacing the whole field is how thirty /// tickets quietly lose their tags, and propose-then-apply is the only thing /// standing between a wrong judgement and thirty wrong tickets. #[test] fn the_plan_skill_keeps_the_rules_that_bound_a_sweep() { for required in [ "Propose the whole set of edits", "replaces the whole\nfield", // `set --tags` is the destructive one "not\nback to what it held", // and --clear is not an undo "blocked by", // ordering constrains any dating plan "worklane campaign ls", "does not touch", ] { assert!( PLAN_SKILL.content.contains(required), "the plan skill no longer says {required:?}" ); } } /// The decisions that make the review document a review rather than a rewrite. /// /// Each of these is a rule an edit would drop without breaking anything else: a /// reviewer that ticks criteria or moves the ticket still runs, and produces a /// board where nothing records that anyone disagreed. #[test] fn the_review_skill_keeps_the_decisions_that_define_it() { for required in [ "worklane show", // the ticket is read before the code "nothing names the ticket", // and the no-work-found case is answered "Never tick a criterion", "Do not move the ticket", "worklane uncheck", "worklane append", "cannot tell", ] { assert!( REVIEW_SKILL.content.contains(required), "the review skill no longer says {required:?}" ); } } }