From 9c5ec0c874ca472eba190ac40c81bb79c0d93eb3 Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Tue, 27 Oct 2026 18:36:52 -0700 Subject: [PATCH] Add the u key, skillz upgrade, and an installers list on install plans. u in the plugins list updates the package under the cursor through the existing update change: plan, progress, result. skillz upgrade updates every Claude and Codex plugin and marketplace, in the project and at user level, that the check does not show current. UpdateCheck gains can_tell so what cannot be checked (Codex) is always updated. An install plan now lists claude, codex and npx as boxes, and every box checked runs its own installer. From the list, a package's skills install with one npx run for the whole source instead of one per skill, and are no longer installed a second time next to the package's plugin. skillz install gets --npx, re-plans when the boxes change, and does not re-ask the pickers. --- DESIGN.md | 6 +- README.md | 18 +- .../src/agents/claude/update.rs | 6 +- crates/skillz-harness/src/update/check.rs | 6 + src/app/install/global.rs | 1 + src/app/install/mod.rs | 263 +++++++++++++++-- src/app/install/skills.rs | 35 +++ src/app/install/test_support.rs | 1 + src/app/install/tools.rs | 170 +++++++++++ src/app/mod.rs | 1 + src/app/review.rs | 37 ++- src/app/route.rs | 190 ++++++++++++ src/app/workspace.rs | 6 + src/cli/args.rs | 21 ++ src/cli/library/install.rs | 2 + src/cli/mod.rs | 3 +- src/cli/run.rs | 16 +- src/cli/session/change.rs | 24 +- src/cli/session/change/provenance_tests.rs | 2 + src/cli/session/change/scope_tests.rs | 8 + src/cli/session/change/selection_tests.rs | 120 ++++++++ src/cli/session/change/update_tests.rs | 20 ++ src/cli/session/perform.rs | 3 + src/cli/session/selection.rs | 20 +- src/cli/session/source_install.rs | 1 + src/cli/upgrade.rs | 279 ++++++++++++++++++ src/tui/keymap.rs | 2 + src/tui/plan.rs | 52 +++- src/tui/workspace/plugins/keys.rs | 14 + src/tui/workspace/plugins/tests.rs | 62 ++++ tests/conformance.rs | 1 + tests/install.rs | 1 + tests/update.rs | 21 +- 33 files changed, 1359 insertions(+), 53 deletions(-) create mode 100644 src/app/install/tools.rs create mode 100644 src/app/route.rs create mode 100644 src/cli/upgrade.rs diff --git a/DESIGN.md b/DESIGN.md index 8bd6fc7..10f4dc7 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -145,7 +145,11 @@ open groups by their ancestor paths so matching labels in other branches stay in Plain `list QUERY` prints matching items. Browsing is explicit with `list -i`. Whether an installed item has a newer version is asked only by `update --check` and `list --check`; the -list does not mark updates yet. The README owns key tables and command examples. +list does not mark updates yet. An install lists its installers (each agent's plugin installer and `npx skills`) as boxes on the +plan, and every box checked runs (`app::route` for the list, `install::tools` for a source). +`upgrade` runs `update` over the plugins of both levels that +the check does not show current: a plugin is as current as its marketplace, and an item the +check cannot judge (`UpdateCheck::can_tell`, today every Codex one) is always updated. The README owns key tables and command examples. ## Extension and tests diff --git a/README.md b/README.md index a300a60..ae3f475 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ is also a command. | `list` (`ls`) | in a terminal, a plain `list` (or `list -g`) opens the plugins list (see Workspace); otherwise (a query, `--all`, a kind filter, no terminal) it shows what is installed as a tree, or browse it with `-i`; `--json` never opens the list and prints the items for scripts and agents, adding each item's location (`--check` also whether a newer version exists); `--available` lists the library items the project (`-g`: the user) lacks | | `uninstall` (`rm`, `delete`) | fuzzy match, pick, confirm, remove completely; several queries go in one plan | | `update` | update installed items with the tool that installed them (`-g`: the user's); `--check` lists the ones with a newer version (`--json` for scripts) | +| `upgrade` | update every Claude and Codex plugin and marketplace, in the project (`-p`) and at user level, that has a newer version; what cannot be checked (Codex) is updated anyway; `--dry-run` shows the plans, `-y` skips the questions, and `SKILLZ_NO_UPDATE_CHECK` updates everything | | `reset` | remove every skill, plugin and marketplace in scope | | `prune` | find duplicate and unused skills and plugins, remove the ones picked | | `doctor` | check the skills on disk, read-only: names that collide (per tool, listing every copy), skill files nested or loose where a tool will not look (or looks too hard), files that break the format, and broken links; `-g` for the user's skills only, `--json` for scripts | @@ -78,6 +79,18 @@ skills`. A malformed marketplace or plugin manifest in the source never fails th skills install loose instead. `library install` and profile applies still install a loose skill entry with `npx skills`, not through the plugin its source may offer. +An install's plan starts with the installers it runs, each a box: `claude`, `codex` and `npx`. +`space` flips the one under the cursor and the plan is made again; every box checked runs its own +installer, so with all three the source's plugins go in through Claude and Codex and `npx skills` +installs its skills as well. `claude` and `codex` start checked (`--agent` narrows them) and `npx` +does not (`--npx` checks it): it takes every skill of the source in one run, or only those named +with `--skill`, and skips nothing. The exception is a source with no plugin for an agent, whose +skills still go through `npx skills` as before; the box then shows checked, and unchecking it +leaves that agent out. Installing a package from `skillz list` follows the same boxes: its +plugins go in through the agents checked, and its skills through one `npx skills` run for the +source, never one run per skill, with `npx` checked at the start only for a package that has +skills and no plugin. + A Codex project install writes the marketplace and plugin into `.codex/config.toml`, which a team usually commits, so skillz refuses a source with a user, password or token in its URL (use ssh or a credential helper; this includes a bare `https://user@` account), and a local source is written @@ -107,7 +120,7 @@ the same install and removal steps). What the list does not do is a command too: | What is installed, the split, where each item lives | `list`, `list -g`, `list --json` (`location`) | | `space` selects, `enter` submits installs and removals as one plan | `install SOURCE`, `uninstall QUERY...` (`-y`, `--dry-run`) | | `i` info: provenance and locations | `list --json` (`location`), `library list --json` | -| Updating | `update [QUERY] [-g]`, `update --check [--json]` | +| Updating | `update [QUERY] [-g]`, `update --check [--json]`, `upgrade [-p DIR] [--dry-run] [-y]` | | Applying and comparing a profile | `use NAME [--exact] [-g]`, `profile status [NAME] [--json]`, `profile list` | | Saving the project as a profile, editing profiles | `profile save`, `profile new`, `profile add` / `profile remove`, `profile delete` | | Clearing the project | `reset` removes skills, plugins and marketplaces; add `--hooks`, `--mcp`, `--subagents` for those kinds | @@ -311,7 +324,7 @@ files are not in it yet. lives on disk. - `/` filters. -There are no tabs: updating, removing by query, profiles and library editing are commands (see +There are no tabs: updating everything or by query, removing by query, profiles and library editing are commands (see the table above). | Key | Does | @@ -320,6 +333,7 @@ the table above). | `enter` | submit everything selected as one change, after a plan to review | | `esc` | drop the selection (with none, clear the filter) | | `i` | info: where the package comes from and where each installed item lives | +| `u` | update the installed package under the cursor, after a plan to review | | `/` | filter; keeps matching rows, `esc` clears it | | `↑↓` `j` `k`, `PgUp` `PgDn`, `^u` `^d`, `g` `G` | move | | `?` | all keys for the screen | diff --git a/crates/skillz-harness/src/agents/claude/update.rs b/crates/skillz-harness/src/agents/claude/update.rs index b5d67d5..629a05d 100644 --- a/crates/skillz-harness/src/agents/claude/update.rs +++ b/crates/skillz-harness/src/agents/claude/update.rs @@ -29,8 +29,12 @@ pub struct ClaudeMarketplaces { } impl UpdateCheck for ClaudeMarketplaces { + fn can_tell(&self, item: &Installed) -> bool { + (item.kind, item.installer) == (Kind::Marketplace, Installer::ClaudeCli) + } + fn available(&self, item: &Installed) -> bool { - if (item.kind, item.installer) != (Kind::Marketplace, Installer::ClaudeCli) { + if !self.can_tell(item) { return false; } let Some(clone) = self.clone_of(&item.name) else { diff --git a/crates/skillz-harness/src/update/check.rs b/crates/skillz-harness/src/update/check.rs index 62c7458..81f5c52 100644 --- a/crates/skillz-harness/src/update/check.rs +++ b/crates/skillz-harness/src/update/check.rs @@ -5,6 +5,8 @@ use crate::model::Installed; pub trait UpdateCheck: Send + Sync { fn available(&self, item: &Installed) -> bool; + /// Whether `available` is a real answer for `item` rather than the default of no update. + fn can_tell(&self, item: &Installed) -> bool; } /// Reports no update for anything: the check is switched off. @@ -14,6 +16,10 @@ impl UpdateCheck for NoCheck { fn available(&self, _item: &Installed) -> bool { false } + + fn can_tell(&self, _item: &Installed) -> bool { + false + } } /// Whether any copy of `item` has a newer version. diff --git a/src/app/install/global.rs b/src/app/install/global.rs index 99df962..236409f 100644 --- a/src/app/install/global.rs +++ b/src/app/install/global.rs @@ -113,6 +113,7 @@ mod tests { agents: vec![Agent::Claude], scope: Scope::Global, selection: super::super::SkillSelection::All, + npx: false, }; let context = Ctx { adapters: &adapters, diff --git a/src/app/install/mod.rs b/src/app/install/mod.rs index b860567..e3e4812 100644 --- a/src/app/install/mod.rs +++ b/src/app/install/mod.rs @@ -4,11 +4,13 @@ mod global; mod skills; #[cfg(test)] pub(crate) mod test_support; +mod tools; use std::path::{Path, PathBuf}; +use self::tools::{Remembering, Tools}; use crate::app::prompt::Prompter; -use crate::app::review::{Group, PlanView, Verdict}; +use crate::app::review::{Group, PlanView, Targets, Verdict}; use skillz_harness::action::{self, Action}; use skillz_harness::agent_skills::skill_names_under; use skillz_harness::agents::{Harness, PluginOffer, adapter_for}; @@ -36,6 +38,9 @@ pub struct InstallRequest { pub agents: Vec, pub scope: Scope, pub selection: SkillSelection, + /// Run `npx skills` for the source's skills next to the agents' plugin installers. It takes + /// every skill, or the ones `Patterns` names. + pub npx: bool, } /// What an install talks to: the registered agents and the outside world. @@ -53,45 +58,83 @@ struct Tree<'a> { } /// What an install will do, shown for approval before anything runs. +#[derive(Default)] struct Plan { lines: Vec, steps: Vec, /// Agents that refused the install, with why. skipped: Vec, + /// Some agent got the source's skills through `npx skills` because it offers no plugin. + fell_back: bool, } -/// `true` when the plan was approved and ran. +/// `true` when the plan was approved and ran. The plan lists the installers it runs, each of +/// which the user may check or not, and is made again when they change. pub fn install(ctx: &Ctx, req: &InstallRequest) -> anyhow::Result { skillz_harness::clone::with_source(&req.source, &req.cwd, ctx.runner, |src, source| { let tree = Tree { src, source }; - let Some(plan) = plan(ctx, req, &tree)? else { - return Ok(false); + let remembering = Remembering::new(ctx.prompter); + let ctx = Ctx { + prompter: &remembering, + ..*ctx + }; + let every: Vec = ctx.adapters.iter().map(|a| a.agent()).collect(); + let mut tools = Tools { + agents: req.agents.clone(), + npx: req.npx, + fallback: true, }; - let view = PlanView { - heading: format!("Install from {source}"), - groups: [(Group::Install, plan.lines), (Group::Skip, plan.skipped)] + let mut first = true; + loop { + let asked = InstallRequest { + agents: tools.agents.clone(), + npx: tools.npx, + ..req.clone() + }; + let plan = match plan(&ctx, &asked, &tree, (&tools, first))? { + Some(plan) => plan, + None if first => return Ok(false), + None => Plan::default(), + }; + first = false; + let view = PlanView { + heading: format!("Install from {source}"), + groups: [ + (Group::Install, plan.lines.clone()), + (Group::Skip, plan.skipped.clone()), + ] .into_iter() .filter(|(_, lines)| !lines.is_empty()) .collect(), - steps: plan.steps.iter().map(Action::describe).collect(), - targets: None, - }; - match ctx.prompter.plan(&view)? { - Verdict::Apply => run(ctx, &plan.steps).map(|()| true), - Verdict::DryRun | Verdict::Cancel | Verdict::Retarget(_) => Ok(false), + steps: plan.steps.iter().map(Action::describe).collect(), + targets: Some(Targets::installers( + every.clone(), + &tools.agents, + tools.npx || plan.fell_back, + )), + }; + match ctx.prompter.plan(&view)? { + Verdict::Apply if plan.steps.is_empty() => return Ok(false), + Verdict::Apply => return run(&ctx, &plan.steps).map(|()| true), + Verdict::Retarget(chosen) => tools = tools.after(&chosen, plan.fell_back), + Verdict::DryRun | Verdict::Cancel => return Ok(false), + } } }) } /// Each requested agent installs the source's plugins through its own installer when it offers -/// any; the agents left over install the source's skills with `npx skills`. `None` when the -/// user picked nothing. -fn plan(ctx: &Ctx, req: &InstallRequest, tree: &Tree) -> anyhow::Result> { - let mut plan = Plan { - lines: vec![], - steps: vec![], - skipped: vec![], - }; +/// any. With `npx` checked, `npx skills` also installs the source's skills; without, the agents +/// that were offered no plugin install them that way while `tools.fallback` stands. `None` when +/// the user picked nothing. `first` is the plan before the user changed anything: one that +/// leaves nothing to do is an error then, and a plan to change afterwards. +fn plan( + ctx: &Ctx, + req: &InstallRequest, + tree: &Tree, + (tools, first): (&Tools, bool), +) -> anyhow::Result> { + let mut plan = Plan::default(); let mut rest = vec![]; for &agent in &req.agents { match agent_plugins(ctx, req, tree, agent)? { @@ -104,19 +147,38 @@ fn plan(ctx: &Ctx, req: &InstallRequest, tree: &Tree) -> anyhow::Result rest.push(agent), } } - if !rest.is_empty() - && let Some(skills) = skills::plan(ctx, req, tree, &rest)? - { - plan.lines.push(skills.line); - plan.steps.push(skills.step); + if req.npx { + let every: Vec = ctx.adapters.iter().map(|a| a.agent()).collect(); + let agents = if req.agents.is_empty() { + &every + } else { + &req.agents + }; + let all = skills::plan_all(ctx, req, tree, agents)?; + plan.lines.push(all.line); + plan.steps.push(all.step); + } else if tools.fallback { + if !rest.is_empty() + && let Some(skills) = skills::plan(ctx, req, tree, &rest)? + { + plan.lines.push(skills.line); + plan.steps.push(skills.step); + plan.fell_back = true; + } + } else { + plan.skipped.extend( + rest.iter().map(|agent| { + format!("{agent}: no plugin in this source, check npx for its skills") + }), + ); } // Every agent refusing leaves nothing to approve, so say why instead of doing nothing. anyhow::ensure!( - !plan.steps.is_empty() || plan.skipped.is_empty(), + !first || !plan.steps.is_empty() || plan.skipped.is_empty(), "{}", plan.skipped.join("; ") ); - Ok((!plan.steps.is_empty()).then_some(plan)) + Ok((!plan.steps.is_empty() || !first).then_some(plan)) } /// What one agent does with the plugins a source offers. @@ -252,7 +314,7 @@ mod tests { fx: &Fixture, req: &InstallRequest, runner: &FakeRunner, - prompter: &ScriptedPrompter, + prompter: &dyn Prompter, ) -> anyhow::Result { let adapters = registry(); let ctx = Ctx { @@ -558,6 +620,149 @@ mod tests { } } + fn npx_args(runner: &FakeRunner) -> Vec> { + let calls = runner.calls(); + calls + .into_iter() + .filter(|call| call.0 == "npx") + .map(|call| call.1) + .collect() + } + + fn skill_flags(args: &[String]) -> Vec<&String> { + args.windows(2) + .filter(|pair| pair[0] == "--skill") + .map(|pair| &pair[1]) + .collect() + } + + #[test] + fn checking_npx_installs_every_skill_next_to_the_plugins() { + let fx = project_with(mattpocock_fixture); + let runner = FakeRunner::new(|_| {}); + let request = InstallRequest { + agents: vec![Agent::Claude, Agent::Codex], + npx: true, + ..req(&fx, "repo", SkillSelection::Interactive) + }; + + run_install(&fx, &request, &runner, &ScriptedPrompter::new(&[0], true)).unwrap(); + + let npx = npx_args(&runner); + assert_eq!(npx.len(), 1); + assert_eq!(skill_flags(&npx[0]), ["*"]); + assert!(runner.calls().iter().any(|call| call.0 == "claude")); + } + + #[test] + fn checking_npx_with_skills_named_installs_those_only() { + let fx = project_with(mattpocock_fixture); + let runner = FakeRunner::new(|_| {}); + let request = InstallRequest { + npx: true, + ..req(&fx, "repo", SkillSelection::Patterns(s(&["tdd"]))) + }; + + run_install(&fx, &request, &runner, &ScriptedPrompter::new(&[], true)).unwrap(); + + assert_eq!(skill_flags(&npx_args(&runner)[0]), ["tdd"]); + } + + /// Changes what the first plan offers, then approves the next; notes every question and the + /// `npx` box each plan showed. + struct ChangesOnce { + change: fn(&mut Targets), + questions: std::cell::Cell, + plans: std::cell::RefCell>>, + } + + impl ChangesOnce { + fn new(change: fn(&mut Targets)) -> Self { + ChangesOnce { + change, + questions: Default::default(), + plans: Default::default(), + } + } + } + + impl Prompter for ChangesOnce { + fn multi_select(&self, _title: &str, _options: &[String]) -> anyhow::Result> { + self.questions.set(self.questions.get() + 1); + Ok(vec![0]) + } + + fn confirm(&self, _question: &str) -> anyhow::Result { + Ok(true) + } + + fn plan(&self, view: &PlanView) -> anyhow::Result { + let mut targets = view + .targets + .clone() + .expect("an install offers its installers"); + self.plans.borrow_mut().push(targets.npx); + if self.plans.borrow().len() > 1 { + return Ok(Verdict::Apply); + } + (self.change)(&mut targets); + Ok(Verdict::Retarget(targets)) + } + } + + #[test] + fn checking_npx_on_the_plan_makes_it_again_without_asking_the_picks_twice() { + let fx = project_with(mattpocock_fixture); + let runner = FakeRunner::new(|_| {}); + let prompter = ChangesOnce::new(|targets| targets.npx = Some(true)); + let request = InstallRequest { + agents: vec![Agent::Claude], + ..req(&fx, "repo", SkillSelection::Interactive) + }; + + let ran = run_install(&fx, &request, &runner, &prompter); + + assert!(ran.unwrap()); + assert_eq!(*prompter.plans.borrow(), [Some(false), Some(true)]); + assert_eq!(prompter.questions.get(), 1); + assert_eq!(npx_args(&runner).len(), 1); + } + + #[test] + fn skills_without_a_plugin_show_npx_checked_and_unchecking_it_installs_nothing() { + let fx = project_with(|root| skill(root, "skills/tdd")); + let runner = FakeRunner::new(|_| {}); + let prompter = ChangesOnce::new(|targets| targets.npx = Some(false)); + let request = InstallRequest { + agents: vec![Agent::Claude], + ..req(&fx, "repo", SkillSelection::All) + }; + + let ran = run_install(&fx, &request, &runner, &prompter); + + assert!(!ran.unwrap()); + assert_eq!(*prompter.plans.borrow(), [Some(true), Some(false)]); + assert!(runner.calls().iter().all(|call| call.0 != "npx")); + } + + #[test] + fn leaving_the_fallback_checked_still_picks_skills_by_name() { + let fx = project_with(|root| skill(root, "skills/tdd")); + let runner = FakeRunner::new(|_| {}); + let prompter = ChangesOnce::new(|targets| targets.agents[1].1 = false); + let request = InstallRequest { + agents: vec![Agent::Claude, Agent::Codex], + ..req(&fx, "repo", SkillSelection::Patterns(s(&["tdd"]))) + }; + + run_install(&fx, &request, &runner, &prompter).unwrap(); + + let npx = npx_args(&runner); + assert_eq!(skill_flags(&npx[0]), ["tdd"]); + assert!(npx[0].contains(&"claude-code".to_string())); + assert!(!npx[0].contains(&"codex".to_string())); + } + #[test] fn selecting_a_skill_installs_only_its_owning_plugin() { let fx = project_with(|root| { diff --git a/src/app/install/skills.rs b/src/app/install/skills.rs index 3d4b84c..493c09f 100644 --- a/src/app/install/skills.rs +++ b/src/app/install/skills.rs @@ -42,6 +42,41 @@ pub(super) fn plan( })) } +/// `npx skills add ` for every skill the source has, or the ones named with `--skill`. +/// Nothing is left out and nothing is asked: the user checked `npx` to have it all. +pub(super) fn plan_all( + ctx: &Ctx, + req: &InstallRequest, + tree: &Tree, + agents: &[Agent], +) -> anyhow::Result { + let names = skill_names_under(tree.src)?; + anyhow::ensure!( + !names.is_empty(), + "found no marketplace, plugin or skills in {}", + tree.source + ); + let (chosen, what) = match &req.selection { + SkillSelection::Patterns(_) => { + let chosen = select_skills(&names, &req.selection); + anyhow::ensure!( + !chosen.is_empty(), + "no skills to install from {}", + tree.source + ); + let what = format!("skills {}", chosen.join(", ")); + (chosen, what) + } + _ => (vec!["*".to_string()], "all skills".to_string()), + }; + let (program, args) = commands::add_command(tree.source, &chosen, agents, req.scope); + let agents: Vec = agents.iter().map(ToString::to_string).collect(); + Ok(SkillsPlan { + line: format!("npx for {}: {what}", agents.join(", ")), + step: Action::required(&program, args, &ctx.env.project), + }) +} + /// The skills to install, or `None` when the user backed out. fn choose( prompter: &dyn Prompter, diff --git a/src/app/install/test_support.rs b/src/app/install/test_support.rs index 108e3d4..fa78772 100644 --- a/src/app/install/test_support.rs +++ b/src/app/install/test_support.rs @@ -67,5 +67,6 @@ pub fn req(fx: &Fixture, source: &str, selection: SkillSelection) -> InstallRequ agents: vec![Agent::Claude], scope: Scope::Project, selection, + npx: false, } } diff --git a/src/app/install/tools.rs b/src/app/install/tools.rs new file mode 100644 index 0000000..a3379bd --- /dev/null +++ b/src/app/install/tools.rs @@ -0,0 +1,170 @@ +//! The installers an install runs, as the user changes them on the plan: each agent's own +//! plugin installer, and `npx skills`. + +use std::cell::RefCell; +use std::collections::HashMap; + +use crate::app::prompt::{Choice, Picked}; +use crate::app::prompt::{Hold, Prompter}; +use crate::app::review::{ItemEvent, Next, Outcome, PlanView, Progress, Targets, Verdict}; +use crate::app::tree::Node; +use skillz_harness::model::Agent; + +/// Which installers the plan is made for. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Tools { + pub agents: Vec, + /// `npx skills` takes every skill the user asked for; checked on the plan. + pub npx: bool, + /// An agent whose source offers no plugin gets the source's skills through `npx skills`, + /// as it always has, until the user has taken `npx` off the plan. + pub fallback: bool, +} + +impl Tools { + /// What the user's choice on the plan makes of the tools, given whether the plan showed + /// `npx` checked only because of the fallback. + pub fn after(&self, chosen: &Targets, shown_by_fallback: bool) -> Tools { + let wants_npx = chosen.npx_on(); + Tools { + agents: chosen.checked(), + // Leaving a fallback box checked keeps the fallback: it picks skills, `npx` takes all. + npx: wants_npx && !shown_by_fallback, + fallback: self.fallback && !(shown_by_fallback && !wants_npx), + } + } +} + +/// Remembers the answers to the questions asked while planning, so changing the installers on +/// the plan does not ask the same question again. +pub(super) struct Remembering<'a> { + asks: &'a dyn Prompter, + picked: RefCell>>, + confirmed: RefCell>, +} + +impl<'a> Remembering<'a> { + pub fn new(asks: &'a dyn Prompter) -> Self { + Remembering { + asks, + picked: RefCell::default(), + confirmed: RefCell::default(), + } + } +} + +impl Prompter for Remembering<'_> { + fn multi_select(&self, title: &str, options: &[String]) -> anyhow::Result> { + let key = format!("{title}\u{0}{}", options.join("\u{0}")); + if let Some(picked) = self.picked.borrow().get(&key) { + return Ok(picked.clone()); + } + let picked = self.asks.multi_select(title, options)?; + self.picked.borrow_mut().insert(key, picked.clone()); + Ok(picked) + } + + fn confirm(&self, question: &str) -> anyhow::Result { + if let Some(answer) = self.confirmed.borrow().get(question) { + return Ok(*answer); + } + let answer = self.asks.confirm(question)?; + self.confirmed + .borrow_mut() + .insert(question.to_string(), answer); + Ok(answer) + } + + fn select_items(&self, title: &str, nodes: &[Node]) -> anyhow::Result> { + self.asks.select_items(title, nodes) + } + + fn browse(&self, title: &str, groups: &[Node]) -> anyhow::Result> { + self.asks.browse(title, groups) + } + + fn hold(&self) -> Hold<'_> { + self.asks.hold() + } + + fn plan(&self, view: &PlanView) -> anyhow::Result { + self.asks.plan(view) + } + + fn progress(&self, title: &str, total: usize) -> Box { + self.asks.progress(title, total) + } + + fn live(&self, title: &str, total: usize, planned: &[ItemEvent]) -> Box { + self.asks.live(title, total, planned) + } + + fn outcome(&self, title: &str, outcome: &Outcome) -> anyhow::Result { + self.asks.outcome(title, outcome) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::app::install::test_support::ScriptedPrompter; + + const BOTH: [Agent; 2] = [Agent::Claude, Agent::Codex]; + + fn tools(npx: bool, fallback: bool) -> Tools { + Tools { + agents: BOTH.to_vec(), + npx, + fallback, + } + } + + fn chosen(agents: &[Agent], npx: bool) -> Targets { + Targets::installers(BOTH.to_vec(), agents, npx) + } + + #[test] + fn checking_npx_makes_it_take_every_skill() { + let next = tools(false, true).after(&chosen(&BOTH, true), false); + + assert_eq!(next, tools(true, true)); + } + + #[test] + fn a_fallback_box_left_checked_keeps_picking_skills_and_unchecking_it_stops_the_fallback() { + let kept = tools(false, true).after(&chosen(&[Agent::Claude], true), true); + let dropped = tools(false, true).after(&chosen(&BOTH, false), true); + + assert_eq!( + kept, + Tools { + agents: vec![Agent::Claude], + npx: false, + fallback: true + } + ); + assert_eq!(dropped, tools(false, false)); + } + + #[test] + fn unchecking_npx_that_was_checked_takes_it_off() { + let next = tools(true, true).after(&chosen(&BOTH, false), false); + + assert_eq!(next, tools(false, true)); + } + + #[test] + fn a_question_asked_again_gets_the_answer_given_before() { + let asks = ScriptedPrompter::new(&[1], true); + let remembering = Remembering::new(&asks); + let options = vec!["a".to_string(), "b".to_string()]; + + let first = remembering.multi_select("pick", &options).unwrap(); + let again = remembering.multi_select("pick", &options).unwrap(); + remembering.confirm("sure?").unwrap(); + remembering.confirm("sure?").unwrap(); + + assert_eq!((first, again), (vec![1], vec![1])); + assert_eq!(asks.offered.borrow().len(), 1); + } +} diff --git a/src/app/mod.rs b/src/app/mod.rs index 6fc6a1d..11ea18b 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -17,6 +17,7 @@ pub mod prompt; pub mod prune; pub(crate) mod remove; pub mod review; +pub mod route; pub mod rule; pub(crate) mod snapshot; pub(crate) mod spinner; diff --git a/src/app/review.rs b/src/app/review.rs index 54a5c89..b7c5250 100644 --- a/src/app/review.rs +++ b/src/app/review.rs @@ -83,6 +83,9 @@ pub struct Listed { pub struct Targets { /// Empty when the plan reaches no more than one agent: there is nothing to choose. pub agents: Vec<(Agent, bool)>, + /// Whether `npx skills` is one of the installers, when the plan installs and so offers it. + /// A box after the agents. + pub npx: Option, pub items: Vec, pub cursor: usize, /// Items the user unchecked that the plan stopped listing (narrowing the agents hid them): @@ -99,12 +102,38 @@ impl Targets { }; Targets { agents: offered.into_iter().map(|agent| (agent, true)).collect(), + npx: None, items: vec![], cursor: 0, left_out: vec![], } } + /// The installers an install may run: each of `offered` checked when it is in `checked`, + /// and `npx skills`. They are always offered, even for a single agent. + pub fn installers(offered: Vec, checked: &[Agent], npx: bool) -> Self { + Targets { + agents: offered + .into_iter() + .map(|agent| (agent, checked.contains(&agent))) + .collect(), + npx: Some(npx), + items: vec![], + cursor: 0, + left_out: vec![], + } + } + + /// Whether `npx skills` is checked. + pub fn npx_on(&self) -> bool { + self.npx == Some(true) + } + + /// Where the items start among the lines the cursor can rest on. + pub fn items_from(&self) -> usize { + self.agents.len() + usize::from(self.npx.is_some()) + } + pub fn checked(&self) -> Vec { self.agents .iter() @@ -120,7 +149,7 @@ impl Targets { /// How many lines the cursor can rest on. pub fn rows(&self) -> usize { - self.agents.len() + self.items.len() + self.items_from() + self.items.len() } /// Whether the item called `id` is left in the plan; one the plan does not list is. @@ -159,10 +188,12 @@ impl Targets { } pub fn toggled(mut self) -> Self { - let agents = self.agents.len(); + let items = self.items_from(); if let Some((_, on)) = self.agents.get_mut(self.cursor) { *on = !*on; - } else if let Some(pick) = self.items.get_mut(self.cursor - agents) { + } else if self.cursor < items { + self.npx = self.npx.map(|on| !on); + } else if let Some(pick) = self.items.get_mut(self.cursor - items) { pick.on = !pick.on; } self diff --git a/src/app/route.rs b/src/app/route.rs new file mode 100644 index 0000000..a77a9c8 --- /dev/null +++ b/src/app/route.rs @@ -0,0 +1,190 @@ +//! Which installer each entry of a batch goes through. Each box the user checks runs its own +//! method: an agent runs its own plugin installer, `npx` runs `npx skills` once for the whole +//! source. A skill is only ever installed by `npx`, so unchecking it leaves skills out rather +//! than doing them a second time next to a plugin. + +use skillz_harness::Spec; +use skillz_harness::model::Agent; + +/// `npx skills` takes every skill the source has. +const EVERY_SKILL: &str = "*"; + +/// Whether `npx` starts checked: some skill has no plugin of the same source to install it, so +/// without `npx` nothing would. +pub fn npx_by_default(entries: &[Spec]) -> bool { + entries.iter().any(|entry| match entry { + Spec::Skill { source, .. } => !entries.iter().any(|other| plugin_from(other, source)), + _ => false, + }) +} + +fn plugin_from(entry: &Spec, from: &str) -> bool { + matches!(entry, Spec::Plugin { source, .. } if source == from) +} + +/// `entries` as the checked installers would run them. Plugins and the other kinds keep to the +/// checked agents, an entry that names its own agents to those. With `npx`, each source gets +/// one install of all its skills in place of its separate skill entries, for the checked agents +/// (every agent when none is checked). +pub fn routed(entries: Vec, (checked, every): (&[Agent], &[Agent]), npx: bool) -> Vec { + let mut sources: Vec = vec![]; + let mut routed: Vec = vec![]; + for entry in entries { + if let Spec::Skill { source, .. } | Spec::Plugin { source, .. } = &entry + && npx + && !sources.contains(source) + { + sources.push(source.clone()); + } + if matches!(entry, Spec::Skill { .. }) { + continue; + } + if let Some(entry) = narrowed(entry, checked) { + routed.push(entry); + } + } + let targets = match checked.is_empty() { + true => every, + false => checked, + }; + routed.extend(sources.into_iter().map(|source| Spec::Skill { + source, + names: vec![EVERY_SKILL.into()], + agents: targets.to_vec(), + })); + routed +} + +/// `entry` for the `chosen` agents it names, or all of them when it names none; `None` when none +/// of its own are chosen. +fn narrowed(entry: Spec, chosen: &[Agent]) -> Option { + if entry.agents().is_empty() { + return (!chosen.is_empty()).then(|| entry.with_agents(chosen.to_vec())); + } + let own: Vec = entry + .agents() + .iter() + .copied() + .filter(|agent| chosen.contains(agent)) + .collect(); + (!own.is_empty()).then(|| entry.with_agents(own)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const BOTH: [Agent; 2] = [Agent::Claude, Agent::Codex]; + + fn skill(source: &str, name: &str) -> Spec { + Spec::Skill { + source: source.into(), + names: vec![name.into()], + agents: vec![], + } + } + + fn plugin(source: &str, name: &str, agents: Vec) -> Spec { + Spec::Plugin { + source: source.into(), + marketplace: "mp".into(), + name: name.into(), + agents, + } + } + + fn all_skills(source: &str, agents: &[Agent]) -> Spec { + Spec::Skill { + source: source.into(), + names: vec!["*".into()], + agents: agents.to_vec(), + } + } + + #[test] + fn skills_without_a_plugin_start_with_npx_checked_and_the_rest_without() { + let loose = [skill("o/r", "a"), skill("o/r", "b")]; + let both = [skill("o/r", "a"), plugin("o/r", "p", vec![])]; + let elsewhere = [skill("o/r", "a"), plugin("x/y", "p", vec![])]; + + assert!(npx_by_default(&loose)); + assert!(!npx_by_default(&both)); + assert!(npx_by_default(&elsewhere)); + assert!(!npx_by_default(&[plugin("o/r", "p", vec![])])); + } + + #[test] + fn without_npx_a_package_installs_its_plugin_and_not_its_skills_a_second_time() { + let entries = vec![skill("o/r", "a"), plugin("o/r", "p", vec![])]; + + let routed = routed(entries, (&BOTH, &BOTH), false); + + assert_eq!(routed, [plugin("o/r", "p", BOTH.to_vec())]); + } + + #[test] + fn with_npx_each_source_installs_all_its_skills_once() { + let entries = vec![ + skill("o/r", "a"), + skill("o/r", "b"), + skill("o/r", "c"), + skill("x/y", "d"), + ]; + + let routed = routed(entries, (&BOTH, &BOTH), true); + + assert_eq!(routed, [all_skills("o/r", &BOTH), all_skills("x/y", &BOTH)]); + } + + #[test] + fn with_everything_checked_each_installer_runs() { + let entries = vec![skill("o/r", "a"), plugin("o/r", "p", vec![])]; + + let routed = routed(entries, (&BOTH, &BOTH), true); + + assert_eq!( + routed, + [plugin("o/r", "p", BOTH.to_vec()), all_skills("o/r", &BOTH)] + ); + } + + #[test] + fn an_unchecked_agent_gets_no_plugin_and_no_skills() { + let entries = vec![skill("o/r", "a"), plugin("o/r", "p", vec![])]; + + let routed = routed(entries, (&[Agent::Codex], &BOTH), true); + + assert_eq!( + routed, + [ + plugin("o/r", "p", vec![Agent::Codex]), + all_skills("o/r", &[Agent::Codex]) + ] + ); + } + + #[test] + fn a_plugin_that_names_other_agents_than_the_checked_ones_is_dropped() { + let entries = vec![plugin("o/r", "p", vec![Agent::Claude])]; + + let routed = routed(entries, (&[Agent::Codex], &BOTH), false); + + assert!(routed.is_empty()); + } + + #[test] + fn npx_with_no_agent_checked_reaches_every_agent_and_nothing_else_runs() { + let entries = vec![skill("o/r", "a"), plugin("o/r", "p", vec![])]; + + let routed = routed(entries, (&[], &BOTH), true); + + assert_eq!(routed, [all_skills("o/r", &BOTH)]); + } + + #[test] + fn with_nothing_checked_nothing_is_installed() { + let entries = vec![skill("o/r", "a"), plugin("o/r", "p", vec![])]; + + assert!(routed(entries, (&[], &BOTH), false).is_empty()); + } +} diff --git a/src/app/workspace.rs b/src/app/workspace.rs index 1705561..f67b426 100644 --- a/src/app/workspace.rs +++ b/src/app/workspace.rs @@ -20,6 +20,12 @@ pub enum Act { install: Vec, remove: Vec, }, + /// Bring the installed items with these ids to their latest version, as one plan, in + /// `scope`. + Update { + scope: Scope, + ids: Vec, + }, } /// What the list shows: a snapshot of the project, the user's installs and the library, read diff --git a/src/cli/args.rs b/src/cli/args.rs index 4191c25..b795f5d 100644 --- a/src/cli/args.rs +++ b/src/cli/args.rs @@ -31,6 +31,8 @@ pub enum Command { Uninstall(UninstallArgs), /// Update installed items with the tool that installed them (`--check` only lists the ones with a newer version) Update(UpdateArgs), + /// Update every Claude and Codex plugin, in the project and at user level, that has a newer version + Upgrade(UpgradeArgs), /// Remove every skill, plugin and marketplace in scope (hooks, MCP servers and subagents only when asked: `--hooks`, `--mcp`, `--subagents`) Reset(ResetArgs), /// Find duplicate skills and skills/plugins unused for 7+ days, then remove the ones picked @@ -159,6 +161,19 @@ pub struct UpdateArgs { pub json: bool, } +#[derive(Debug, Args)] +pub struct UpgradeArgs { + /// Project directory (default: cwd) + #[arg(short = 'p', long)] + pub project: Option, + /// Don't prompt + #[arg(short, long)] + pub yes: bool, + /// Print the update plans without changing anything + #[arg(long)] + pub dry_run: bool, +} + #[derive(Debug, Args)] pub struct ResetArgs { /// Project directory (default: the current one). With `-g`, only global unless given. @@ -242,6 +257,9 @@ pub struct InstallArgs { /// Skill names or globs, comma separated (e.g. `tdd,*commit`) #[arg(long, value_delimiter = ',')] pub skill: Vec, + /// Also install the source's skills with `npx skills`: all of them, or the ones named by `--skill` + #[arg(long)] + pub npx: bool, /// Project directory (default: cwd) #[arg(short = 'p', long)] pub project: Option, @@ -338,6 +356,7 @@ pub(super) fn wants_auto_yes(command: &Command) -> bool { Command::Uninstall(a) => a.yes, Command::Install(a) => a.yes, Command::Update(a) => a.yes, + Command::Upgrade(a) => a.yes, Command::Use(a) => a.yes, Command::Run(a) => a.yes, Command::Library { @@ -453,6 +472,8 @@ mod tests { assert!(wants_auto_yes(&parse(&["install", "o/r", "--yes"]))); assert!(!wants_auto_yes(&parse(&["install", "o/r"]))); assert!(!wants_auto_yes(&parse(&["list"]))); + assert!(wants_auto_yes(&parse(&["upgrade", "-y"]))); + assert!(!wants_auto_yes(&parse(&["upgrade", "--dry-run"]))); assert!(wants_auto_yes(&parse(&["prune", "--force"]))); assert!(!wants_auto_yes(&parse(&["prune"]))); assert!(wants_auto_yes(&parse(&["reset", "-f"]))); diff --git a/src/cli/library/install.rs b/src/cli/library/install.rs index 7097947..8c1211f 100644 --- a/src/cli/library/install.rs +++ b/src/cli/library/install.rs @@ -28,6 +28,8 @@ pub(super) fn install( install: &entries, remove: &[], only: None, + packages: false, + npx: None, }; console.conclude(change(session, scope, &Change::Selection(&selection))?) } diff --git a/src/cli/mod.rs b/src/cli/mod.rs index f96a0b8..57a667a 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -20,6 +20,7 @@ mod scope; mod session; mod sync; mod update; +mod upgrade; mod workspace; use std::io::IsTerminal; @@ -31,7 +32,7 @@ use clap::Parser; pub use args::{ Cli, Command, DoctorArgs, Filter, InstallArgs, ListArgs, PruneArgs, ResetArgs, SyncArgs, - UninstallArgs, UpdateArgs, UseArgs, + UninstallArgs, UpdateArgs, UpgradeArgs, UseArgs, }; use args::{plugin_list, wants_auto_yes}; pub use deps::Deps; diff --git a/src/cli/run.rs b/src/cli/run.rs index 4357e04..3d311ab 100644 --- a/src/cli/run.rs +++ b/src/cli/run.rs @@ -3,7 +3,7 @@ use std::path::PathBuf; use super::args::{ Command, Filter, InstallArgs, ListArgs, PruneArgs, ResetArgs, SyncArgs, UninstallArgs, - UpdateArgs, UseArgs, + UpdateArgs, UpgradeArgs, UseArgs, }; use super::deps::Deps; use super::doctor::doctor; @@ -17,6 +17,7 @@ use super::scope::{Scene, resolve, resolve_project, split_target}; use super::session::{Change, Session, with_session}; use super::sync::{SyncRequest, sync}; use super::update::{UpdateRequest, check, update}; +use super::upgrade::{UpgradeRequest, upgrade}; use super::workspace::workspace; use crate::app::install::{InstallRequest, SkillSelection}; use skillz_harness::model::Scope; @@ -28,6 +29,7 @@ pub fn run(command: Command, deps: &Deps, out: &mut dyn Write) -> anyhow::Result Command::List(args) => succeeded(run_list(deps, args, out)), Command::Uninstall(args) => succeeded(run_uninstall(deps, args, out)), Command::Update(args) => succeeded(run_update(deps, args, out)), + Command::Upgrade(args) => succeeded(run_upgrade(deps, args, out)), Command::Prune(args) => succeeded(run_prune(deps, args, out)), Command::Doctor(args) => succeeded(doctor(deps, &args, out)), Command::Reset(args) => succeeded(run_reset(deps, args, out)), @@ -99,6 +101,17 @@ fn run_update(deps: &Deps, args: UpdateArgs, out: &mut dyn Write) -> anyhow::Res update(&scene, &request, out) } +/// Both levels at once: the project's installs and the user's. +fn run_upgrade(deps: &Deps, args: UpgradeArgs, out: &mut dyn Write) -> anyhow::Result<()> { + let (env, scopes) = resolve(deps, args.project.as_deref(), false)?; + let filter = Filter::default(); + let scene = Scene::new(deps, &env, &scopes, &filter); + let request = UpgradeRequest { + dry_run: args.dry_run, + }; + upgrade(&scene, &request, out) +} + fn run_prune(deps: &Deps, args: PruneArgs, out: &mut dyn Write) -> anyhow::Result<()> { let (env, scopes) = resolve(deps, args.project.as_deref(), args.filter.global)?; let scene = Scene::new(deps, &env, &scopes, &args.filter); @@ -151,6 +164,7 @@ fn run_install(deps: &Deps, args: InstallArgs) -> anyhow::Result<()> { agents: deps.agents_or_all(&args.agents), scope, selection: skill_selection(args.all, args.skill), + npx: args.npx, }; Session::open(deps, &env) .install_source(&request) diff --git a/src/cli/session/change.rs b/src/cli/session/change.rs index bb7d4a4..53345e4 100644 --- a/src/cli/session/change.rs +++ b/src/cli/session/change.rs @@ -11,6 +11,7 @@ use crate::app::apply::{self, Switch, Watch}; use crate::app::profile; use crate::app::remove; use crate::app::review::{ItemEvent, Next, Outcome, Phase, Target, Targets, Verdict}; +use crate::app::route::npx_by_default; use crate::app::stale::Disk; use crate::app::store::Store; use crate::cli::deps::Deps; @@ -91,8 +92,8 @@ pub(in crate::cli) fn change( let applier = job.applier(); let mut switch = job.plan(&applier, what, None)?; targets = targets.or_else(|| job.offered_targets(what, &switch)); - if let Some(only) = targets.as_ref().and_then(Targets::narrowing) { - switch = job.plan(&applier, what, Some(&only))?; + if targets.is_some() { + switch = job.plan(&applier, what, targets.as_ref())?; } switch .updates @@ -146,10 +147,16 @@ impl Job<'_> { } /// What the user may narrow in a change they picked: the agents it reaches, when more than - /// one, and each item it installs or removes. + /// one, and each item it installs or removes. An install also offers `npx`, as one of the + /// installers to run next to the agents'. fn offered_targets(&self, what: &Change, switch: &Switch) -> Option { - if !matches!(what, Change::Selection(_)) { + let Change::Selection(picked) = what else { return None; + }; + if picked.packages && !picked.install.is_empty() { + let every: Vec = self.deps.adapters.iter().map(|a| a.agent()).collect(); + let npx = npx_by_default(picked.install); + return Some(Targets::installers(every.clone(), &every, npx)); } let mut agents: Vec = switch .removals @@ -165,14 +172,19 @@ impl Job<'_> { &self, applier: &apply::Applier, what: &Change, - only: Option<&[Agent]>, + targets: Option<&Targets>, ) -> anyhow::Result { match what { Change::Apply(name) => self.apply_plan(applier, name, false), Change::ApplyExact(name) => self.apply_plan(applier, name, true), Change::Selection(picked) => { let library = self.store.read()?.items.in_env(&self.env); - let narrowed = Selection { only, ..**picked }; + let only = targets.and_then(Targets::narrowing); + let narrowed = Selection { + only: only.as_deref(), + npx: targets.and_then(|t| t.npx), + ..**picked + }; selection_plan(self.deps, &self.env, applier, (&narrowed, &library)) } Change::Update(ids) => update_plan(self.deps, &self.env, self.scope, ids), diff --git a/src/cli/session/change/provenance_tests.rs b/src/cli/session/change/provenance_tests.rs index 273d038..5a453bd 100644 --- a/src/cli/session/change/provenance_tests.rs +++ b/src/cli/session/change/provenance_tests.rs @@ -25,6 +25,8 @@ fn install_picked(dir: &Path, library: &[LibraryItem]) -> (FakeNpx, Store) { install: &entries, remove: &[], only: None, + packages: false, + npx: None, }; change( &session(&deps, dir), diff --git a/src/cli/session/change/scope_tests.rs b/src/cli/session/change/scope_tests.rs index 510333a..4951dea 100644 --- a/src/cli/session/change/scope_tests.rs +++ b/src/cli/session/change/scope_tests.rs @@ -43,6 +43,8 @@ fn installing_at_global_scope_gives_npx_the_global_flag_and_project_scope_does_n install: &entries, remove: &[], only: None, + packages: false, + npx: None, }; let global = run_in( @@ -103,6 +105,8 @@ fn removing_at_global_scope_removes_only_the_global_item() { install: &[], remove: &[id], only: None, + packages: false, + npx: None, }; let wrong_scope = change( @@ -179,6 +183,8 @@ fn installing_a_library_entry_goes_to_the_chosen_scope_and_only_the_chosen_tools install: &[entry], remove: &[], only: None, + packages: false, + npx: None, }; change( &session(&deps, project.path()), @@ -230,6 +236,8 @@ fn codex_library_and_profile_plugins_install_only_in_the_project() { install: std::slice::from_ref(&entry), remove: &[], only: None, + packages: false, + npx: None, }; let what = if from_profile { Change::Apply("matt") diff --git a/src/cli/session/change/selection_tests.rs b/src/cli/session/change/selection_tests.rs index 543c141..263d58c 100644 --- a/src/cli/session/change/selection_tests.rs +++ b/src/cli/session/change/selection_tests.rs @@ -37,6 +37,8 @@ fn selection<'a>(install: &'a [Spec], remove: &'a [String]) -> Selection<'a> { install, remove, only: None, + packages: false, + npx: None, } } @@ -308,3 +310,121 @@ fn a_plan_whose_removals_are_all_unchecked_is_no_longer_destructive() { assert_eq!(*prompter.destructive.borrow(), [true, false]); } + +fn package<'a>(install: &'a [Spec]) -> Selection<'a> { + Selection { + packages: true, + ..selection(install, &[]) + } +} + +fn plugin_entry(source: &str) -> Spec { + Spec::Plugin { + source: source.into(), + marketplace: "mp".into(), + name: "p".into(), + agents: vec![], + } +} + +fn npx_calls(runner: &crate::app::install::test_support::FakeRunner) -> Vec> { + runner + .calls() + .into_iter() + .filter(|(program, _, _)| program == "npx") + .map(|(_, args, _)| args) + .collect() +} + +#[test] +fn a_package_of_skills_installs_with_one_npx_run_for_the_whole_source() { + let dir = tempfile::tempdir().unwrap(); + let entries = [ + skill_entry("grill"), + skill_entry("rust"), + skill_entry("tdd"), + ]; + + let (result, runner) = run_change(dir.path(), true, &Change::Selection(&package(&entries))); + + let npx = npx_calls(&runner); + assert!(matches!( + result.unwrap(), + Some(Notice::Changed { installed: 1, .. }) + )); + assert_eq!(npx.len(), 1); + assert!(npx[0].windows(2).any(|pair| pair == ["--skill", "*"])); +} + +#[test] +fn a_package_with_a_plugin_installs_the_plugin_and_leaves_its_skills_to_it() { + let dir = tempfile::tempdir().unwrap(); + let source = match skill_entry("grill") { + Spec::Skill { source, .. } => source, + other => panic!("{other:?}"), + }; + let entries = [skill_entry("grill"), plugin_entry(&source)]; + + let (_, runner) = run_change(dir.path(), true, &Change::Selection(&package(&entries))); + + let programs: Vec = runner.calls().into_iter().map(|c| c.0).collect(); + assert!(npx_calls(&runner).is_empty()); + assert!(programs.contains(&"claude".to_string())); +} + +/// Checks `npx` in the first plan it is shown, then approves. +struct ChecksNpx { + seen: std::cell::RefCell>>, +} + +impl crate::app::prompt::Prompter for ChecksNpx { + fn multi_select(&self, _title: &str, _options: &[String]) -> anyhow::Result> { + Ok(vec![]) + } + + fn confirm(&self, _question: &str) -> anyhow::Result { + Ok(true) + } + + fn plan(&self, view: &crate::app::review::PlanView) -> anyhow::Result { + let targets = view + .targets + .clone() + .expect("an install offers its installers"); + self.seen.borrow_mut().push(targets.npx); + if self.seen.borrow().len() > 1 { + return Ok(Verdict::Apply); + } + Ok(Verdict::Retarget(Targets { + npx: Some(true), + ..targets + })) + } +} + +#[test] +fn checking_npx_runs_it_next_to_the_agents_plugin_installers() { + let dir = tempfile::tempdir().unwrap(); + let source = match skill_entry("grill") { + Spec::Skill { source, .. } => source, + other => panic!("{other:?}"), + }; + let entries = [skill_entry("grill"), plugin_entry(&source)]; + let runner = crate::app::install::test_support::FakeRunner::new(|_| {}); + let prompter = ChecksNpx { + seen: Default::default(), + }; + let deps = Deps::for_test(dir.path(), registry(), (&runner, &prompter)); + + change( + &session(&deps, dir.path()), + Scope::Project, + &Change::Selection(&package(&entries)), + ) + .unwrap(); + + let programs: Vec = runner.calls().into_iter().map(|c| c.0).collect(); + assert_eq!(*prompter.seen.borrow(), [Some(false), Some(true)]); + assert_eq!(npx_calls(&runner).len(), 1); + assert!(programs.contains(&"claude".to_string())); +} diff --git a/src/cli/session/change/update_tests.rs b/src/cli/session/change/update_tests.rs index 19b8894..f97098b 100644 --- a/src/cli/session/change/update_tests.rs +++ b/src/cli/session/change/update_tests.rs @@ -4,6 +4,7 @@ use std::path::Path; use super::tests::{project_with_skill, run_change, session, skill_id}; use super::*; use crate::app::install::test_support::{FakeNpx, FakeRunner, ScriptedPrompter}; +use crate::app::workspace::Act; use skillz_harness::agents::registry; fn locked_at(dir: &Path, hash: &str) { @@ -142,3 +143,22 @@ fn retrying_an_update_only_retries_the_failed_items() { assert_eq!(*runner.names.borrow(), ["a", "b", "b"]); assert!(matches!(result, Some(Notice::ItemsUpdated(1)))); } + +#[test] +fn the_workspace_update_act_runs_the_same_update() { + let dir = tempfile::tempdir().unwrap(); + locked_at(dir.path(), "old"); + let act = Act::Update { + scope: Scope::Project, + ids: vec![skill_id(dir.path())], + }; + let runner = FakeRunner::new(|_| {}); + let prompter = ScriptedPrompter::new(&[], true); + let deps = Deps::for_test(dir.path(), registry(), (&runner, &prompter)); + + let result = session(&deps, dir.path()).perform(act); + + let calls = runner.calls(); + assert!(matches!(result.unwrap(), Some(Notice::ItemsUpdated(1)))); + assert_eq!(calls[0].1[2], "update"); +} diff --git a/src/cli/session/perform.rs b/src/cli/session/perform.rs index 1a09a93..ef9c41e 100644 --- a/src/cli/session/perform.rs +++ b/src/cli/session/perform.rs @@ -21,9 +21,12 @@ impl Session<'_, '_> { install, remove, only: None, + packages: true, + npx: None, }; change(self, *scope, &Change::Selection(&picked)) } + Act::Update { scope, ids } => change(self, *scope, &Change::Update(ids)), } } diff --git a/src/cli/session/selection.rs b/src/cli/session/selection.rs index 774d727..165dfad 100644 --- a/src/cli/session/selection.rs +++ b/src/cli/session/selection.rs @@ -7,6 +7,7 @@ use crate::app::library::Catalog; use crate::app::merge::merge; use crate::app::profile::Profile; use crate::app::review::Outcome; +use crate::app::route::{npx_by_default, routed}; use crate::cli::deps::Deps; use crate::cli::scope::complete_installed; use skillz_harness::Spec; @@ -18,8 +19,14 @@ use skillz_harness::model::{Agent, Installed}; pub(in crate::cli) struct Selection<'a> { pub install: &'a [Spec], pub remove: &'a [String], - /// The agents to remove from; every agent when `None`. + /// The agents to install for and remove from; every agent when `None`. pub only: Option<&'a [Agent]>, + /// The entries are whole packages from the list, to be installed by the installers the user + /// checks; otherwise each is installed as given. + pub packages: bool, + /// Whether `npx skills` is one of the installers; by default when no plugin could install + /// the skills instead. + pub npx: Option, } /// Installs for what is missing (from the link the library recorded, when it has one), @@ -32,11 +39,20 @@ pub(super) fn selection_plan( (picked, library): (&Selection, &Catalog), ) -> anyhow::Result { let mut wanted = Profile::new("selection"); - wanted.entries = picked + let entries: Vec = picked .install .iter() .map(|entry| library.installable(entry)) .collect(); + wanted.entries = match picked.packages { + true => { + let every: Vec = deps.adapters.iter().map(|a| a.agent()).collect(); + let checked = picked.only.unwrap_or(&every); + let npx = picked.npx.unwrap_or_else(|| npx_by_default(picked.install)); + routed(entries, (checked, &every), npx) + } + false => entries, + }; let mut switch = applier.plan(&wanted, false).context("planning installs")?; switch.removals = complete_installed(deps, env, applier.scope)? .into_iter() diff --git a/src/cli/session/source_install.rs b/src/cli/session/source_install.rs index 37f1e57..ada27c8 100644 --- a/src/cli/session/source_install.rs +++ b/src/cli/session/source_install.rs @@ -49,6 +49,7 @@ mod tests { agents: vec![Agent::Claude], scope: Scope::Global, selection: SkillSelection::Interactive, + npx: false, } } diff --git a/src/cli/upgrade.rs b/src/cli/upgrade.rs new file mode 100644 index 0000000..b9fa7c3 --- /dev/null +++ b/src/cli/upgrade.rs @@ -0,0 +1,279 @@ +//! `skillz upgrade`: update the plugins of both agents, in the project and at user level, that +//! have something newer. What the check cannot tell is updated anyway: the tools' own update +//! commands do nothing when there is nothing new. + +use std::io::Write; + +use super::scope::Scene; +use super::session::{Change, change, with_session}; +use skillz_harness::model::{Installed, Kind, Scope}; +use skillz_harness::update; +use skillz_harness::update::check::UpdateCheck; + +pub(super) struct UpgradeRequest { + pub dry_run: bool, +} + +pub(super) fn upgrade( + scene: &Scene, + request: &UpgradeRequest, + out: &mut dyn Write, +) -> anyhow::Result<()> { + let items = scene.complete()?; + let due = due(scene.deps.checker.as_ref(), &items, &|item| { + !update::steps(&scene.deps.adapters, item, &scene.env.project).is_empty() + }); + if due.is_empty() { + writeln!(out, "everything is up to date")?; + return Ok(()); + } + with_session( + scene.deps, + scene.env, + out, + request.dry_run, + |session, console| { + // A failure in one level does not keep the other from being upgraded. + let mut failed = None; + for &scope in scene.scopes { + let ids = ids_in(&due, scope); + if ids.is_empty() { + continue; + } + let notice = change(session, scope, &Change::Update(&ids))?; + if let Err(e) = console.conclude(notice) { + failed.get_or_insert(e); + } + } + failed.map_or(Ok(()), Err) + }, + ) +} + +/// The plugins and marketplaces that are worth updating: they have an update step, and the +/// check does not say they are current. A plugin is as current as its marketplace. +fn due<'a>( + checker: &dyn UpdateCheck, + items: &'a [Installed], + updatable: &dyn Fn(&Installed) -> bool, +) -> Vec<&'a Installed> { + let parts: Vec<&Installed> = items.iter().flat_map(|item| item.parts()).collect(); + let stale = |part: &Installed| { + let anchor = marketplace_of(part, &parts); + !checker.can_tell(anchor) || checker.available(anchor) + }; + items + .iter() + .filter(|item| matches!(item.kind, Kind::Plugin | Kind::Marketplace)) + .filter(|item| updatable(item)) + .filter(|item| item.parts().iter().any(stale)) + .collect() +} + +/// The marketplace a plugin comes from, when it is installed too, else the item itself. +fn marketplace_of<'a>(item: &'a Installed, all: &[&'a Installed]) -> &'a Installed { + if item.kind != Kind::Plugin { + return item; + } + all.iter() + .copied() + .find(|other| { + other.kind == Kind::Marketplace + && other.group == item.group + && other.installer == item.installer + }) + .unwrap_or(item) +} + +fn ids_in(due: &[&Installed], scope: Scope) -> Vec { + due.iter() + .filter(|item| item.scope == scope) + .flat_map(|item| item.parts().iter().map(|part| part.id.clone())) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::app::install::test_support::{FakeRunner, ScriptedPrompter}; + use crate::cli::args::Filter; + use crate::cli::deps::Deps; + use skillz_harness::action::Action; + use skillz_harness::agents::Harness; + use skillz_harness::env::Env; + use skillz_harness::model::{Agent, Installer}; + use std::path::{Path, PathBuf}; + use std::sync::Arc; + + fn item(name: &str, kind: Kind, group: &str, scope: Scope, installer: Installer) -> Installed { + Installed { + details: Default::default(), + hooks: Vec::new(), + members: Vec::new(), + id: format!("{scope}:{kind}:{name}"), + name: name.into(), + kind, + agents: vec![Agent::Claude], + scope, + group: group.into(), + source: None, + installer, + origin: Default::default(), + children: vec![], + removal: vec![], + } + } + + fn claude(name: &str, kind: Kind, group: &str, scope: Scope) -> Installed { + item(name, kind, group, scope, Installer::ClaudeCli) + } + + /// Two Claude marketplaces, `mp` moved on and `fresh` not, with plugins of each at both + /// levels, and a Codex plugin the check knows nothing about. + fn installs() -> Vec { + vec![ + claude("mp", Kind::Marketplace, "mp", Scope::Global), + claude("a@mp", Kind::Plugin, "mp", Scope::Global), + claude("fresh", Kind::Marketplace, "fresh", Scope::Global), + claude("b@fresh", Kind::Plugin, "fresh", Scope::Global), + item( + "c@cx", + Kind::Plugin, + "cx", + Scope::Global, + Installer::CodexCli, + ), + claude("d@mp", Kind::Plugin, "mp", Scope::Project), + claude("e@fresh", Kind::Plugin, "fresh", Scope::Project), + ] + } + + /// Knows the state of Claude marketplaces only; `mp` has an update. + struct Moved; + + impl UpdateCheck for Moved { + fn available(&self, item: &Installed) -> bool { + item.name == "mp" + } + + fn can_tell(&self, item: &Installed) -> bool { + item.kind == Kind::Marketplace && item.installer == Installer::ClaudeCli + } + } + + fn names(items: &[&Installed]) -> Vec { + items.iter().map(|i| i.name.clone()).collect() + } + + #[test] + fn a_plugin_is_due_with_its_marketplace_and_what_cannot_be_checked_always_is() { + let items = installs(); + + let due = due(&Moved, &items, &|_| true); + + assert_eq!(names(&due), ["mp", "a@mp", "c@cx", "d@mp"]); + } + + #[test] + fn what_has_no_update_step_is_not_due() { + let items = installs(); + + let due = due(&Moved, &items, &|i| i.name != "c@cx"); + + assert_eq!(names(&due), ["mp", "a@mp", "d@mp"]); + } + + #[test] + fn only_plugins_and_marketplaces_are_due() { + let items = [claude("tdd", Kind::Skill, "g", Scope::Global)]; + + assert!(due(&skillz_harness::update::check::NoCheck, &items, &|_| true).is_empty()); + } + + #[test] + fn with_the_check_switched_off_everything_updatable_is_due() { + let items = installs(); + + let due = due(&skillz_harness::update::check::NoCheck, &items, &|_| true); + + assert_eq!(due.len(), items.len()); + } + + #[test] + fn ids_are_split_by_level() { + let items = installs(); + let due = due(&Moved, &items, &|_| true); + + let project = ids_in(&due, Scope::Project); + let global = ids_in(&due, Scope::Global); + + assert_eq!(project, [items[5].id.clone()]); + assert_eq!(global.len(), 3); + } + + struct Fake; + + impl Harness for Fake { + fn agent(&self) -> Agent { + Agent::Claude + } + fn hook_files(&self, _: &Env, _: Scope) -> Vec { + vec![] + } + fn installed(&self, _: &Env, scope: Scope) -> anyhow::Result> { + Ok(installs() + .into_iter() + .filter(|item| item.scope == scope) + .collect()) + } + fn home_dir_names(&self) -> &'static [&'static str] { + &[] + } + fn plan_update(&self, item: &Installed, cwd: &Path) -> Vec { + vec![Action::required( + "fake", + vec!["update".into(), item.name.clone()], + cwd, + )] + } + } + + fn upgraded(approve: bool, dry_run: bool) -> Vec { + let (home, project) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let runner = FakeRunner::new(|_| {}); + let prompter = ScriptedPrompter::new(&[], approve); + let mut deps = Deps::for_test(home.path(), vec![Box::new(Fake)], (&runner, &prompter)); + deps.cwd = project.path().to_path_buf(); + deps.checker = Arc::new(Moved); + let env = super::super::scope::resolve_project(&deps, None).unwrap(); + let scopes = [Scope::Global, Scope::Project]; + let filter = Filter::default(); + let scene = Scene::new(&deps, &env, &scopes, &filter); + let mut out = Vec::new(); + + upgrade(&scene, &UpgradeRequest { dry_run }, &mut out).unwrap(); + + runner + .calls() + .iter() + .map(|(_, args, _)| args[1].clone()) + .collect() + } + + #[test] + fn upgrading_updates_each_level_and_leaves_what_is_current() { + let ran = upgraded(true, false); + + let mut sorted = ran.clone(); + sorted.sort(); + assert_eq!(sorted, ["a@mp", "c@cx", "d@mp", "mp"]); + } + + #[test] + fn a_declined_or_dry_upgrade_runs_nothing() { + let declined = upgraded(false, false); + let dry = upgraded(true, true); + + assert!(declined.is_empty() && dry.is_empty()); + } +} diff --git a/src/tui/keymap.rs b/src/tui/keymap.rs index f99aff7..f308a16 100644 --- a/src/tui/keymap.rs +++ b/src/tui/keymap.rs @@ -55,6 +55,7 @@ pub enum Action { Toggle, Mark, Info, + Update, ToggleDryRun, ToggleSteps, Copy, @@ -131,6 +132,7 @@ pub const BINDINGS: &[Binding] = &[ bind(Plugins, A::Select, &[plain(KeyCode::Enter)], "enter", "apply", 0), bind(Plugins, A::Back, &[plain(KeyCode::Esc)], "esc", "clear selection", 0), bind(Plugins, A::Info, &[ch('i')], "i", "info", 0), + bind(Plugins, A::Update, &[ch('u')], "u", "update", 0), bind(Plugins, A::Filter, &[ch('/')], "/", "filter", 0), bind(Picker, A::Toggle, &[ch(' ')], "space", "check", 0), bind(Picker, A::Select, &[plain(KeyCode::Enter)], "enter", "save selection", 0), diff --git a/src/tui/plan.rs b/src/tui/plan.rs index 08bcae1..f65cb5a 100644 --- a/src/tui/plan.rs +++ b/src/tui/plan.rs @@ -167,17 +167,28 @@ impl Screen for PlanScreen { } } -/// The agents the plan may reach, each checked or not, the cursor on one. +/// The agents the plan may reach, and `npx` when it installs, each checked or not, the cursor +/// on one. fn target_lines(targets: &Targets, theme: &Theme) -> Vec> { - if targets.agents.is_empty() { + if targets.items_from() == 0 { return vec![]; } let glyphs = &theme.glyphs; + let title = match targets.npx { + Some(_) => "Install with", + None => "Agents", + }; let mut lines = vec![Line::styled( - "Agents", + title, theme.accent.add_modifier(theme.title.add_modifier), )]; - lines.extend(targets.agents.iter().enumerate().map(|(at, (agent, on))| { + let npx = targets.npx.map(|on| ("npx".to_string(), on)); + let boxes = targets + .agents + .iter() + .map(|(agent, on)| (agent.to_string(), *on)) + .chain(npx); + lines.extend(boxes.enumerate().map(|(at, (name, on))| { let (glyph, style) = match on { true => (glyphs.checked, theme.ok), false => (glyphs.unchecked, theme.muted), @@ -185,7 +196,7 @@ fn target_lines(targets: &Targets, theme: &Theme) -> Vec> { let cursor = if at == targets.cursor { CURSOR } else { " " }; Line::from(vec![ Span::styled(cursor, theme.accent), - Span::styled(format!("{glyph} {agent}"), style), + Span::styled(format!("{glyph} {name}"), style), ]) })); lines.push(Line::default()); @@ -247,7 +258,7 @@ fn check_lines(targets: &Targets, group: Group, theme: &Theme) -> Vec self.pending.clear(), Action::Back if self.outline.is_filtered() => self.outline.clear_filter(), Action::Info => self.show_info(), + Action::Update => return self.update(), Action::Toggle => self.select(), Action::Select => return self.apply(), movement => { @@ -79,6 +80,19 @@ impl PluginsTab { } } + /// Update what the project has installed of the package under the cursor. The user's + /// packages below the divider are shown only, so they are not updated from here. + fn update(&self) -> Option { + let id = self.outline.current()?; + let Row::Own(plugin) = &self.rows[id] else { + return None; + }; + plugin.is_installed().then(|| Act::Update { + scope: self.scope, + ids: plugin.installed.clone(), + }) + } + /// Flip the package under the cursor between staying as it is and changing. The user's /// packages and the divider above them are left alone. fn select(&mut self) { diff --git a/src/tui/workspace/plugins/tests.rs b/src/tui/workspace/plugins/tests.rs index 0ae7422..501a959 100644 --- a/src/tui/workspace/plugins/tests.rs +++ b/src/tui/workspace/plugins/tests.rs @@ -827,3 +827,65 @@ fn a_marketplace_left_without_plugins_still_has_a_row_to_remove_it_from() { let rows_removing_it = rows_removing(&rows, "marketplace:mp"); assert_eq!(rows_removing_it, 1); } + +#[test] +fn u_updates_what_the_project_has_of_the_package_under_the_cursor() { + let held = installed("tdd", Kind::Skill, "o/r", Some("o/r")); + let mut tab = tab(Model { + library: library(vec![skill("o/r", "tdd")]), + installed: vec![held.clone()], + ..Model::default() + }); + + let act = press(&mut tab, KeyCode::Char('u')); + + assert_eq!( + act, + Some(Act::Update { + scope: Scope::Project, + ids: vec![held.id], + }) + ); + assert!(tab.pending.is_empty()); +} + +#[test] +fn u_does_nothing_on_a_package_that_is_not_installed() { + let mut tab = tab(Model { + library: library(vec![skill("o/r", "tdd")]), + ..Model::default() + }); + + assert_eq!(press(&mut tab, KeyCode::Char('u')), None); +} + +#[test] +fn u_leaves_the_users_packages_alone() { + let mut tab = with_global(); + tab.outline.select_row(5); + + assert_eq!(press(&mut tab, KeyCode::Char('u')), None); +} + +#[test] +fn u_at_user_level_updates_in_that_scope() { + let held = globally("tdd", Kind::Skill, "o/r", Some("o/r")); + let mut tab = tab_for( + Scope::Global, + Model { + library: library(vec![skill("o/r", "tdd")]), + global: vec![held.clone()], + ..Model::default() + }, + ); + + let act = press(&mut tab, KeyCode::Char('u')); + + assert_eq!( + act, + Some(Act::Update { + scope: Scope::Global, + ids: vec![held.id], + }) + ); +} diff --git a/tests/conformance.rs b/tests/conformance.rs index 2a6f389..422b01a 100644 --- a/tests/conformance.rs +++ b/tests/conformance.rs @@ -245,6 +245,7 @@ fn install_asks_the_fake_to_install_plugins_and_runs_no_other_command() { agents: vec![Agent::Codex], scope: Scope::Global, selection: SkillSelection::Interactive, + npx: false, }; // The clone of `o/r` would be a command `OnlyFake` refuses, so use a local source. let src = w.env.project.join("repo"); diff --git a/tests/install.rs b/tests/install.rs index a1673c1..e5d356d 100644 --- a/tests/install.rs +++ b/tests/install.rs @@ -24,6 +24,7 @@ fn install_args(source: &str) -> InstallArgs { agents: vec![Agent::Codex], all: true, skill: vec![], + npx: false, project: None, global: false, yes: true, diff --git a/tests/update.rs b/tests/update.rs index cfd46b0..850d30a 100644 --- a/tests/update.rs +++ b/tests/update.rs @@ -6,7 +6,7 @@ use std::fs; use std::sync::Arc; use common::*; -use skillz::cli::{Command, Deps, Filter, UpdateArgs}; +use skillz::cli::{Command, Deps, Filter, UpdateArgs, UpgradeArgs}; use skillz_harness::model::Installed; use skillz_harness::update::check::UpdateCheck; @@ -62,6 +62,10 @@ impl UpdateCheck for Outdated { fn available(&self, item: &Installed) -> bool { item.name == self.0 } + + fn can_tell(&self, _: &Installed) -> bool { + true + } } fn update_with(w: &World, command: Command) -> (anyhow::Result, Recorder) { @@ -178,3 +182,18 @@ fn an_agent_filter_updates_only_the_selected_copy_of_a_merged_subagent() { assert_eq!(codex == toml, selected == Agent::Codex); } } + +#[test] +fn upgrading_a_project_with_no_plugins_runs_nothing() { + let w = world_with_skill(true); + let command = Command::Upgrade(UpgradeArgs { + project: None, + yes: true, + dry_run: false, + }); + + let (result, runner) = update_with(&w, command); + + assert!(result.is_ok()); + assert_eq!(runner.count(), 0); +}