Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent): share skills and plugins across git worktrees

thinhlpgf722c99ae35e
diff --git a/src-tauri/src/core/agent/git.rs b/src-tauri/src/core/agent/git.rs
index a020f1614..dcd6925ff 100644
--- a/src-tauri/src/core/agent/git.rs
+++ b/src-tauri/src/core/agent/git.rs
@@ -140,6 +140,37 @@ pub(crate) fn current_branch(path: &Path) -> Option<String> {
.filter(|s| !s.is_empty() && s != "HEAD")
}
+/// The main worktree's root when `path` sits in a *linked* worktree, `None`
+/// when `path` is the main worktree itself (or not a git repo at all). Skills
+/// and plugins are installed under `<repo>/.jan/agent` in whatever checkout ran
+/// the install; a linked worktree has its own working tree but shares the
+/// repository, so agent setup should follow the repo, not the checkout.
+/// `--git-common-dir` points at the shared `<main>/.git`; the main worktree
+/// root is its parent. `--path-format=absolute` (git 2.31+) keeps the answer
+/// usable no matter which cwd git would otherwise resolve against.
+pub(crate) fn worktree_primary_root(path: &Path) -> Option<PathBuf> {
+ let p = path.to_string_lossy();
+ let common = git(&[
+ "-C",
+ &p,
+ "rev-parse",
+ "--path-format=absolute",
+ "--git-common-dir",
+ ])
+ .ok()
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())?;
+ let primary = PathBuf::from(&common).parent()?.to_path_buf();
+ // Only a linked worktree shares: the main worktree's common dir lives
+ // *inside* its own root, so this filter also keeps callers from merging a
+ // directory with itself (duplicate entries).
+ if primary == path {
+ None
+ } else {
+ Some(primary)
+ }
+}
+
/// The canonical empty tree object every git repo has, without needing a
/// commit to hash it from -- used as the base tree when `HEAD` is unborn.
#[cfg(feature = "cli")]
@@ -601,4 +632,23 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+
+ /// A linked worktree shares the repo's common dir but has its own working
+ /// tree: `worktree_primary_root` must resolve to the main checkout there,
+ /// and to `None` in the main checkout itself (no self-merge).
+ #[test]
+ fn worktree_primary_root_resolves_linked_worktrees() {
+ let Some(root) = init_repo() else { return };
+ assert_eq!(worktree_primary_root(&root), None, "main worktree has no primary");
+
+ let linked = std::env::temp_dir().join(format!("jan_wt_linked_{}", COUNTER.fetch_add(1, Ordering::SeqCst)));
+ let r = root.to_string_lossy().to_string();
+ let l = linked.to_string_lossy().to_string();
+ git(&["-C", &r, "worktree", "add", &l, "-b", "jan-test-linked"])
+ .expect("add worktree");
+ assert_eq!(worktree_primary_root(&linked).as_deref(), Some(root.as_path()));
+
+ let _ = std::fs::remove_dir_all(&linked);
+ let _ = std::fs::remove_dir_all(&root);
+ }
}
diff --git a/src-tauri/src/core/agent/plugin_commands.rs b/src-tauri/src/core/agent/plugin_commands.rs
index b74c405a9..e1ba47c9b 100644
--- a/src-tauri/src/core/agent/plugin_commands.rs
+++ b/src-tauri/src/core/agent/plugin_commands.rs
@@ -32,39 +32,47 @@ pub(crate) struct ParsedCommand {
/// Every command shipped by installed plugins, sorted by plugin then name.
/// Discovery is recursive (`commands/**/*.md`), skips `README.md` and
-/// dotfiles, and ignores interrupted `.installing-*` staging directories.
+/// dotfiles, and ignores interrupted `.installing-*` staging directories. A
+/// linked git worktree also sees the main worktree's plugins, project-local
+/// shadowing shared ones (see `skills::discovery_roots`).
pub(crate) fn discover(root: &Path) -> Vec<CommandEntry> {
- let dir = crate::core::agent::skills::plugins_dir(root);
- let Ok(rd) = std::fs::read_dir(&dir) else {
- return Vec::new();
- };
+ let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
- for entry in rd.flatten() {
- let path = entry.path();
- if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
- continue;
- }
- let Some(plugin) = path.file_name().and_then(|s| s.to_str()) else {
+ for r in crate::core::agent::skills::discovery_roots(root) {
+ let dir = crate::core::agent::skills::plugins_dir(&r);
+ let Ok(rd) = std::fs::read_dir(&dir) else {
continue;
};
- if plugin.starts_with(".installing-") {
- continue;
- }
- crate::core::agent::skills::walk_markdown_files(&path.join("commands"), &mut |path| {
- let raw = std::fs::read_to_string(path).unwrap_or_default();
- let name = path
- .file_stem()
- .and_then(|s| s.to_str())
- .unwrap_or_default();
- let parsed = parse_command(&raw);
- out.push(CommandEntry {
- name: name.to_string(),
- plugin: plugin.to_string(),
- description: parsed.description,
- file: path.to_path_buf(),
- hints: template_hints(&parsed.body),
+ for entry in rd.flatten() {
+ let path = entry.path();
+ if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
+ continue;
+ }
+ let Some(plugin) = path.file_name().and_then(|s| s.to_str()) else {
+ continue;
+ };
+ if plugin.starts_with(".installing-") {
+ continue;
+ }
+ if !seen.insert(plugin.to_string()) {
+ continue;
+ }
+ crate::core::agent::skills::walk_markdown_files(&path.join("commands"), &mut |path| {
+ let raw = std::fs::read_to_string(path).unwrap_or_default();
+ let name = path
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or_default();
+ let parsed = parse_command(&raw);
+ out.push(CommandEntry {
+ name: name.to_string(),
+ plugin: plugin.to_string(),
+ description: parsed.description,
+ file: path.to_path_buf(),
+ hints: template_hints(&parsed.body),
+ });
});
- });
+ }
}
out.sort_by(|a, b| (&a.plugin, &a.name).cmp(&(&b.plugin, &b.name)));
out
diff --git a/src-tauri/src/core/agent/plugins.rs b/src-tauri/src/core/agent/plugins.rs
index 29c681ed8..f4ef6596c 100644
--- a/src-tauri/src/core/agent/plugins.rs
+++ b/src-tauri/src/core/agent/plugins.rs
@@ -176,52 +176,61 @@ pub(crate) fn find_installed(root: &Path, query: &str) -> Option<(String, Instal
}
fn installed_entries(root: &Path) -> Vec<(String, InstalledPlugin)> {
- let dir = skills::plugins_dir(root);
- let Ok(rd) = std::fs::read_dir(&dir) else {
- return Vec::new();
- };
- // Scan each artifact kind once; per-plugin counts filter the shared lists
- // rather than re-walking the whole plugin tree per plugin.
+ // A linked git worktree also sees the main worktree's plugins, the
+ // project-local one shadowing a same-named shared one. Counts come from
+ // the merged discovery above, so shared plugins report real payloads.
+ let mut seen = std::collections::HashSet::new();
let all_skills = skills::discover_plugins(root);
let all_commands = crate::core::agent::plugin_commands::discover(root);
let mut out = Vec::new();
- for entry in rd.flatten() {
- let path = entry.path();
- if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
- continue;
- }
- let Some(directory) = path.file_name().and_then(|s| s.to_str()) else {
+ for r in skills::discovery_roots(root) {
+ let dir = skills::plugins_dir(&r);
+ let Ok(rd) = std::fs::read_dir(&dir) else {
continue;
};
- if directory.starts_with(".installing-") {
- continue;
+ // Scan each artifact kind once; per-plugin counts filter the shared
+ // lists rather than re-walking the whole plugin tree per plugin.
+ for entry in rd.flatten() {
+ let path = entry.path();
+ if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
+ continue;
+ }
+ let Some(directory) = path.file_name().and_then(|s| s.to_str()) else {
+ continue;
+ };
+ if directory.starts_with(".installing-") {
+ continue;
+ }
+ if !seen.insert(directory.to_string()) {
+ continue;
+ }
+ let manifest = read_manifest(&path);
+ let plugin_skills = all_skills
+ .iter()
+ .filter(|e| e.plugin.as_deref() == Some(directory))
+ .count();
+ let plugin_commands = all_commands
+ .iter()
+ .filter(|e| e.plugin == directory)
+ .count();
+ let plugin_agents = crate::core::agent::subagent::count_plugin_agents(root, directory);
+ out.push((
+ directory.to_string(),
+ InstalledPlugin {
+ name: manifest.name.unwrap_or_else(|| directory.to_string()),
+ description: manifest.description.unwrap_or_default(),
+ version: manifest.version.unwrap_or_else(|| "0.0.0".to_string()),
+ repo: manifest.repo.unwrap_or_default(),
+ skills: plugin_skills,
+ commands: plugin_commands,
+ agents: plugin_agents,
+ tools: crate::core::agent::hooks_config::plugin_tool_entries(&path).len(),
+ hooks: tauri_plugin_agent_tools::tools::hooks::plugin_hook_entries(&path)
+ .0
+ .len(),
+ },
+ ));
}
- let manifest = read_manifest(&path);
- let plugin_skills = all_skills
- .iter()
- .filter(|e| e.plugin.as_deref() == Some(directory))
- .count();
- let plugin_commands = all_commands
- .iter()
- .filter(|e| e.plugin == directory)
- .count();
- let plugin_agents = crate::core::agent::subagent::count_plugin_agents(root, directory);
- out.push((
- directory.to_string(),
- InstalledPlugin {
- name: manifest.name.unwrap_or_else(|| directory.to_string()),
- description: manifest.description.unwrap_or_default(),
- version: manifest.version.unwrap_or_else(|| "0.0.0".to_string()),
- repo: manifest.repo.unwrap_or_default(),
- skills: plugin_skills,
- commands: plugin_commands,
- agents: plugin_agents,
- tools: crate::core::agent::hooks_config::plugin_tool_entries(&path).len(),
- hooks: tauri_plugin_agent_tools::tools::hooks::plugin_hook_entries(&path)
- .0
- .len(),
- },
- ));
}
out.sort_by(|a, b| a.1.name.cmp(&b.1.name));
out
diff --git a/src-tauri/src/core/agent/skills.rs b/src-tauri/src/core/agent/skills.rs
index 167855b25..b0d55c9cb 100644
--- a/src-tauri/src/core/agent/skills.rs
+++ b/src-tauri/src/core/agent/skills.rs
@@ -203,9 +203,22 @@ pub(crate) fn scan_skill_dir(dir: &Path) -> Vec<SkillEntry> {
out
}
-/// All project skills (`<store_root>/skills`), sorted by name.
+/// All project skills (`<store_root>/skills`), sorted by name. A linked git
+/// worktree also sees the main worktree's skills: installs land in the
+/// checkout that ran them, but agent setup follows the repository, not the
+/// checkout. Project-local skills shadow same-named shared ones.
pub(crate) fn discover(root: &Path) -> Vec<SkillEntry> {
- scan_skill_dir(&skills_dir(root))
+ let mut seen = std::collections::HashSet::new();
+ let mut out: Vec<SkillEntry> = Vec::new();
+ for r in discovery_roots(root) {
+ for e in scan_skill_dir(&skills_dir(&r)) {
+ if seen.insert(e.name.clone()) {
+ out.push(e);
+ }
+ }
+ }
+ out.sort_by(|a, b| a.name.cmp(&b.name));
+ out
}
/// The plugins directory `<store_root>/plugins`.
@@ -213,6 +226,27 @@ pub(crate) fn plugins_dir(root: &Path) -> PathBuf {
crate::core::agent::project::store_root(root).join("plugins")
}
+/// Project roots whose stores this project sees, in shadowing order:
+/// the project root first, then the main worktree root when the project is a
+/// linked git worktree. Skills and plugins install into whichever checkout ran
+/// the install; a linked worktree shares the repository but not the working
+/// tree, so discovery follows the repo, not the checkout. Earlier roots win:
+/// a project-local entry shadows a same-named shared one.
+pub(crate) fn discovery_roots(root: &Path) -> Vec<PathBuf> {
+ let mut roots = vec![root.to_path_buf()];
+ roots.extend(crate::core::agent::git::worktree_primary_root(root));
+ roots
+}
+
+/// Locate an installed plugin's directory by name across the discovery roots
+/// (project-local first). `None` when no root has it.
+pub(crate) fn find_plugin_dir(root: &Path, plugin: &str) -> Option<PathBuf> {
+ discovery_roots(root)
+ .iter()
+ .map(|r| plugins_dir(r).join(plugin))
+ .find(|p| p.is_dir())
+}
+
/// Recursively yield every `*.md` file under `dir`, skipping dotfiles and
/// `README` files (any case). Callers read each file themselves so read-failure
/// handling stays with them. Shared by plugin command and plugin agent
@@ -263,42 +297,50 @@ pub(crate) fn invocation_wrapper(name: &str, kind: &str) -> String {
/// (folder and flat forms, same rules as project skills) plus an optional
/// single `SKILL.md` at the plugin root (a repo that is itself one skill).
pub(crate) fn discover_plugins(root: &Path) -> Vec<SkillEntry> {
- let dir = plugins_dir(root);
- let Ok(rd) = std::fs::read_dir(&dir) else {
- return Vec::new();
- };
+ let mut seen = std::collections::HashSet::new();
let mut out: Vec<SkillEntry> = Vec::new();
- for entry in rd.flatten() {
- let path = entry.path();
- if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
- continue;
- }
- let Some(plugin) = path.file_name().and_then(|s| s.to_str()) else {
+ for r in discovery_roots(root) {
+ let dir = plugins_dir(&r);
+ let Ok(rd) = std::fs::read_dir(&dir) else {
continue;
};
- // Ignore interrupted `.installing-*` staging directories, matching the
- // command/agent loaders: a partially-copied plugin must not leak its
- // skills into the catalog during an install.
- if plugin.starts_with(".installing-") {
- continue;
- }
- let mut tagged = Vec::new();
- for e in scan_skill_dir(&path.join("skills")) {
- tagged.push(SkillEntry {
- plugin: Some(plugin.to_string()),
- ..e
- });
- }
- let root_md = path.join("SKILL.md");
- if root_md.is_file() {
- tagged.push(SkillEntry {
- name: plugin.to_string(),
- file: root_md,
- is_folder: false,
- plugin: Some(plugin.to_string()),
- });
+ for entry in rd.flatten() {
+ let path = entry.path();
+ if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
+ continue;
+ }
+ let Some(plugin) = path.file_name().and_then(|s| s.to_str()) else {
+ continue;
+ };
+ // Ignore interrupted `.installing-*` staging directories, matching
+ // the command/agent loaders: a partially-copied plugin must not
+ // leak its skills into the catalog during an install.
+ if plugin.starts_with(".installing-") {
+ continue;
+ }
+ // Earlier roots shadow: a plugin installed in this checkout hides
+ // a same-named one shared from the main worktree.
+ if !seen.insert(plugin.to_string()) {
+ continue;
+ }
+ let mut tagged = Vec::new();
+ for e in scan_skill_dir(&path.join("skills")) {
+ tagged.push(SkillEntry {
+ plugin: Some(plugin.to_string()),
+ ..e
+ });
+ }
+ let root_md = path.join("SKILL.md");
+ if root_md.is_file() {
+ tagged.push(SkillEntry {
+ name: plugin.to_string(),
+ file: root_md,
+ is_folder: false,
+ plugin: Some(plugin.to_string()),
+ });
+ }
+ out.extend(tagged);
}
- out.extend(tagged);
}
out.sort_by(|a, b| a.name.cmp(&b.name));
out
@@ -355,7 +397,7 @@ fn resolve_in_plugin(root: &Path, plugin: &str, plain: &str) -> Option<SkillEntr
if safe_stem(plugin).ok()? != plugin || safe_stem(plain).ok()? != plain {
return None;
}
- let base = plugins_dir(root).join(plugin);
+ let base = find_plugin_dir(root, plugin)?;
let folder = base.join("skills").join(plain).join("SKILL.md");
if folder.is_file() {
return Some(SkillEntry {
@@ -1221,4 +1263,80 @@ mod tests {
assert!(build_invocation_message(&root, "nope", "").is_err());
let _ = std::fs::remove_dir_all(&root);
}
+
+ /// A repo with one commit plus a linked worktree, or skip when git is
+ /// unavailable. Returns `(main_root, linked_root)`.
+ fn repo_with_linked_worktree(tag: &str) -> Option<(std::path::PathBuf, std::path::PathBuf)> {
+ if std::process::Command::new("git").arg("--version").output().is_err() {
+ return None;
+ }
+ let n = std::time::SystemTime::UNIX_EPOCH
+ .elapsed()
+ .unwrap()
+ .as_nanos();
+ let main = std::env::temp_dir().join(format!("jan_wt_main_{tag}_{n}"));
+ std::fs::create_dir_all(&main).unwrap();
+ let run = |args: &[&str]| -> bool {
+ std::process::Command::new("git")
+ .args(args)
+ .current_dir(&main)
+ .status()
+ .map(|s| s.success())
+ .unwrap_or(false)
+ };
+ if !run(&["init", "-q", "."])
+ || !run(&["commit", "--allow-empty", "-q", "-m", "init"])
+ {
+ return None;
+ }
+ let linked = std::env::temp_dir().join(format!("jan_wt_link_{tag}_{n}"));
+ let l = linked.to_string_lossy().to_string();
+ if !run(&["worktree", "add", &l]) {
+ return None;
+ }
+ Some((main, linked))
+ }
+
+ /// Skills and plugins installed in the main worktree are visible from a
+ /// linked worktree (agent setup follows the repo, not the checkout), and a
+ /// project-local skill shadows a same-named shared one.
+ #[test]
+ fn linked_worktree_sees_main_worktree_skills_and_plugins() {
+ let Some((main, linked)) = repo_with_linked_worktree("discover") else {
+ return;
+ };
+ // git resolves paths through realpath, and on macOS /var is a symlink
+ // to /private/var: canonicalize so prefix comparisons hold.
+ let main = std::fs::canonicalize(&main).unwrap();
+ let linked = std::fs::canonicalize(&linked).unwrap();
+ project_skill(&main, "shared", "shared\n");
+ plugin_skill(&main, "shared-plugin", "prep", "plugin\n");
+
+ // Both the shared skill and the shared plugin's skills are visible
+ // from the linked worktree, under the linked root.
+ let names: Vec<String> = discover(&linked).iter().map(|e| e.name.clone()).collect();
+ assert!(names.contains(&"shared".to_string()), "{names:?}");
+ let plugins = discover_plugins(&linked);
+ assert_eq!(
+ plugins.iter().map(qualified_name).collect::<Vec<_>>(),
+ vec!["shared-plugin:prep".to_string()]
+ );
+ // Reading a shared plugin skill resolves through the linked root too.
+ let entry = resolve_readable(&linked, "shared-plugin:prep").unwrap();
+ assert!(entry.file.starts_with(&main));
+
+ // Project-local shadows shared: the linked worktree's own copy wins.
+ project_skill(&linked, "shared", "local\n");
+ let entry = discover(&linked)
+ .into_iter()
+ .find(|e| e.name == "shared")
+ .unwrap();
+ assert!(entry.file.starts_with(&linked), "local must win");
+
+ // The main worktree does not merge with itself (no duplicates).
+ assert_eq!(discover(&main).iter().filter(|e| e.name == "shared").count(), 1);
+
+ let _ = std::fs::remove_dir_all(&main);
+ let _ = std::fs::remove_dir_all(&linked);
+ }
}
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index 343cd749a..e3219eb6d 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -278,10 +278,9 @@ fn load_plugin_agents(project_root: &Path, out: &mut Vec<SubagentDefinition>) {
/// skipping READMEs and dotfiles.
pub(crate) fn count_plugin_agents(root: &Path, plugin: &str) -> usize {
let mut count = 0;
- let base = crate::core::agent::skills::plugins_dir(root)
- .join(plugin)
- .join("agents");
- scan_agent_files(&base, &mut |_, _| count += 1);
+ if let Some(dir) = crate::core::agent::skills::find_plugin_dir(root, plugin) {
+ scan_agent_files(&dir.join("agents"), &mut |_, _| count += 1);
+ }
count
}
@@ -380,9 +379,10 @@ fn map_claude_tools(tools: &[String]) -> Option<Vec<String>> {
#[cfg(feature = "cli")]
pub(crate) fn plugin_agent_metas(root: &Path, plugin: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
- let base = crate::core::agent::skills::plugins_dir(root)
- .join(plugin)
- .join("agents");
+ let Some(base) = crate::core::agent::skills::find_plugin_dir(root, plugin) else {
+ return out;
+ };
+ let base = base.join("agents");
scan_agent_files(&base, &mut |_, raw| {
if let Some((name, description, _, _)) = parse_plugin_agent(raw) {
out.push((name, description));