Files
worklane/src/install.rs
T
Ansho ReiandClaude Opus 5 11145b228e (c092ea7) Ship the opencode tool definitions with the binary, behind install-tool
`.opencode/tools/worklane.ts` was the second agent asset and the only one
that existed nowhere but a checkout. `cargo install` places binaries and
nothing else, so anyone who installed worklane got the skills and never the
tools, and the copy that did exist was reachable only from this repo. It is
now `assets/TOOL.ts`, embedded with `include_str!` like every other asset,
and `install-tool` writes it where opencode looks.

Its own command rather than a flag on `install-skill`, because the two
artifacts are not alike. A skill is inert markdown and one path serves both
agents. The tool is executable TypeScript and serves one: Claude Code has no
directory it scans for a tool definition, `claude mcp add` is the only way a
tool enters its list, and its plugin system adopts agents, hooks, monitors,
workflows, output-styles and themes and nothing named tools. Reaching it
would mean an MCP server, which is a different artifact and not this file.
So somebody on Claude Code takes the documents and never the wrapper, which
is the choice this command exists to give them.

The path was measured rather than guessed, as the ticket asked. 1.15.10
loads `~/.config/opencode/tool/` and `~/.config/opencode/tools/` both: each
was served in turn from a directory outside any project and
`/experimental/tool/ids` came back with all eleven worklane tools. Singular
is the target, the spelling opencode's own documentation puts first the way
it writes `agent(s)` and `skill(s)`. `tools_root()` follows
`XDG_CONFIG_HOME` where `skills_root()` does not, because opencode's config
root is an XDG path and `~/.claude` is not; `opencode debug paths` reports
`$XDG_CONFIG_HOME/opencode` with it set. An empty value counts as unset, the
convention `colors_wanted` already follows.

`opencode_tool_dir` takes both variables as arguments for the reason
`colors_wanted` does: a threaded test binary cannot mutate the process
environment to reach one branch at a time.

The file name is load bearing and now pinned by a test. opencode builds each
tool id as the file name then the export, so `worklane.ts` plus eleven
`export const` lines is what makes them `worklane_add` through
`worklane_uncheck`. Renaming the file renames every tool and every
permission rule naming one.

The closing line is not the skills' "on their next session". opencode reads
its config once at startup and never reloads it, so a running one keeps the
tools it began with and the honest instruction is to restart it.

Nothing else has to be installed, which is worth saying because the file is
executable and reads as though it wants a toolchain. Criterion 6 asked the
command to name the plugin package and Bun as runtime requirements and both
are wrong: a copy in a project with no `node_modules` above it registered
all eleven tools on a machine with no `bun` on `PATH`. opencode is a Bun
binary and the import resolves inside it. The message says the opposite, and
the reasoning is on the ticket.

`install_each` is the outcome loop both commands now share, with the
compare-and-refuse invocation passed in: that line is the only part of an
outcome that has to name the command it came from. What each command says
after the loop stays with the command.

`every_tool_the_wrapper_exports_is_a_real_subcommand` guards the direction
that breaks at call time, a tool wrapping a command that has been renamed or
dropped. Deliberately not the reverse: the wrapper has no tool for `relate`,
`campaign`, `assign` or `tags`, so an agent holding the tools cannot reach
campaigns or relations at all, and a test asserting that gap would fail on a
decision nobody has taken rather than on a mistake. Its own ticket.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 14:14:14 +02:00

568 lines
23 KiB
Rust

