Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 98 additions & 25 deletions crates/devstack-hub/src/poolskills.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,8 @@ type Download = Box<dyn Fn(&str, &str, &str) -> Result<Vec<u8>, String> + Send +
type Trees = Box<dyn Fn() -> Vec<Tree> + Send + Sync>;
/// Whether git tracks a file at or below a path (relative) of a tree.
type Tracked = Box<dyn Fn(&Path, &Path) -> bool + Send + Sync>;
/// The stacks registered here (`registry::list`; tests: their own).
type Stacks = Box<dyn Fn() -> Vec<devstack_daemon::registry::Entry> + Send + Sync>;

/// What a skill name should be.
struct Want {
Expand All @@ -213,6 +215,10 @@ pub struct PoolSkills {
trees: Trees,
seen: Mutex<Vec<Tree>>,
tracked: Tracked,
/// The user's home: emptied folders above a user folder go up to it.
home: Option<PathBuf>,
/// The stacks whose working trees get the generated skills.
stacks: Stacks,
}

fn now_ms() -> u128 {
Expand Down Expand Up @@ -271,6 +277,8 @@ impl PoolSkills {
);
s.trees = Box::new(registered_trees);
s.tracked = Box::new(crate::branches::tracked);
s.home = devstack_skills::agents::home();
s.stacks = Box::new(devstack_daemon::registry::list);
s
}

Expand All @@ -286,6 +294,8 @@ impl PoolSkills {
trees: Box::new(Vec::new),
seen: Mutex::new(Vec::new()),
tracked: Box::new(|_, _| false),
home: None,
stacks: Box::new(Vec::new),
};
s.publish();
s
Expand Down Expand Up @@ -381,20 +391,24 @@ impl PoolSkills {
/// The generated devstack skills (`devstack skills install`) in every
/// working tree of the stacks registered here (ADR-0079): into the
/// folders there of the agents switched on, and refreshed where an
/// earlier one is; each folder ignores itself. A skill git tracks is
/// left to the upgrade prompt.
/// earlier one is; each folder ignores itself. Out of the folders of the
/// agents switched off that no agent switched on reads (ADR-0083). A
/// skill git tracks is left to the upgrade prompt.
pub fn local(&self) {
let s = self.settings();
let mut rels: Vec<&str> = Vec::new();
let (mut rels, mut off): (Vec<&str>, Vec<&str>) = (Vec::new(), Vec::new());
for a in devstack_skills::agents::all() {
if s.agents.get(&a.id) == Some(&true)
&& let Some(p) = a.project.as_deref()
&& !rels.contains(&p)
{
rels.push(p);
let Some(p) = a.project.as_deref() else {
continue;
};
match s.agents.get(&a.id) {
Some(true) if !rels.contains(&p) => rels.push(p),
Some(false) if !off.contains(&p) => off.push(p),
_ => {}
}
}
for e in devstack_daemon::registry::list() {
off.retain(|p| !rels.contains(p));
for e in (self.stacks)() {
let rel = e
.file
.strip_prefix(&e.repo)
Expand All @@ -417,20 +431,24 @@ impl PoolSkills {
continue;
};
let base = file.parent().unwrap_or(&root).to_path_buf();
let dirs: Vec<PathBuf> = rels
.iter()
.map(|r| {
let mut d = base.clone();
d.extend(r.split('/').filter(|p| !p.is_empty()));
d
})
.collect();
let at = |rels: &[&str]| -> Vec<PathBuf> {
rels.iter()
.map(|r| {
let mut d = base.clone();
d.extend(r.split('/').filter(|p| !p.is_empty()));
d
})
.collect()
};
let (dirs, retire) = (at(&rels), at(&off));
let skip = |folder: &Path| {
folder
.strip_prefix(&root)
.is_ok_and(|rel| (self.tracked)(&root, rel))
};
if let Err(err) = devstack_skills::install_into(&stack, &file, &dirs, &skip) {
if let Err(err) =
devstack_skills::install_into(&stack, &file, &dirs, &retire, &skip)
{
devstack_daemon::diag::warn(
"local_skills",
serde_json::json!({ "tree": root, "error": format!("{err:#}") }),
Expand Down Expand Up @@ -691,12 +709,17 @@ impl PoolSkills {
}
let path = i.dir.join(&i.name);
match tree(&path) {
Some(t) if t == i.tree => {
if let Err(e) = std::fs::remove_dir_all(&path) {
Some(t) if t == i.tree => match std::fs::remove_dir_all(&path) {
Ok(()) => {
if let Some(stop) = self.stop(&i.dir, &trees) {
devstack_skills::prune_empty(&i.dir, &stop);
}
}
Err(e) => {
errors.push(format!("{}: {e}", path.display()));
keep.push(i);
}
}
},
Some(_) => conflicts.push(Conflict {
dir: i.dir.to_string_lossy().into_owned(),
name: i.name.clone(),
Expand Down Expand Up @@ -822,6 +845,19 @@ impl PoolSkills {
out
}

/// How far up the folders a skill leaves empty in `dir` go (ADR-0083):
/// to its working tree's root, or, an agent's user folder, to the home;
/// else none.
fn stop(&self, dir: &Path, trees: &[Tree]) -> Option<PathBuf> {
if let Some(t) = trees.iter().find(|t| dir.starts_with(&t.root)) {
return Some(t.root.clone());
}
let user = devstack_skills::agents::all()
.iter()
.any(|a| (self.folder)(a).as_deref() == Some(dir));
self.home.clone().filter(|h| user && dir.starts_with(h))
}

/// Archives no set names any more go from the store.
fn prune_store(&self, lists: &BTreeMap<String, Vec<SetManifest>>) {
let named: BTreeSet<String> = lists
Expand Down Expand Up @@ -1324,7 +1360,8 @@ mod tests {
let a = archives.clone();
let home = home.to_path_buf();
let h2 = home.clone();
let s = PoolSkills::with(
let h3 = home.clone();
let mut s = PoolSkills::with(
state.to_path_buf(),
Box::new(move |a| match a.id.as_str() {
"claude-code" => Some(home.join(".claude").join("skills")),
Expand All @@ -1345,6 +1382,7 @@ mod tests {
.ok_or_else(|| "gone".into())
}),
);
s.home = Some(h3);
(s, Pool { archives })
}

Expand Down Expand Up @@ -1383,16 +1421,51 @@ mod tests {
);
assert!(hub.view().sets[0].skills[0].installed);

// An update comes at once; switched off, the folder is cleared.
// An update comes at once; switched off, the folder is cleared, and
// the folders it leaves empty go too (ADR-0083), up to the home.
let b = pool.put("work-issue", "v2");
hub.set_pool("default", Some(set(vec![b])));
assert!(std::fs::read_to_string(&claude).unwrap().ends_with("v2"));
hub.set_agent("codex", false).unwrap();
assert!(!home.path().join(".agents/skills/work-issue").exists());
assert!(!home.path().join(".agents").exists());

// The set gone from the pool: its skill goes.
// The set gone from the pool: its skill goes; a folder with a skill
// of the user's own in it stays.
std::fs::create_dir_all(home.path().join(".claude/skills/own")).unwrap();
hub.set_pool("default", Some(Vec::new()));
assert!(!claude.exists());
assert!(home.path().join(".claude/skills/own").is_dir());
assert!(home.path().is_dir());
}

#[test]
fn the_generated_skills_leave_the_folders_of_an_agent_switched_off() {
let (st, home, wt) = (
tempfile::tempdir().unwrap(),
tempfile::tempdir().unwrap(),
tempfile::tempdir().unwrap(),
);
let (mut hub, _pool) = hub(st.path(), home.path());
let file = wt.path().join("devstack.toml");
std::fs::write(
&file,
"version = 1\n[stack]\nname = \"shop\"\n[services.api]\nrun = \"x\"\n",
)
.unwrap();
let (f, r) = (file.clone(), wt.path().to_path_buf());
hub.stacks = Box::new(move || {
vec![devstack_daemon::registry::Entry {
file: f.clone(),
repo: r.clone(),
..Default::default()
}]
});
let agents = wt.path().join(".agents/skills/devstack/SKILL.md");
hub.set_agent("codex", true).unwrap();
assert!(agents.is_file());
hub.set_agent("codex", false).unwrap();
assert!(!wt.path().join(".agents").exists());
assert!(file.is_file(), "the tree stays");
}

#[test]
Expand Down
100 changes: 95 additions & 5 deletions crates/devstack-skills/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,18 +380,38 @@ pub fn install(

/// What the hub writes (ADR-0079): the skills into `dirs` (the agents' skill
/// folders in the working tree of `stack_file`), and a generated copy found
/// in another agent's folder refreshed. A path `skip` says no to (one git
/// tracks) is left alone; a skill the project wrote itself too.
/// in another agent's folder refreshed. In `retire` (the folders of agents
/// the user switched off, ADR-0083) a generated copy goes instead, with the
/// folders it leaves empty, unless `dirs` or `[agents] skills` names the
/// folder or it holds files devstack did not write. A path `skip` says no
/// to (one git tracks) is left alone; a skill the project wrote itself too.
pub fn install_into(
stack: &Stack,
stack_file: &Path,
dirs: &[PathBuf],
retire: &[PathBuf],
skip: &dyn Fn(&Path) -> bool,
) -> Result<Vec<Outcome>> {
let rendered = render_all(stack, stack_file);
let named = skill_dirs(stack, stack_file)?;
let retired: Vec<&PathBuf> = retire
.iter()
.filter(|d| !dirs.contains(d) && !named.contains(d))
.collect();
let root = repo(stack_file)?;
for dir in &retired {
for (name, _) in &rendered {
let folder = dir.join(name);
if generated(&folder) && only_ours(&folder) && !skip(&folder) {
std::fs::remove_dir_all(&folder)
.with_context(|| format!("remove {}", folder.display()))?;
prune_empty(dir, &root);
}
}
}
let mut targets: Vec<(PathBuf, bool)> = dirs.iter().map(|d| (d.clone(), true)).collect();
for d in search_dirs(stack, stack_file)? {
if !targets.iter().any(|(t, _)| *t == d) {
if !targets.iter().any(|(t, _)| *t == d) && !retired.contains(&&d) {
targets.push((d, false));
}
}
Expand Down Expand Up @@ -426,6 +446,27 @@ fn generated(skill_dir: &Path) -> bool {
std::fs::read_to_string(skill_dir.join("SKILL.md")).is_ok_and(|e| e.contains(MARKER_TAG))
}

/// A generated skill's folder holds only what devstack writes there.
fn only_ours(skill_dir: &Path) -> bool {
std::fs::read_dir(skill_dir).is_ok_and(|rd| {
rd.flatten()
.all(|e| e.file_name() == "SKILL.md" || e.file_name() == ".gitignore")
})
}

/// Remove `dir` and the folders above it while they are empty, below
/// `stop` (which stays): what removing a skill left behind (ADR-0083). A
/// folder with anything in it ends the walk.
pub fn prune_empty(dir: &Path, stop: &Path) {
let mut d = dir;
while d != stop && d.starts_with(stop) && std::fs::remove_dir(d).is_ok() {
match d.parent() {
Some(p) => d = p,
None => break,
}
}
}

fn write_one(path: &Path, content: &str, force: bool) -> Result<Outcome> {
let path = path.to_path_buf();
let folder = path.parent().expect("has a parent");
Expand Down Expand Up @@ -817,14 +858,63 @@ ours"
age(&claude.join("SKILL.md"), true);
let old = std::fs::read_to_string(claude.join("SKILL.md")).unwrap();
let tracked = |f: &Path| f.ends_with(".claude/skills/devstack");
install_into(&stack, &file, std::slice::from_ref(&agents), &tracked).unwrap();
install_into(&stack, &file, std::slice::from_ref(&agents), &[], &tracked).unwrap();
assert!(agents.join("devstack/SKILL.md").is_file());
assert!(agents.join("devstack/.gitignore").is_file());
assert_eq!(
std::fs::read_to_string(claude.join("SKILL.md")).unwrap(),
old
);
install_into(&stack, &file, &[], &|_| false).unwrap();
install_into(&stack, &file, &[], &[], &|_| false).unwrap();
assert!(outdated(&file).is_empty(), "{:?}", outdated(&file));
}

#[test]
fn the_hub_takes_a_copy_out_of_a_folder_switched_off() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("devstack.toml");
std::fs::write(&file, STACK).unwrap();
let stack = devstack_config::load(&file).unwrap();
let (claude, agents, github) = (
dir.path().join(".claude/skills"),
dir.path().join(".agents/skills"),
dir.path().join(".github/skills"),
);
let both = [claude.clone(), agents.clone(), github.clone()];
install_into(&stack, &file, &both, &[], &|_| false).unwrap();
// The project's own file beside a generated copy keeps that one.
std::fs::write(github.join("devstack/notes.md"), "ours").unwrap();

// Every agent switched off: the copies go, and the folders they
// leave empty; `.claude/skills` is what `[agents] skills` names by
// default, so it stays; one git tracks stays too.
let tracked = |f: &Path| f.ends_with(".github/skills/devstack-config");
install_into(&stack, &file, &[], &both, &tracked).unwrap();
assert!(claude.join("devstack/SKILL.md").is_file());
assert!(!dir.path().join(".agents").exists());
assert!(github.join("devstack/notes.md").is_file());
assert!(github.join("devstack-config/SKILL.md").is_file());

// A folder still on is written, not taken out.
install_into(&stack, &file, std::slice::from_ref(&agents), &both, &|_| {
false
})
.unwrap();
assert!(agents.join("devstack/SKILL.md").is_file());
}

#[test]
fn pruning_stops_at_a_folder_with_something_in_it_and_at_the_root() {
let root = tempfile::tempdir().unwrap();
let deep = root.path().join("a/b/c");
std::fs::create_dir_all(&deep).unwrap();
std::fs::write(root.path().join("a/keep"), "").unwrap();
prune_empty(&deep, root.path());
assert!(!root.path().join("a/b").exists());
assert!(root.path().join("a").is_dir());
std::fs::remove_file(root.path().join("a/keep")).unwrap();
prune_empty(&root.path().join("a"), root.path());
assert!(!root.path().join("a").exists());
assert!(root.path().is_dir(), "the root stays");
}
}
5 changes: 3 additions & 2 deletions docs/adr/0079-skills-local-to-a-working-tree.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# ADR-0079: Skills local to a working tree: a pool's project skills bound to their repository, devstack's own untracked

- **Status:** Accepted (2026-10-30)
- **Status:** Accepted (2026-10-30); point 5 amended by [ADR-0083](0083-the-hub-takes-out-what-an-agent-switched-off-leaves.md) (a copy in a folder switched off goes)
- **Date:** 2026-10-30
- **Deciders:** project owner
- **Related:** [ADR-0074](0074-a-pool-hands-out-skill-sets-the-hub-installs-them-for-the-agents.md) (skill sets, the agent table; its "per-repository installation" alternative taken up here), [ADR-0077](0077-a-sets-skills-are-grouped-and-switched-one-by-one.md) (`metadata` of a skill), [ADR-0071](0071-the-dashboard-writes-no-file-of-a-repository.md) (amended here), [ADR-0078](0078-the-hub-follows-every-stacks-worktrees.md) (the working trees the hub follows), [ADR-0070](0070-a-review-card-comes-before-the-code-an-adr-records-what-was-built.md)
Expand Down Expand Up @@ -92,7 +92,8 @@ What was built:
renders the generated skills from the stack file the tree runs with
(its own, else the main tree's) and writes them into the folders of the
agents switched on, next to the stack file, refreshing a generated copy
found in another agent's folder. A copy git tracks is left alone; the
found in another agent's folder (one in the folder of an agent switched
off goes instead, ADR-0083). A copy git tracks is left alone; the
banner offers the prompt that untracks it. Nothing is written for a tree
whose stack file does not load.
6. **When.** A thread of the hub looks every three seconds at the
Expand Down
Loading