//! 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. The tool file is executable
//! code and reaches opencode alone, so it gets its own command and its own root, but the
//! compare-and-refuse logic is the same and lives here. What it needs at runtime is
//! opencode and nothing else: it is loaded into opencode's own runtime, so neither Bun
//! nor `@opencode-ai/plugin` has to be installed for the import in it to resolve.
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 opencode tool definitions, the second kind of asset this binary carries.
///
/// Executable TypeScript rather than a document, and it reaches one agent where a skill
/// reaches both: opencode loads a `.ts` file from its tool directory and Claude Code has
/// no directory it scans for one, so this is not the artifact that would reach it. That
/// asymmetry is the whole reason it is its own command with its own root rather than a
/// flag on `install-skill`.
///
/// Flat in the root rather than in a directory of its own, and the file name is load
/// bearing: opencode builds each tool id as the file name then the export, so this file
/// is what makes them `worklane_add` and `worklane_mv` rather than `tool_add`. A skill
/// carries the equivalent in its frontmatter `name:`, which its directory has to agree
/// with; a tool carries it in the file name alone.
pub const TOOL: Asset = Asset {
name: "worklane",
what: "tool",
relative: "worklane.ts",
content: include_str!("../assets/TOOL.ts"),
};
/// Every tool this binary carries.
///
/// One, and an array anyway: it is what keeps the install loop the same shape as the
/// skills', so a second tool needs no new machinery. A `static` for the reason `SKILLS`
/// is one.
pub static TOOLS: [Asset; 1] = [TOOL];
/// 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::<Vec<_>>()
.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/<name>/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<PathBuf> {
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"))
}
/// Where the tool has to sit for opencode to load it in every project.
///
/// `XDG_CONFIG_HOME` when it is set and non-empty, `~/.config` otherwise, which is what
/// opencode itself resolves: `opencode debug paths` reports its config root under
/// `$XDG_CONFIG_HOME/opencode` with the variable set and `~/.config/opencode` without.
/// An empty value counts as unset, the convention `colors_wanted` already follows for
/// `NO_COLOR`. Checked against opencode 1.15.10.
///
/// Singular `tool`, though 1.15.10 loads `tools` as well: each was served in turn from a
/// directory outside any project and registered all eleven worklane tools. The singular
/// is the spelling opencode's own documentation puts first, the way it writes `agent(s)`
/// and `skill(s)`.
///
/// One agent, unlike `skills_root`. Claude Code has no path that belongs here at all: a
/// tool reaches it through an MCP server, which is a different artifact and not one this
/// binary carries.
pub fn tools_root() -> Result<PathBuf> {
let xdg = std::env::var_os("XDG_CONFIG_HOME");
let home = std::env::var_os("HOME");
opencode_tool_dir(xdg.as_deref().map(Path::new), home.as_deref().map(Path::new))
}
/// `tools_root` with the two variables passed in rather than read.
///
/// The seam exists for the reason `colors_wanted` has one: both branches and the failure
/// have to be reachable from a test, and a threaded test binary cannot mutate the process
/// environment to reach them one at a time.
fn opencode_tool_dir(xdg: Option<&Path>, home: Option<&Path>) -> Result<PathBuf> {
if let Some(xdg) = xdg.filter(|value| !value.as_os_str().is_empty()) {
return Ok(xdg.join("opencode/tool"));
}
let home = home.ok_or_else(|| {
anyhow!(
"cannot tell where your opencode config lives because neither XDG_CONFIG_HOME nor HOME is set in the environment"
)
})?;
Ok(home.join(".config/opencode/tool"))
}
#[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<Outcome> {
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<String> {
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<String> {
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<String> = 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; 4] = ["tui", "install-skill", "install-tool", "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:?}"
);
}
}
// ------------------------------------------------------------ the tool --
/// `XDG_CONFIG_HOME` wins, because it is what opencode itself resolves its config
/// root from: `opencode debug paths` reports `$XDG_CONFIG_HOME/opencode` with it set.
#[test]
fn the_tool_root_follows_xdg_config_home_when_it_is_set() {
let root = opencode_tool_dir(Some(Path::new("/tmp/xdg")), Some(Path::new("/home/x")));
assert_eq!(root.unwrap(), Path::new("/tmp/xdg/opencode/tool"));
}
/// An empty value counts as unset, the convention `colors_wanted` already follows, so
/// a wrapper script that cleared an inherited one still lands in the home directory
/// rather than at `/opencode/tool`.
#[test]
fn an_empty_xdg_config_home_falls_back_to_the_home_directory() {
let root = opencode_tool_dir(Some(Path::new("")), Some(Path::new("/home/x")));
assert_eq!(root.unwrap(), Path::new("/home/x/.config/opencode/tool"));
let unset = opencode_tool_dir(None, Some(Path::new("/home/x")));
assert_eq!(unset.unwrap(), Path::new("/home/x/.config/opencode/tool"));
}
/// Neither one set is the case that has to fail rather than guess: writing to a
/// relative `.config/opencode/tool` would put the tool wherever the caller happened
/// to be standing.
#[test]
fn neither_variable_set_is_an_error_rather_than_a_relative_path() {
let error = opencode_tool_dir(None, None).unwrap_err().to_string();
assert!(error.contains("XDG_CONFIG_HOME"), "{error}");
assert!(error.contains("HOME"), "{error}");
}
/// The file name is the tool id prefix, not decoration: opencode names each tool as
/// the file then the export, so a renamed file renames all eleven tools and every
/// permission rule that mentions one.
#[test]
fn the_tool_lands_flat_in_the_root_under_the_name_that_prefixes_its_ids() {
let root = opencode_tool_dir(None, Some(Path::new("/home/x"))).unwrap();
assert_eq!(TOOL.path(&root), Path::new("/home/x/.config/opencode/tool/worklane.ts"));
assert_eq!(TOOL.relative, "worklane.ts");
}
/// Every tool the file exports names a real subcommand.
///
/// The guard the fish completion lists already have, pointed the other way: this
/// catches a tool wrapping a command that has been renamed or dropped, which would
/// fail only when an agent finally called it. It cannot catch the reverse, a
/// subcommand the wrapper never grew a tool for, and the wrapper is behind by
/// several: `relate`, `campaign`, `assign` and `tags` have no tool. That is its own
/// ticket, and asserting it here would fail on a gap nobody has decided to close.
#[test]
fn every_tool_the_wrapper_exports_is_a_real_subcommand() {
use clap::CommandFactory;
let commands: Vec<String> = crate::Cli::command()
.get_subcommands()
.map(|command| command.get_name().to_string())
.collect();
let exported: Vec<&str> = TOOL
.content
.lines()
.filter_map(|line| line.strip_prefix("export const "))
.filter_map(|rest| rest.split_whitespace().next())
.collect();
assert_eq!(exported.len(), 11, "{exported:?}");
for name in exported {
assert!(
commands.iter().any(|command| command == name),
"the wrapper exports {name:?}, which is not a subcommand: {commands:?}"
);
}
}
}