Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(settings): move MCP servers and skills between the global and project levels

vastsa4533426a26c3
diff --git a/apps/desktop/electron/main/ipc/mcp-ipc.ts b/apps/desktop/electron/main/ipc/mcp-ipc.ts
index 488ce1021..f6c7e1624 100644
--- a/apps/desktop/electron/main/ipc/mcp-ipc.ts
+++ b/apps/desktop/electron/main/ipc/mcp-ipc.ts
@@ -1,4 +1,4 @@
-import { IPC, parseMcpImport, type ActivationScope, type AgentCapabilityQuery, type MarketSource, type McpServerInput, type McpServerRecord, type McpServerStatus } from "@pi-desktop/shared";
+import { IPC, parseMcpImport, type ActivationScope, type AgentCapabilityMove, type AgentCapabilityQuery, type MarketSource, type McpServerInput, type McpServerRecord, type McpServerStatus } from "@pi-desktop/shared";
import type { HostProcess } from "../host-process";
import type { McpRegistrySearchResult } from "../mcp-registry-catalog";
import type { UserMcpRuntime } from "../user-mcp";
@@ -103,6 +103,21 @@ handle(IPC.invoke.mcpList, async (query: Partial<AgentCapabilityQuery> = {}) =>
},
);
+ /**
+ * Move a server between the global and a project's `.agents/servers`.
+ *
+ * Ownership changes, so both levels change: the project runtime is rebuilt and
+ * the renderer is told which id the server ended up under, because a move into
+ * an occupied destination renames it.
+ */
+ handle(IPC.invoke.mcpTransfer, async (payload: AgentCapabilityMove) => {
+ if (!host) throw new Error("host unavailable");
+ const res = await host.call<{ server: McpServerRecord }>("mcp.transfer", payload);
+ await refreshUserMcp(currentWorkspacePath());
+ sendToRenderer(IPC.event.pluginChanged,{ reason: "mcp", pluginId: res.server?.id });
+ return res;
+ });
+
handle(
IPC.invoke.mcpTest,
async (payload: { id: string } & Partial<AgentCapabilityQuery>) => {
diff --git a/apps/desktop/electron/main/ipc/skills-ipc.ts b/apps/desktop/electron/main/ipc/skills-ipc.ts
index bc2c81572..a863ea28b 100644
--- a/apps/desktop/electron/main/ipc/skills-ipc.ts
+++ b/apps/desktop/electron/main/ipc/skills-ipc.ts
@@ -1,5 +1,5 @@
import { dialog, shell } from "electron";
-import { ErrorCodes, IPC, type ActivationScope, type AgentCapabilityQuery, type UserSkillRecord, type UserSubagentRecord } from "@pi-desktop/shared";
+import { ErrorCodes, IPC, type ActivationScope, type AgentCapabilityMove, type AgentCapabilityQuery, type UserSkillRecord, type UserSubagentRecord } from "@pi-desktop/shared";
import { loadSubagentDefinitions, type UserSubagentDocument } from "@pi-desktop/agent-runtime";
import type { HostProcess } from "../host-process";
import type { Logger } from "../logger";
@@ -192,6 +192,19 @@ export function registerSkillsIpc({
},
);
+ /**
+ * Move a skill between the global and a project's `.agents/skills`.
+ *
+ * Ownership changes, so both levels change; the response carries the id the
+ * skill ended up under, because a move into an occupied destination renames it.
+ */
+ handle(IPC.invoke.skillTransfer, async (payload: AgentCapabilityMove) => {
+ if (!host) throw new Error("host unavailable");
+ const res = await host.call<{ skill: UserSkillRecord }>("skills.transfer", payload);
+ sendToRenderer(IPC.event.pluginChanged,{ reason: "skill" });
+ return res;
+ });
+
/**
* Show a skill document in the OS file manager. The level and project travel
* with the id because `skills.read` falls back to the global directory when
diff --git a/apps/desktop/src/components/settings/AgentMcpPage.tsx b/apps/desktop/src/components/settings/AgentMcpPage.tsx
index 3ce5b5c1c..e325fd368 100644
--- a/apps/desktop/src/components/settings/AgentMcpPage.tsx
+++ b/apps/desktop/src/components/settings/AgentMcpPage.tsx
@@ -35,7 +35,15 @@ import {
type McpDraft,
} from "../extensions/McpEditorSheet";
import { McpMarketPanel } from "./McpMarketPanel";
-import { IconPencil, IconPlay, IconPlus, IconServer, IconTerminal, IconTrash } from "../icons";
+import {
+ IconArrowUpDown,
+ IconPencil,
+ IconPlay,
+ IconPlus,
+ IconServer,
+ IconTerminal,
+ IconTrash,
+} from "../icons";
import { TooltipButton, cx } from "../ui";
const GLOBAL_MCP_PATH = "~/.agents/servers";
@@ -282,6 +290,58 @@ export function AgentMcpPage() {
[options, selectedProjectPath],
);
+ /** Where a move sends a row, named the way the toast should say it. */
+ const moveTarget: Partial<Record<AgentCapabilityLevel, string>> = {
+ global: t("settings.globalLevel"),
+ project: selectedProjectPath
+ ? `${t("settings.projectLevel")} · ${projectName ?? projectDisplayName(selectedProjectPath)}`
+ : undefined,
+ };
+
+ /**
+ * Move one row to the other level. The project picker owns the destination,
+ * so the same action reads "Move into <project>" on a global row and "Move to
+ * Global" on a project one.
+ *
+ * The host moves the document rather than copying it, and a destination that
+ * already holds the id or name renames the arriving server, so the toast
+ * reports the new name instead of pretending the id survived.
+ */
+ const move = async (server: McpServerRecord, level: AgentCapabilityLevel) => {
+ const to: AgentCapabilityLevel = level === "global" ? "project" : "global";
+ const target = moveTarget[to];
+ if (!target) {
+ showToast(t("settings.selectProjectFirst"), { variant: "error" });
+ return;
+ }
+ const key = rowKey(level, server.id);
+ setBusyId(key);
+ try {
+ const result = await api.transferMcpServer({
+ id: server.id,
+ from: levelQuery(level),
+ to: levelQuery(to),
+ });
+ await load();
+ const name = server.label || server.id;
+ const arrived = result.server;
+ showToast(
+ arrived && arrived.id !== server.id
+ ? t("settings.capabilityMovedRenamed", {
+ name,
+ target,
+ newName: arrived.label || arrived.id,
+ })
+ : t("settings.capabilityMoved", { name, target }),
+ { variant: "success" },
+ );
+ } catch (error) {
+ showToast(error instanceof Error ? error.message : String(error), { variant: "error" });
+ } finally {
+ setBusyId(null);
+ }
+ };
+
const renderRow = (server: McpServerRecord, level: AgentCapabilityLevel) => {
const key = rowKey(level, server.id);
const name = server.label || server.id;
@@ -300,6 +360,29 @@ export function AgentMcpPage() {
void testConnection(server, level);
},
},
+ /**
+ * A move needs a destination, so a global row offers it only while the
+ * picker names a project; a project row always has Global to go back to.
+ */
+ ...(moveTarget[level === "global" ? "project" : "global"]
+ ? [
+ {
+ key: "move",
+ label:
+ level === "global"
+ ? t("settings.capabilityMoveToProject", {
+ project:
+ projectName ?? projectDisplayName(selectedProjectPath ?? ""),
+ })
+ : t("settings.capabilityMoveToGlobal"),
+ icon: <IconArrowUpDown size={14} />,
+ onSelect: () => {
+ setMenuFor(null);
+ void move(server, level);
+ },
+ } satisfies CapabilityMenuItem,
+ ]
+ : []),
{
key: "remove",
label: isArmed ? t("settings.capabilityRemoveConfirm") : t("extensions.mcp.remove"),
diff --git a/apps/desktop/src/components/settings/AgentSkillsPage.tsx b/apps/desktop/src/components/settings/AgentSkillsPage.tsx
index e39b8d0f3..5ad4a852e 100644
--- a/apps/desktop/src/components/settings/AgentSkillsPage.tsx
+++ b/apps/desktop/src/components/settings/AgentSkillsPage.tsx
@@ -33,6 +33,7 @@ import {
type SkillDraft,
} from "./SkillEditorSheet";
import {
+ IconArrowUpDown,
IconBookOpen,
IconDownload,
IconFileText,
@@ -284,6 +285,58 @@ export function AgentSkillsPage() {
[options, selectedProjectPath],
);
+ /** Where a move sends a row, named the way the toast should say it. */
+ const moveTarget: Partial<Record<AgentCapabilityLevel, string>> = {
+ global: t("settings.globalLevel"),
+ project: selectedProjectPath
+ ? `${t("settings.projectLevel")} · ${projectName ?? projectDisplayName(selectedProjectPath)}`
+ : undefined,
+ };
+
+ /**
+ * Move one row to the other level. The project picker owns the destination,
+ * so the same action reads "Move into <project>" on a global row and "Move to
+ * Global" on a project one.
+ *
+ * The host moves the document rather than copying it, and a destination that
+ * already holds the id or display name renames the arriving skill, so the
+ * toast reports the new name instead of pretending the id survived.
+ */
+ const move = async (skill: UserSkillRecord, level: AgentCapabilityLevel) => {
+ const to: AgentCapabilityLevel = level === "global" ? "project" : "global";
+ const target = moveTarget[to];
+ if (!target) {
+ showToast(t("settings.selectProjectFirst"), { variant: "error" });
+ return;
+ }
+ const key = rowKey(level, skill.id);
+ setBusyId(key);
+ try {
+ const result = await api.transferUserSkill({
+ id: skill.id,
+ from: levelQuery(level),
+ to: levelQuery(to),
+ });
+ await load();
+ const name = skill.name || skill.id;
+ const arrived = result.skill;
+ showToast(
+ arrived && arrived.id !== skill.id
+ ? t("settings.capabilityMovedRenamed", {
+ name,
+ target,
+ newName: arrived.name || arrived.id,
+ })
+ : t("settings.capabilityMoved", { name, target }),
+ { variant: "success" },
+ );
+ } catch (error) {
+ showToast(error instanceof Error ? error.message : String(error), { variant: "error" });
+ } finally {
+ setBusyId(null);
+ }
+ };
+
const renderRow = (skill: UserSkillRecord, level: AgentCapabilityLevel) => {
const key = rowKey(level, skill.id);
const name = skill.name || skill.id;
@@ -299,6 +352,29 @@ export function AgentSkillsPage() {
void reveal(skill, level);
},
},
+ /**
+ * A move needs a destination, so a global row offers it only while the
+ * picker names a project; a project row always has Global to go back to.
+ */
+ ...(moveTarget[level === "global" ? "project" : "global"]
+ ? [
+ {
+ key: "move",
+ label:
+ level === "global"
+ ? t("settings.capabilityMoveToProject", {
+ project:
+ projectName ?? projectDisplayName(selectedProjectPath ?? ""),
+ })
+ : t("settings.capabilityMoveToGlobal"),
+ icon: <IconArrowUpDown size={14} />,
+ onSelect: () => {
+ setMenuFor(null);
+ void move(skill, level);
+ },
+ } satisfies CapabilityMenuItem,
+ ]
+ : []),
{
key: "remove",
label: isArmed ? t("settings.capabilityRemoveConfirm") : t("extensions.skills.remove"),
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 964e3dfff..7168ac056 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -1,5 +1,6 @@
import type {
ActivationScope,
+ AgentCapabilityMove,
AgentCapabilityQuery,
AgentEventEnvelope,
AgentCompactRequest,
@@ -701,6 +702,13 @@ export const api = {
) => invoke(IPC.invoke.mcpSetEnabled, { id, enabled, ...query }),
setMcpServerScope: (id: string, scope: ActivationScope) =>
invoke(IPC.invoke.mcpSetScope, { id, scope }),
+ /**
+ * Move one server to the other level. The document is moved, not copied, and
+ * the response carries the id it ended up under: a destination that already
+ * holds the same id or name renames the arriving server.
+ */
+ transferMcpServer: (move: AgentCapabilityMove) =>
+ invoke<{ server: McpServerRecord }>(IPC.invoke.mcpTransfer, move),
/** Force one handshake and report what happened, for the editor's test button. */
testMcpServer: (id: string, query?: Partial<AgentCapabilityQuery>) =>
invoke<{ status: McpServerStatus }>(IPC.invoke.mcpTest, { id, ...query }),
@@ -760,6 +768,13 @@ export const api = {
) => invoke(IPC.invoke.skillSetEnabled, { id, enabled, ...query }),
setUserSkillScope: (id: string, scope: ActivationScope) =>
invoke(IPC.invoke.skillSetScope, { id, scope }),
+ /**
+ * Move one skill to the other level. The document is moved, not copied, and
+ * the response carries the id it ended up under: a destination that already
+ * holds the same id or display name renames the arriving skill.
+ */
+ transferUserSkill: (move: AgentCapabilityMove) =>
+ invoke<{ skill: UserSkillRecord }>(IPC.invoke.skillTransfer, move),
/**
* Level and project must travel with the id: a project skill has no global
* counterpart to fall back to, so resolving by id alone would miss it.
diff --git a/apps/desktop/test/agent-capability-settings.test.mjs b/apps/desktop/test/agent-capability-settings.test.mjs
index 54e3d80ff..8921d53a7 100644
--- a/apps/desktop/test/agent-capability-settings.test.mjs
+++ b/apps/desktop/test/agent-capability-settings.test.mjs
@@ -347,3 +347,73 @@ test("Settings lists shipped builtin subagents as read-only rows", () => {
assert.doesNotMatch(builtinRow, /CapabilityToggle|setUserSubagentEnabled|revealSubagent|removeUserSubagent/);
assert.match(builtinRow, /IconCopy/);
});
+
+test("a capability can be moved between the global and a project level", () => {
+ const api = read("../src/lib/api.ts");
+ const protocol = read("../../../packages/shared/src/protocol.ts");
+ const sharedTypes = read("../../../packages/shared/src/types/capabilities.ts");
+ const mcpIpc = readMainModuleSync("ipc/mcp-ipc.ts");
+ const rpc = read("../../../crates/host-core/src/rpc/mod.rs");
+ const capabilities = read("../../../crates/host-core/src/agent_capabilities.rs");
+ const mcpRegistry = read("../../../crates/host-core/src/mcp_servers.rs");
+ const skillRegistry = read("../../../crates/host-core/src/user_skills.rs");
+
+ // Both ends travel with the request, so a global source that names a project
+ // as its enablement context is never mistaken for the destination.
+ assert.match(
+ sharedTypes,
+ /export type AgentCapabilityMove = \{[\s\S]*?from: AgentCapabilityTarget;[\s\S]*?to: AgentCapabilityTarget;/,
+ );
+ assert.match(protocol, /mcpTransfer: "pi-desktop\/mcp\/transfer"/);
+ assert.match(protocol, /skillTransfer: "pi-desktop\/skill\/transfer"/);
+ assert.match(api, /transferMcpServer: \(move: AgentCapabilityMove\) =>/);
+ assert.match(api, /transferUserSkill: \(move: AgentCapabilityMove\) =>/);
+ assert.match(mcpIpc, /host\.call<\{ server: McpServerRecord \}>\("mcp\.transfer", payload\)/);
+ assert.match(
+ skillImport,
+ /host\.call<\{ skill: UserSkillRecord \}>\("skills\.transfer", payload\)/,
+ );
+ assert.match(rpc, /"mcp\.transfer" =>/);
+ assert.match(rpc, /"skills\.transfer" =>/);
+
+ // The host moves the document instead of copying it, so the source level
+ // stops listing it, and the enabled value follows it to the new level. The
+ // state entry dropped is the source owner's, never another project's.
+ assert.match(capabilities, /pub fn set_moved_capability_state\(/);
+ assert.match(
+ capabilities,
+ /state\.forget\(kind, source_level, source_id, source_project_path\)\?;/,
+ );
+ assert.match(capabilities, /pub fn move_capability_file\(/);
+ assert.match(mcpRegistry, /pub fn transfer\(/);
+ assert.match(skillRegistry, /pub fn transfer\(/);
+ // A destination that already owns the id or name keeps both by renaming.
+ assert.match(capabilities, /pub fn suffixed_capability_id\(/);
+ assert.match(capabilities, /pub fn suffixed_display_name\(/);
+ // A directory-shaped skill carries its sibling resources, so the directory is
+ // the unit, not the one markdown file.
+ assert.match(skillRegistry, /fn directory_skill_root\(/);
+ assert.match(skillRegistry, /copy_directory_tree\(dir, &target_unit, true\)/);
+ // Renaming must not reformat the document it edits.
+ assert.match(skillRegistry, /fn rewrite_document_name\(/);
+ assert.doesNotMatch(
+ skillRegistry.slice(
+ skillRegistry.indexOf("pub fn transfer("),
+ skillRegistry.indexOf("pub fn new(data_dir"),
+ ),
+ /render_document/,
+ );
+});
+
+test("the move action offers a level only when there is a destination", () => {
+ for (const source of [skills, mcp]) {
+ assert.match(source, /settings\.capabilityMoveToGlobal/);
+ assert.match(source, /settings\.capabilityMoveToProject/);
+ assert.match(source, /settings\.capabilityMovedRenamed/);
+ assert.match(source, /IconArrowUpDown/);
+ // The project picker owns the destination, so a global row has nowhere to
+ // go until a project is selected; a project row always has Global.
+ assert.match(source, /moveTarget\[level === "global" \? "project" : "global"\]/);
+ assert.match(source, /showToast\(t\("settings\.selectProjectFirst"\)/);
+ }
+});
diff --git a/crates/host-core/src/agent_capabilities.rs b/crates/host-core/src/agent_capabilities.rs
index 68ed22e0f..163564540 100644
--- a/crates/host-core/src/agent_capabilities.rs
+++ b/crates/host-core/src/agent_capabilities.rs
@@ -1,8 +1,8 @@
-use anyhow::{bail, Result};
+use anyhow::{bail, Context, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
@@ -181,6 +181,44 @@ impl CapabilityState {
Ok(())
}
+ /// Drop the stored state of one document at its source level.
+ ///
+ /// A global document is one shared file, so its id owns the global default
+ /// and every project override alike: they are all dropped, whichever
+ /// project context the move started from (`project_path` is ignored there).
+ /// A project document has exactly one owner, so only the entry belonging to
+ /// `project_path` goes with it — another project's same-named document is a
+ /// different file with its own state.
+ pub fn forget(
+ &mut self,
+ kind: &str,
+ level: CapabilityLevel,
+ id: &str,
+ project_path: Option<&str>,
+ ) -> Result<()> {
+ let before = self.values.len();
+ self.values.retain(|raw_key, _| {
+ let Ok(key) = serde_json::from_str::<StateKey>(raw_key) else {
+ return false;
+ };
+ if key.kind != kind || key.level != level.as_str() || key.id != id {
+ return true;
+ }
+ match level {
+ CapabilityLevel::Global => false,
+ CapabilityLevel::Project => match (&key.project_path, project_path) {
+ (Some(owner), Some(selected)) => !same_path(owner, selected),
+ (None, None) => false,
+ _ => true,
+ },
+ }
+ });
+ if before != self.values.len() {
+ self.save()?;
+ }
+ Ok(())
+ }
+
fn save(&self) -> Result<()> {
if let Some(parent) = self.path.parent() {
fs::create_dir_all(parent)?;
@@ -193,7 +231,21 @@ impl CapabilityState {
}
}
+/// Repoints the global capability root, the way `PI_DESKTOP_DATA_DIR` repoints
+/// the app-local data directory.
+///
+/// The global `.agents` root is otherwise the real home directory, which leaves
+/// the global half of a level switch untestable and makes an isolated install
+/// impossible. An empty value falls back to the home directory.
+pub const AGENTS_DIR_ENV: &str = "PI_DESKTOP_AGENTS_DIR";
+
pub fn global_agents_dir() -> PathBuf {
+ if let Ok(configured) = std::env::var(AGENTS_DIR_ENV) {
+ let trimmed = configured.trim();
+ if !trimmed.is_empty() {
+ return PathBuf::from(trimmed);
+ }
+ }
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join(AGENTS_DIR)
@@ -237,6 +289,228 @@ fn same_path(a: &str, b: &str) -> bool {
normalize_project_path(a).to_lowercase() == normalize_project_path(b).to_lowercase()
}
+/// One place a capability document can live: a level plus, for the project
+/// level, the project that owns it.
+///
+/// A global target may still carry a project path. There it means "resolve the
+/// global document with this project's enabled override", which is the context
+/// a move needs to read the state the user was actually looking at.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CapabilityTarget {
+ pub level: CapabilityLevel,
+ pub project_path: Option<String>,
+}
+
+impl CapabilityTarget {
+ pub fn new(level: CapabilityLevel, project_path: Option<&str>) -> Result<Self> {
+ let project_path = project_path
+ .map(normalize_project_path)
+ .filter(|value| !value.is_empty());
+ if level == CapabilityLevel::Project && project_path.is_none() {
+ bail!("CAPABILITY_INVALID: projectPath is required for project capabilities");
+ }
+ Ok(Self {
+ level,
+ project_path,
+ })
+ }
+
+ /// True when both targets name the same directory.
+ pub fn same_directory(&self, other: &Self) -> bool {
+ if self.level != other.level {
+ return false;
+ }
+ match (&self.project_path, &other.project_path) {
+ (Some(a), Some(b)) => same_path(a, b),
+ (None, None) => true,
+ // A global target's project path is a state context, not an owner,
+ // so two global targets always name the same directory.
+ _ => self.level == CapabilityLevel::Global,
+ }
+ }
+}
+
+/// Carry a moved document's activation state across to its destination.
+///
+/// The value that travels is the one the user was looking at at the source. A
+/// document arriving in a project gets that project's own state; one arriving
+/// globally gets the global default, never a per-project override, because the
+/// move says nothing about the projects it left behind. The source entry is
+/// dropped first so the old level holds no state for a document it lost, and
+/// `source_project_path` scopes that drop to the document's real owner: moving
+/// project A's document must not clear project B's state for a same-named one.
+// Every parameter names a distinct part of the move (source kind, level, id,
+// owner, target, target id, value); bundling them would hide the owner, which
+// is the one that must not be dropped.
+#[allow(clippy::too_many_arguments)]
+pub fn set_moved_capability_state(
+ state: &mut CapabilityState,
+ kind: &str,
+ source_level: CapabilityLevel,
+ source_id: &str,
+ source_project_path: Option<&str>,
+ target: &CapabilityTarget,
+ target_id: &str,
+ enabled: bool,
+) -> Result<()> {
+ state.forget(kind, source_level, source_id, source_project_path)?;
+ let owner = match target.level {
+ CapabilityLevel::Global => None,
+ CapabilityLevel::Project => target.project_path.as_deref(),
+ };
+ state.set_enabled(kind, target.level, target_id, owner, enabled)
+}
+
+/// How many `-2`, `-3`, … candidates a move tries before giving up.
+pub(crate) const MAX_ID_SUFFIX: u32 = 999;
+
+/// The id a document should carry at a destination that already holds `taken`.
+///
+/// A level switch that silently overwrote a document the user still has would
+/// be data loss, and refusing the move outright would make the global/project
+/// switch useless whenever both sides happen to share a name. Renaming mirrors
+/// how a file manager disambiguates a copy. The returned ordinal is the suffix
+/// that was applied, or `0` when the preferred id was free.
+///
+/// `taken` must already be lowercased, and the comparison is lowercased on
+/// both sides: on macOS and Windows `MyServer.json` and `myserver.json` are the
+/// same file, so a case-sensitive check would hand the arriving document a name
+/// that silently replaces an existing one.
+pub fn suffixed_capability_id(
+ preferred: &str,
+ taken: &HashSet<String>,
+ max_chars: usize,
+) -> Option<(String, u32)> {
+ if !taken.contains(&preferred.to_lowercase()) {
+ return Some((preferred.to_string(), 0));
+ }
+ for ordinal in 2..=MAX_ID_SUFFIX {
+ let suffix = format!("-{ordinal}");
+ let keep = max_chars.saturating_sub(suffix.len());
+ let mut base: String = preferred.chars().take(keep).collect();
+ while base.ends_with('-') {
+ base.pop();
+ }
+ if base.is_empty() {
+ return None;
+ }
+ let candidate = format!("{base}{suffix}");
+ if !taken.contains(&candidate.to_lowercase()) {
+ return Some((candidate, ordinal));
+ }
+ }
+ None
+}
+
+/// The display name for `ordinal` collisions, suffix included.
+///
+/// `ordinal <= 1` is the name itself, trimmed to the character budget.
+/// Otherwise the suffix is appended *after* the base is trimmed to fit, so a
+/// name already at the budget still yields a distinct candidate instead of a
+/// truncated copy of itself, and a base cut mid-word keeps no trailing space
+/// before the suffix.
+pub fn display_name_candidate(name: &str, ordinal: u32, max_chars: usize) -> String {
+ if ordinal <= 1 {
+ return name.chars().take(max_chars).collect();
+ }
+ let suffix = format!(" ({ordinal})");
+ let keep = max_chars.saturating_sub(suffix.len());
+ let mut base: String = name.chars().take(keep).collect();
+ while base.ends_with(' ') {
+ base.pop();
+ }
+ format!("{base}{suffix}")
+}
+
+/// The display name a document should carry at a destination that already
+/// holds `taken` (compared case-insensitively, the way shadowing compares it).
+pub fn suffixed_display_name(
+ preferred: &str,
+ taken: &HashSet<String>,
+ max_chars: usize,
+) -> String {
+ for ordinal in 1..=MAX_ID_SUFFIX {
+ let candidate = display_name_candidate(preferred, ordinal, max_chars);
+ if !candidate.is_empty() && !taken.contains(&candidate.to_lowercase()) {
+ return candidate;
+ }
+ }
+ preferred.to_string()
+}
+
+/// Copy a directory tree, optionally leaving a skill's own `SKILL.md` behind.
+///
+/// Shared by the cross-filesystem fallback of `move_capability_file` and the
+/// skill move that has already written the renamed document and only needs the
+/// resources beside it (`skip_skill_document` skips the document at the root of
+/// `from` — the one the caller wrote; a nested `SKILL.md` is just a resource
+/// and is copied, because the source directory is deleted afterwards).
+/// Same-named files are overwritten: the destination unit is new (its id is
+/// unique at the level), so a file already there can only be the leftover of an
+/// interrupted move, never another skill's data.
+pub fn copy_directory_tree(from: &Path, to: &Path, skip_skill_document: bool) -> Result<()> {
+ fs::create_dir_all(to).map_err(|error| anyhow::anyhow!("create {}: {error}", to.display()))?;
+ let entries = fs::read_dir(from).with_context(|| format!("read {}", from.display()))?;
+ for entry in entries.flatten() {
+ let path = entry.path();
+ let Some(name) = path.file_name() else {
+ continue;
+ };
+ if skip_skill_document && name.eq_ignore_ascii_case("SKILL.md") {
+ continue;
+ }
+ let target = to.join(name);
+ if path.is_dir() {
+ copy_directory_tree(&path, &target, false)?;
+ } else {
+ fs::copy(&path, &target)
+ .map_err(|error| anyhow::anyhow!("copy {}: {error}", path.display()))?;
+ }
+ }
+ Ok(())
+}
+
+/// Move one capability document or directory, staying byte-identical whenever
+/// the caller does not need to rewrite it.
+///
+/// `fs::rename` is tried first so a same-filesystem move is atomic and cheap;
+/// the copy fallback covers a project on another mount. `fs::copy` cannot move
+/// a directory (it fails with EISDIR), so a directory falls back to a recursive
+/// copy, a destination check, and only then a recursive delete of the source:
+/// the copy is complete before the original is touched, so a failure leaves the
+/// source intact. The caller must have checked that `to` is free, because this
+/// never replaces an existing destination.
+pub fn move_capability_file(from: &Path, to: &Path) -> Result<()> {
+ if to.exists() {
+ bail!("CAPABILITY_INVALID: destination already exists: {}", to.display());
+ }
+ if let Some(parent) = to.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ match fs::rename(from, to) {
+ Ok(()) => Ok(()),
+ Err(_) => {
+ if from.is_dir() {
+ copy_directory_tree(from, to, false)?;
+ if !to.is_dir() {
+ bail!(
+ "CAPABILITY_INVALID: could not copy directory {}",
+ from.display()
+ );
+ }
+ fs::remove_dir_all(from)
+ .map_err(|error| anyhow::anyhow!("remove {}: {error}", from.display()))?;
+ return Ok(());
+ }
+ fs::copy(from, to)
+ .map_err(|error| anyhow::anyhow!("copy {}: {error}", from.display()))?;
+ fs::remove_file(from)
+ .map_err(|error| anyhow::anyhow!("remove {}: {error}", from.display()))?;
+ Ok(())
+ }
+ }
+}
+
pub fn parse_front_matter(raw: &str) -> (BTreeMap<String, String>, String) {
let text = raw.trim_start_matches('\u{feff}');
let Some(rest) = text.strip_prefix("---") else {
@@ -434,6 +708,31 @@ pub fn sorted_files(dir: &Path, extension: &str) -> Vec<PathBuf> {
files
}
+/// Test-only seams shared by every capability module.
+#[cfg(test)]
+pub(crate) mod test_support {
+ use std::path::Path;
+ use std::sync::Mutex;
+
+ static AGENTS_ENV_LOCK: Mutex<()> = Mutex::new(());
+
+ /// Point the global capability root at `dir` for the duration of `f`.
+ ///
+ /// `PI_DESKTOP_AGENTS_DIR` is process-global and the test harness runs
+ /// tests in parallel threads, so every repointing test takes this one lock:
+ /// per-module locks would not exclude each other, and two tests would end up
+ /// reading each other's directory.
+ pub fn with_global_agents<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
+ let _guard = AGENTS_ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());
+ // Safety: test-only process env mutation, serialized by the lock above.
+ unsafe { std::env::set_var(super::AGENTS_DIR_ENV, dir) };
+ let outcome = f();
+ unsafe { std::env::remove_var(super::AGENTS_DIR_ENV) };
+ outcome
+ }
+
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -516,4 +815,274 @@ mod tests {
.unwrap();
assert!(orphaned.enabled("skills", CapabilityLevel::Global, "review", Some("/a")));
}
+
+ #[test]
+ fn suffix_keeps_the_preferred_id_when_it_is_free() {
+ let taken = HashSet::new();
+ assert_eq!(
+ suffixed_capability_id("review", &taken, 64),
+ Some(("review".to_string(), 0))
+ );
+ }
+
+ #[test]
+ fn suffix_walks_past_every_taken_id_and_stays_inside_the_budget() {
+ let taken: HashSet<String> = ["review".to_string(), "review-2".to_string()]
+ .into_iter()
+ .collect();
+ assert_eq!(
+ suffixed_capability_id("review", &taken, 64),
+ Some(("review-3".to_string(), 3))
+ );
+
+ // A 64-character id has no room for the suffix, so the base is trimmed
+ // rather than the candidate growing past what the id validator accepts.
+ let long = "a".repeat(64);
+ let taken: HashSet<String> = [long.clone()].into_iter().collect();
+ let (candidate, ordinal) = suffixed_capability_id(&long, &taken, 64).unwrap();
+ assert_eq!(ordinal, 2);
+ assert_eq!(candidate.len(), 64);
+ assert!(valid_capability_id(&candidate, 64));
+ }
+
+ #[test]
+ fn suffix_reports_exhaustion_instead_of_reusing_a_taken_id() {
+ let taken: HashSet<String> = ["review".to_string()].into_iter().collect();
+ // `max_chars` below the suffix length leaves nothing to build on.
+ assert_eq!(suffixed_capability_id("review", &taken, 2), None);
+ }
+
+ #[test]
+ fn display_name_suffix_is_case_insensitive_like_shadowing() {
+ let taken: HashSet<String> = ["review".to_string()].into_iter().collect();
+ assert_eq!(suffixed_display_name("Review", &taken, 120), "Review (2)");
+ assert_eq!(suffixed_display_name("Files", &taken, 120), "Files");
+ }
+
+ #[test]
+ fn suffix_ignores_id_case_so_a_case_insensitive_volume_keeps_both_files() {
+ // Callers pass the taken set lowercased, mirroring the filesystem, so
+ // `MyServer` must not be treated as free next to `myserver`.
+ let taken: HashSet<String> = ["myserver".to_string()].into_iter().collect();
+ assert_eq!(
+ suffixed_capability_id("MyServer", &taken, 64),
+ Some(("MyServer-2".to_string(), 2))
+ );
+ }
+
+ #[test]
+ fn display_name_suffix_stays_distinct_at_the_character_budget() {
+ let full = "a".repeat(120);
+ let taken: HashSet<String> = [full.clone()].into_iter().collect();
+ let renamed = suffixed_display_name(&full, &taken, 120);
+ assert_ne!(renamed, full);
+ assert!(renamed.chars().count() <= 120);
+ assert_eq!(renamed, format!("{} (2)", "a".repeat(116)));
+
+ // Each ordinal still yields its own candidate once the earlier ones
+ // are taken, instead of collapsing onto the truncated base name.
+ let taken: HashSet<String> = [full.clone(), renamed.clone()]
+ .into_iter()
+ .map(|value| value.to_lowercase())
+ .collect();
+ let third = suffixed_display_name(&full, &taken, 120);
+ assert_ne!(third, full);
+ assert_ne!(third, renamed);
+ assert!(third.chars().count() <= 120);
+
+ // The suffix follows a base that was cut mid-word without a stray
+ // space, and ordinal 1 is the plain name.
+ assert_eq!(display_name_candidate("Review", 1, 120), "Review");
+ assert_eq!(display_name_candidate("Review", 2, 8), "Revi (2)");
+ assert_eq!(display_name_candidate("Review more", 2, 11), "Review (2)");
+ }
+
+ #[test]
+ fn project_target_requires_a_project_path() {
+ assert!(CapabilityTarget::new(CapabilityLevel::Project, None).is_err());
+ assert!(CapabilityTarget::new(CapabilityLevel::Project, Some(" ")).is_err());
+ assert!(CapabilityTarget::new(CapabilityLevel::Global, None).is_ok());
+ assert_eq!(
+ CapabilityTarget::new(CapabilityLevel::Project, Some("/repo/"))
+ .unwrap()
+ .project_path
+ .as_deref(),
+ Some("/repo")
+ );
+ }
+
+ #[test]
+ fn global_targets_share_one_directory_whatever_project_context_they_carry() {
+ let plain = CapabilityTarget::new(CapabilityLevel::Global, None).unwrap();
+ let contextual = CapabilityTarget::new(CapabilityLevel::Global, Some("/repo")).unwrap();
+ assert!(plain.same_directory(&contextual));
+ let project = CapabilityTarget::new(CapabilityLevel::Project, Some("/repo")).unwrap();
+ assert!(!plain.same_directory(&project));
+ let other = CapabilityTarget::new(CapabilityLevel::Project, Some("/other")).unwrap();
+ assert!(!project.same_directory(&other));
+ }
+
+ #[test]
+ fn global_root_follows_the_environment_override() {
+ let dir = tempdir().unwrap();
+ test_support::with_global_agents(dir.path(), || {
+ assert_eq!(global_agents_dir(), dir.path());
+ assert_eq!(
+ capability_dir(CapabilityLevel::Global, None, "skills").unwrap(),
+ dir.path().join("skills")
+ );
+ });
+ }
+
+ #[test]
+ fn forget_drops_every_project_override_for_one_document() {
+ let dir = tempdir().unwrap();
+ let mut state = CapabilityState::new(dir.path(), "skills");
+ state
+ .set_enabled("skills", CapabilityLevel::Global, "review", None, false)
+ .unwrap();
+ state
+ .set_enabled(
+ "skills",
+ CapabilityLevel::Global,
+ "review",
+ Some("/repo"),
+ true,
+ )
+ .unwrap();
+ state
+ .set_enabled("skills", CapabilityLevel::Project, "review", Some("/repo"), false)
+ .unwrap();
+ assert!(!state.enabled("skills", CapabilityLevel::Global, "review", None));
+
+ state
+ .forget("skills", CapabilityLevel::Global, "review", None)
+ .unwrap();
+ // Back to the default, and the unrelated project-level entry survives.
+ assert!(state.enabled("skills", CapabilityLevel::Global, "review", Some("/repo")));
+ assert!(!state.enabled("skills", CapabilityLevel::Project, "review", Some("/repo")));
+ }
+
+ #[test]
+ fn project_level_forget_keeps_other_projects_entries() {
+ let dir = tempdir().unwrap();
+ let mut state = CapabilityState::new(dir.path(), "skills");
+ state
+ .set_enabled(
+ "skills",
+ CapabilityLevel::Project,
+ "review",
+ Some("/a"),
+ false,
+ )
+ .unwrap();
+ state
+ .set_enabled(
+ "skills",
+ CapabilityLevel::Project,
+ "review",
+ Some("/b"),
+ false,
+ )
+ .unwrap();
+
+ state
+ .forget("skills", CapabilityLevel::Project, "review", Some("/a"))
+ .unwrap();
+ // Only the owner's entry is gone: another project's same-named document
+ // is a different file and keeps its own state.
+ assert!(state.enabled("skills", CapabilityLevel::Project, "review", Some("/a")));
+ assert!(!state.enabled("skills", CapabilityLevel::Project, "review", Some("/b")));
+ }
+
+ #[test]
+ fn moving_a_project_document_leaves_other_projects_state_alone() {
+ let dir = tempdir().unwrap();
+ let mut state = CapabilityState::new(dir.path(), "mcp");
+ state
+ .set_enabled("mcp", CapabilityLevel::Project, "files", Some("/a"), false)
+ .unwrap();
+ state
+ .set_enabled("mcp", CapabilityLevel::Project, "files", Some("/b"), false)
+ .unwrap();
+
+ set_moved_capability_state(
+ &mut state,
+ "mcp",
+ CapabilityLevel::Project,
+ "files",
+ Some("/a"),
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ "files",
+ false,
+ )
+ .unwrap();
+
+ // The departed project's entry moved with the document; the other
+ // project still owns its own state for the same id.
+ assert!(state.enabled("mcp", CapabilityLevel::Project, "files", Some("/a")));
+ assert!(!state.enabled("mcp", CapabilityLevel::Project, "files", Some("/b")));
+ assert!(!state.enabled("mcp", CapabilityLevel::Global, "files", Some("/b")));
+ }
+
+ #[test]
+ fn copy_directory_tree_overwrites_stale_files_and_can_skip_the_document() {
+ let dir = tempdir().unwrap();
+ let from = dir.path().join("from");
+ let to = dir.path().join("to");
+ fs::create_dir_all(from.join("nested")).unwrap();
+ fs::write(from.join("SKILL.md"), "doc").unwrap();
+ fs::write(from.join("notes.txt"), "keep me").unwrap();
+ fs::write(from.join("nested/page.html"), "<p>page</p>").unwrap();
+ // A leftover from an interrupted copy must not survive: skipping it
+ // would silently drop the resource.
+ fs::create_dir_all(&to).unwrap();
+ fs::write(to.join("notes.txt"), "stale").unwrap();
+
+ copy_directory_tree(&from, &to, true).unwrap();
+ assert!(!to.join("SKILL.md").exists());
+ assert_eq!(fs::read_to_string(to.join("notes.txt")).unwrap(), "keep me");
+ assert_eq!(
+ fs::read_to_string(to.join("nested/page.html")).unwrap(),
+ "<p>page</p>"
+ );
+
+ let whole = dir.path().join("whole");
+ copy_directory_tree(&from, &whole, false).unwrap();
+ assert_eq!(fs::read_to_string(whole.join("SKILL.md")).unwrap(), "doc");
+ }
+
+ #[test]
+ fn moving_a_directory_capability_carries_its_tree() {
+ let dir = tempdir().unwrap();
+ let from = dir.path().join("skill");
+ let to = dir.path().join("moved/skill");
+ fs::create_dir_all(from.join("templates")).unwrap();
+ fs::write(from.join("SKILL.md"), "doc").unwrap();
+ fs::write(from.join("templates/page.html"), "<p>page</p>").unwrap();
+
+ move_capability_file(&from, &to).unwrap();
+ assert!(!from.exists());
+ assert_eq!(fs::read_to_string(to.join("SKILL.md")).unwrap(), "doc");
+ assert_eq!(
+ fs::read_to_string(to.join("templates/page.html")).unwrap(),
+ "<p>page</p>"
+ );
+ }
+
+ #[test]
+ fn moving_a_file_never_replaces_an_existing_destination() {
+ let dir = tempdir().unwrap();
+ let from = dir.path().join("from.md");
+ let to = dir.path().join("nested/to.md");
+ fs::write(&from, "source").unwrap();
+ move_capability_file(&from, &to).unwrap();
+ assert!(!from.exists());
+ assert_eq!(fs::read_to_string(&to).unwrap(), "source");
+
+ fs::write(&from, "second").unwrap();
+ assert!(move_capability_file(&from, &to).is_err());
+ assert_eq!(fs::read_to_string(&to).unwrap(), "source");
+ assert_eq!(fs::read_to_string(&from).unwrap(), "second");
+ }
}
diff --git a/crates/host-core/src/mcp_servers.rs b/crates/host-core/src/mcp_servers.rs
index 08d89a823..3840479ca 100644
--- a/crates/host-core/src/mcp_servers.rs
+++ b/crates/host-core/src/mcp_servers.rs
@@ -1,7 +1,8 @@
use crate::activation::{ActivationMode, ActivationScope};
use crate::agent_capabilities::{
- capability_dir, file_timestamp, normalize_project_path, sorted_files, CapabilityLevel,
- CapabilityState,
+ capability_dir, file_timestamp, move_capability_file, normalize_project_path,
+ set_moved_capability_state, sorted_files, suffixed_capability_id, suffixed_display_name,
+ CapabilityLevel, CapabilityState, CapabilityTarget,
};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
@@ -526,6 +527,96 @@ impl McpServerRegistry {
self.find(id, None, None)
}
+ /// Move one server between the global directory and a project's.
+ ///
+ /// The document moves instead of being copied: a copy would leave the old
+ /// level holding a definition the user just said belongs somewhere else.
+ /// When the destination already owns the same id or label the arriving
+ /// server is renamed, so both definitions survive with names that tell them
+ /// apart. Activation state follows the document.
+ pub fn transfer(
+ &mut self,
+ id: &str,
+ from: &CapabilityTarget,
+ to: &CapabilityTarget,
+ ) -> Result<McpServerRecord> {
+ let Some(source) = self.find(id, Some(from.level), from.project_path.as_deref())? else {
+ bail!("MCP_INVALID: unknown MCP server \"{id}\"");
+ };
+ if from.same_directory(to) {
+ return Ok(source);
+ }
+ let source_path = source
+ .path
+ .clone()
+ .ok_or_else(|| anyhow::anyhow!("MCP_INVALID: server has no configuration file"))?;
+ let existing = self.list(to.level, to.project_path.as_deref())?;
+ if existing.len() >= MAX_SERVERS {
+ bail!("MCP_INVALID: at most {MAX_SERVERS} MCP servers");
+ }
+ // Lowercased: `suffixed_capability_id` compares this way, and on a
+ // case-insensitive volume `MyServer.json` and `myserver.json` are one
+ // file, so a case-sensitive check would let the move overwrite it.
+ let taken_ids = existing
+ .iter()
+ .map(|record| record.id.to_lowercase())
+ .collect::<HashSet<_>>();
+ let taken_labels = existing
+ .iter()
+ .map(|record| record.label.to_lowercase())
+ .collect::<HashSet<_>>();
+ let (target_id, _) = suffixed_capability_id(&source.id, &taken_ids, 64)
+ .ok_or_else(|| anyhow::anyhow!("MCP_INVALID: no free id at the destination"))?;
+ let target_label = suffixed_display_name(&source.label, &taken_labels, MAX_VALUE_BYTES);
+
+ let mut config: McpConfig = serde_json::from_str(
+ &fs::read_to_string(&source_path)
+ .with_context(|| format!("read {source_path}"))?,
+ )
+ .with_context(|| format!("parse {source_path}"))?;
+ let rename = config.id != target_id || config.label != target_label;
+ if rename {
+ config.id = target_id.clone();
+ config.label = target_label;
+ check_len("label", &config.label)?;
+ }
+ let directory = capability_dir(to.level, to.project_path.as_deref(), "servers")?;
+ let target_path = directory.join(format!("{target_id}.json"));
+ if rename {
+ // Never replace what is already at the destination. On a
+ // case-insensitive volume `fs::write` would silently hit an
+ // existing `MyServer.json` from `myserver.json`; refusing is the
+ // only non-destructive answer there.
+ if target_path.exists() {
+ bail!(
+ "MCP_INVALID: destination already exists: {}",
+ target_path.display()
+ );
+ }
+ // The document has to change, so it is written first and the source
+ // removed only after the destination exists: a failure in between
+ // leaves a shadowed duplicate rather than no server at all.
+ fs::create_dir_all(&directory)?;
+ fs::write(&target_path, serde_json::to_string_pretty(&config)?)
+ .with_context(|| format!("write {}", target_path.display()))?;
+ fs::remove_file(&source_path).ok();
+ } else {
+ move_capability_file(Path::new(&source_path), &target_path)?;
+ }
+ set_moved_capability_state(
+ &mut self.state,
+ MCP_KIND,
+ from.level,
+ &source.id,
+ source.project_path.as_deref(),
+ to,
+ &target_id,
+ source.enabled,
+ )?;
+ self.find(&target_id, Some(to.level), to.project_path.as_deref())?
+ .ok_or_else(|| anyhow::anyhow!("MCP_INVALID: moved server was not found"))
+ }
+
/// Compatibility lookup for older host callers; management uses level-aware list/find paths.
#[allow(dead_code)]
pub fn get(&mut self, id: &str) -> Option<McpServerRecord> {
@@ -536,8 +627,18 @@ impl McpServerRegistry {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::agent_capabilities::test_support;
use tempfile::tempdir;
+ /// A registry plus the two directories a level switch needs.
+ fn scaffolding() -> (tempfile::TempDir, tempfile::TempDir, tempfile::TempDir) {
+ (
+ tempdir().unwrap(),
+ tempdir().unwrap(),
+ tempdir().unwrap(),
+ )
+ }
+
fn stdio(id: &str) -> McpServerInput {
McpServerInput {
id: id.into(),
@@ -665,4 +766,289 @@ mod tests {
Some(&project_path)
));
}
+
+ #[test]
+ fn a_global_server_moves_into_a_project_with_its_state() {
+ let (home, app, project) = scaffolding();
+ let project_path = project.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut input = stdio("files");
+ input.label = Some("Files".into());
+ registry.upsert(input).unwrap();
+ // Turned off for this one project only, which is the value a move
+ // has to carry because it is what the user was looking at.
+ registry
+ .set_enabled(
+ "files",
+ false,
+ Some(CapabilityLevel::Global),
+ Some(&project_path),
+ )
+ .unwrap();
+
+ let moved = registry
+ .transfer(
+ "files",
+ &CapabilityTarget::new(CapabilityLevel::Global, Some(&project_path)).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.level.as_deref(), Some("project"));
+ assert_eq!(moved.project_path.as_deref(), Some(project_path.as_str()));
+ assert!(!moved.enabled);
+ assert!(!home.path().join("servers/files.json").exists());
+ assert!(project.path().join(".agents/servers/files.json").is_file());
+ assert!(registry
+ .list(CapabilityLevel::Global, None)
+ .unwrap()
+ .is_empty());
+ // The global override is gone with the document, not left pointing
+ // at an id the global directory no longer holds.
+ assert!(registry
+ .state
+ .enabled(MCP_KIND, CapabilityLevel::Global, "files", Some(&project_path)));
+ });
+ }
+
+ #[test]
+ fn a_destination_collision_renames_the_arriving_server() {
+ let (home, app, project) = scaffolding();
+ let project_path = project.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut global = stdio("files");
+ global.label = Some("Files".into());
+ registry.upsert(global).unwrap();
+ let mut local = stdio("files");
+ local.label = Some("Files".into());
+ local.level = Some("project".into());
+ local.project_path = Some(project_path.clone());
+ registry.upsert(local).unwrap();
+
+ let moved = registry
+ .transfer(
+ "files",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.id, "files-2");
+ assert_eq!(moved.label, "Files (2)");
+ assert!(!home.path().join("servers/files.json").exists());
+ let listed = registry
+ .list(CapabilityLevel::Project, Some(&project_path))
+ .unwrap();
+ assert_eq!(listed.len(), 2);
+ // The server that was already there is untouched.
+ assert!(listed
+ .iter()
+ .any(|record| record.id == "files" && record.label == "Files"));
+ let document =
+ fs::read_to_string(project.path().join(".agents/servers/files-2.json")).unwrap();
+ assert!(document.contains("\"id\": \"files-2\""));
+ assert!(document.contains("\"label\": \"Files (2)\""));
+ });
+ }
+
+ #[test]
+ fn a_project_server_moves_to_global_without_leaving_a_project_override() {
+ let (home, app, project) = scaffolding();
+ let project_path = project.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut input = stdio("files");
+ input.label = Some("Files".into());
+ input.level = Some("project".into());
+ input.project_path = Some(project_path.clone());
+ input.enabled = Some(false);
+ registry.upsert(input).unwrap();
+
+ let moved = registry
+ .transfer(
+ "files",
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.level.as_deref(), Some("global"));
+ assert_eq!(moved.project_path, None);
+ assert!(!moved.enabled);
+ assert!(home.path().join("servers/files.json").is_file());
+ assert!(!project.path().join(".agents/servers/files.json").exists());
+ // The disabled state is now the global default: it follows the
+ // document, and no project-only entry is left behind.
+ assert!(!registry
+ .state
+ .enabled(MCP_KIND, CapabilityLevel::Global, "files", Some("/elsewhere")));
+ assert!(registry
+ .state
+ .enabled(MCP_KIND, CapabilityLevel::Project, "files", Some(&project_path)));
+ });
+ }
+
+ #[test]
+ fn transferring_within_one_directory_changes_nothing() {
+ let (home, app, project) = scaffolding();
+ let project_path = project.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut input = stdio("files");
+ input.label = Some("Files".into());
+ input.level = Some("project".into());
+ input.project_path = Some(project_path.clone());
+ registry.upsert(input).unwrap();
+
+ let target =
+ CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap();
+ let same = registry.transfer("files", &target, &target).unwrap();
+ assert_eq!(same.id, "files");
+ assert!(project.path().join(".agents/servers/files.json").is_file());
+ });
+ }
+
+ #[test]
+ fn transferring_an_unknown_server_is_an_error() {
+ let (home, app, _project) = scaffolding();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let error = registry
+ .transfer(
+ "missing",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ )
+ .unwrap_err();
+ assert!(error.to_string().contains("MCP_INVALID"));
+ });
+ }
+
+ #[test]
+ fn a_case_differing_id_at_the_destination_is_not_overwritten() {
+ let (home, app, project) = scaffolding();
+ let project_path = project.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut global = stdio("files");
+ global.label = Some("Files".into());
+ registry.upsert(global).unwrap();
+ let mut local = stdio("FILES");
+ local.label = Some("Uppercase files".into());
+ local.level = Some("project".into());
+ local.project_path = Some(project_path.clone());
+ registry.upsert(local).unwrap();
+ let existing =
+ fs::read_to_string(project.path().join(".agents/servers/FILES.json")).unwrap();
+
+ let moved = registry
+ .transfer(
+ "files",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ // `FILES` and `files` are the same file on macOS and Windows, so the
+ // arriving server must take a genuinely free id instead.
+ assert_eq!(moved.id, "files-2");
+ assert!(!home.path().join("servers/files.json").exists());
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/servers/FILES.json")).unwrap(),
+ existing
+ );
+ assert!(project.path().join(".agents/servers/files-2.json").is_file());
+ let listed = registry
+ .list(CapabilityLevel::Project, Some(&project_path))
+ .unwrap();
+ assert_eq!(listed.len(), 2);
+ });
+ }
+
+ #[test]
+ fn a_rename_never_writes_over_a_file_the_scan_does_not_list() {
+ let (home, app, project) = scaffolding();
+ let project_path = project.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut global = stdio("files");
+ global.label = Some("Files".into());
+ registry.upsert(global).unwrap();
+ // Two project entries: one listed server whose label forces the
+ // arriving server to rename, plus an unparseable file that occupies
+ // the destination path without appearing in any scan.
+ let mut local = stdio("other");
+ local.label = Some("Files".into());
+ local.level = Some("project".into());
+ local.project_path = Some(project_path.clone());
+ registry.upsert(local).unwrap();
+ let bogus = project.path().join(".agents/servers/files.json");
+ fs::write(&bogus, "not a server config").unwrap();
+
+ let error = registry
+ .transfer(
+ "files",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap_err();
+
+ assert!(error.to_string().contains("MCP_INVALID"));
+ assert_eq!(fs::read_to_string(&bogus).unwrap(), "not a server config");
+ // The move refused before deleting anything.
+ assert!(home.path().join("servers/files.json").is_file());
+ });
+ }
+
+ #[test]
+ fn moving_one_projects_server_to_global_keeps_another_projects_state() {
+ let (home, app, project) = scaffolding();
+ let other = tempdir().unwrap();
+ let project_a = project.path().to_str().unwrap().to_string();
+ let project_b = other.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut a = stdio("files");
+ a.label = Some("Files".into());
+ a.level = Some("project".into());
+ a.project_path = Some(project_a.clone());
+ a.enabled = Some(false);
+ registry.upsert(a).unwrap();
+ let mut b = stdio("files");
+ b.label = Some("Files".into());
+ b.level = Some("project".into());
+ b.project_path = Some(project_b.clone());
+ b.enabled = Some(false);
+ registry.upsert(b).unwrap();
+
+ registry
+ .transfer(
+ "files",
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_a)).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ )
+ .unwrap();
+
+ // Project B's document and its disabled state survive: moving A's
+ // same-id server says nothing about B.
+ assert!(other.path().join(".agents/servers/files.json").is_file());
+ assert!(!registry.state.enabled(
+ MCP_KIND,
+ CapabilityLevel::Project,
+ "files",
+ Some(&project_b)
+ ));
+ assert!(registry.state.enabled(
+ MCP_KIND,
+ CapabilityLevel::Project,
+ "files",
+ Some(&project_a)
+ ));
+ assert!(!registry
+ .state
+ .enabled(MCP_KIND, CapabilityLevel::Global, "files", None));
+ });
+ }
}
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 47c4fb2e6..d17631dd6 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -1173,6 +1173,40 @@ fn parse_capability_query(
Ok((level, project_path))
}
+/// Read one end of a move from a nested `{ level, projectPath }` object.
+///
+/// A move names two directories at once, so unlike the single-level queries it
+/// reads a named key instead of the flat params, and the two ends can never be
+/// confused for each other. `level` must be present and a string: defaulting a
+/// missing or non-string level to `global` would silently write a capability
+/// into the wrong directory, so it is rejected as invalid params instead.
+fn parse_capability_target(
+ params: &Value,
+ key: &str,
+) -> Result<crate::agent_capabilities::CapabilityTarget, JsonRpcError> {
+ let source = params
+ .get(key)
+ .ok_or_else(|| rpc_err(1002, format!("{key} required"), "INVALID_PARAMS"))?;
+ let level = match source.get("level") {
+ Some(Value::String(level)) => CapabilityLevel::parse(Some(level))
+ .map_err(|error| capability_err(error.to_string()))?,
+ _ => {
+ return Err(rpc_err(
+ 1002,
+ format!("{key}.level must be 'global' or 'project'"),
+ "INVALID_PARAMS",
+ ))
+ }
+ };
+ let project_path = source
+ .get("projectPath")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ .filter(|value| !value.trim().is_empty());
+ crate::agent_capabilities::CapabilityTarget::new(level, project_path.as_deref())
+ .map_err(|error| capability_err(error.to_string()))
+}
+
async fn handle_request(
state: Arc<Mutex<AppState>>,
method: &str,
@@ -4045,6 +4079,17 @@ async fn handle_request(
let server = st.mcp_servers.set_scope(&id, scope).map_err(scope_err)?;
Ok(json!({ "server": server }))
}
+ "mcp.transfer" => {
+ let id = require_id(&params)?;
+ let from = parse_capability_target(&params, "from")?;
+ let to = parse_capability_target(&params, "to")?;
+ let mut st = state.lock().await;
+ let server = st
+ .mcp_servers
+ .transfer(&id, &from, &to)
+ .map_err(scope_err)?;
+ Ok(json!({ "server": server }))
+ }
"skills.list" => {
let (level, project_path) = parse_capability_query(&params)?;
@@ -4141,6 +4186,17 @@ async fn handle_request(
let skill = st.user_skills.set_scope(&id, scope).map_err(skill_err)?;
Ok(json!({ "skill": skill }))
}
+ "skills.transfer" => {
+ let id = require_id(&params)?;
+ let from = parse_capability_target(&params, "from")?;
+ let to = parse_capability_target(&params, "to")?;
+ let mut st = state.lock().await;
+ let skill = st
+ .user_skills
+ .transfer(&id, &from, &to)
+ .map_err(skill_err)?;
+ Ok(json!({ "skill": skill }))
+ }
"agents.list" => {
let mut st = state.lock().await;
@@ -4348,10 +4404,11 @@ mod tests {
use tokio::sync::{mpsc, Mutex};
use super::{
- capability_err, handle_request, parse_capability_query, peek_jsonrpc_id, provider_rpc_err,
- resolve_plan_workspace, resolve_tool_workspace, resolve_tool_workspace_for_call, scope_err,
- skill_err,
+ capability_err, handle_request, parse_capability_query, parse_capability_target,
+ peek_jsonrpc_id, provider_rpc_err, resolve_plan_workspace, resolve_tool_workspace,
+ resolve_tool_workspace_for_call, scope_err, skill_err,
};
+ use crate::agent_capabilities::CapabilityLevel;
use crate::plans::{PlanResolveParams, PlanSubmitParams};
use crate::scheduled;
use crate::sessions;
@@ -4390,6 +4447,39 @@ mod tests {
);
}
+ #[test]
+ fn capability_target_requires_an_explicit_string_level() {
+ // A missing or non-string level must not fall back to `global`: that
+ // would write the capability into the wrong directory without telling
+ // the caller.
+ let missing = parse_capability_target(&json!({ "to": { "projectPath": "/p" } }), "to")
+ .expect_err("a target without a level is invalid");
+ assert_eq!(missing.code, 1002);
+ assert_eq!(
+ missing.data.as_ref().unwrap()["errorCode"],
+ json!("INVALID_PARAMS")
+ );
+
+ let wrong_type = parse_capability_target(&json!({ "to": { "level": 5 } }), "to")
+ .expect_err("a non-string level is invalid");
+ assert_eq!(wrong_type.code, 1002);
+ assert_eq!(
+ wrong_type.data.as_ref().unwrap()["errorCode"],
+ json!("INVALID_PARAMS")
+ );
+
+ let absent = parse_capability_target(&json!({}), "from")
+ .expect_err("the named end of a move is required");
+ assert_eq!(absent.code, 1002);
+
+ let project =
+ parse_capability_target(&json!({ "to": { "level": "project", "projectPath": "/p" } }), "to")
+ .unwrap();
+ assert_eq!(project.level, CapabilityLevel::Project);
+ let global = parse_capability_target(&json!({ "to": { "level": "global" } }), "to").unwrap();
+ assert_eq!(global.level, CapabilityLevel::Global);
+ }
+
#[test]
fn peek_jsonrpc_id_reads_a_string_id_from_a_truncated_prefix() {
let prefix =
diff --git a/crates/host-core/src/user_skills.rs b/crates/host-core/src/user_skills.rs
index 6a2afef10..102383a3e 100644
--- a/crates/host-core/src/user_skills.rs
+++ b/crates/host-core/src/user_skills.rs
@@ -1,7 +1,9 @@
use crate::activation::ActivationScope;
use crate::agent_capabilities::{
- capability_dir, capability_id, file_timestamp, normalize_project_path, parse_front_matter,
- path_stem_for_id, slugify, sorted_files, valid_capability_id, CapabilityLevel, CapabilityState,
+ capability_dir, capability_id, copy_directory_tree, display_name_candidate, file_timestamp,
+ move_capability_file, normalize_project_path, parse_front_matter, path_stem_for_id,
+ set_moved_capability_state, slugify, sorted_files, suffixed_capability_id, valid_capability_id,
+ CapabilityLevel, CapabilityState, CapabilityTarget, MAX_ID_SUFFIX,
};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
@@ -124,6 +126,334 @@ fn merge_active_records(
result
}
+/// The text after the opening `---` line, when `text` really starts frontmatter.
+///
+/// `parse_front_matter` accepts any first line that trims to `---`, so `--- `,
+/// `---\r` and `--- \r\n` all open a block. A stricter check here would send
+/// those documents down the "no frontmatter" path and copy the old block into
+/// the body of a fresh one, leaving two frontmatter blocks in the file.
+fn front_matter_body(text: &str) -> Option<&str> {
+ let newline = text.find('\n')?;
+ let first = text[..newline].trim_end_matches('\r');
+ if first.trim() != "---" {
+ return None;
+ }
+ Some(&text[newline + 1..])
+}
+
+/// Give a skill document the display name a destination needs, rewriting the
+/// frontmatter `name` line and nothing else.
+///
+/// A move that has to rename must not reformat the document: `render_document`
+/// normalizes prose, drops unknown frontmatter keys, and re-indents the body,
+/// which would silently edit a file the user only asked to relocate. Everything
+/// outside the rewritten lines — extra fields, whitespace, line endings — is
+/// copied through byte for byte.
+fn rewrite_document_name(raw: &str, name: &str) -> String {
+ let value = name.replace(['\n', '\r'], " ");
+ let (bom, text) = match raw.strip_prefix('\u{feff}') {
+ Some(rest) => ("\u{feff}", rest),
+ None => ("", raw),
+ };
+ let Some(front) = front_matter_body(text) else {
+ return with_fresh_frontmatter(bom, text, &value);
+ };
+ let mut out = String::with_capacity(raw.len() + value.len() + 16);
+ out.push_str(bom);
+ out.push_str("---\n");
+ let mut cursor = 0usize;
+ let mut replaced = false;
+ while cursor < front.len() {
+ let end = match front[cursor..].find('\n') {
+ Some(at) => cursor + at + 1,
+ None => front.len(),
+ };
+ let line = &front[cursor..end];
+ if line.trim_end_matches(['\n', '\r']).trim() == "---" {
+ if !replaced {
+ out.push_str(&format!("name: {value}\n"));
+ }
+ // The terminator and everything after it, body included, is copied
+ // through untouched.
+ out.push_str(&front[cursor..]);
+ return out;
+ }
+ let top_level = !line.starts_with(' ') && !line.starts_with('\t');
+ let is_name = top_level
+ && line
+ .trim_end_matches(['\n', '\r'])
+ .split_once(':')
+ .is_some_and(|(key, _)| key.trim().eq_ignore_ascii_case("name"));
+ if is_name {
+ if !replaced {
+ out.push_str(&format!("name: {value}\n"));
+ replaced = true;
+ }
+ // A later `name:` line is dropped rather than kept: the parser
+ // inserts into a map, so the *last* line wins. Keeping a stale one
+ // would silently defeat the rename — the document would keep its
+ // old display name while the move claims it was changed.
+ } else {
+ out.push_str(line);
+ }
+ cursor = end;
+ }
+ // An unterminated opening delimiter is not frontmatter (`parse_front_matter`
+ // rejects it), so the text becomes the body of a fresh, complete block.
+ with_fresh_frontmatter(bom, text, &value)
+}
+
+fn with_fresh_frontmatter(bom: &str, text: &str, value: &str) -> String {
+ format!(
+ "{bom}---\nname: {value}\n---\n\n{}",
+ text.trim_start_matches(['\n', '\r'])
+ )
+}
+
+/// The directory a `<skill>/SKILL.md` document owns, when the document really is
+/// the directory shape.
+///
+/// A skill may ship sibling resources next to its `SKILL.md`, so moving one
+/// document is not enough — the directory is the unit. The guard matters: a
+/// loose `SKILL.md` sitting directly in the skills directory has the skills
+/// directory itself as its parent, and treating that as the unit would move
+/// every skill at once.
+fn directory_skill_root(path: &Path, skills_dir: &Path) -> Option<PathBuf> {
+ if !path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .is_some_and(|name| name.eq_ignore_ascii_case("SKILL.md"))
+ {
+ return None;
+ }
+ let dir = path.parent()?;
+ if dir == skills_dir {
+ return None;
+ }
+ Some(dir.to_path_buf())
+}
+
+/// Where an arriving skill document should land, and under which display name.
+struct SkillPlacement {
+ name: String,
+ stem: String,
+}
+
+/// The document a skill with `stem` occupies inside the skills directory.
+///
+/// Directory-shape skills live at `<stem>/SKILL.md` because the scan gives that
+/// document the *directory* name as its path-derived id; flat skills are one
+/// `<stem>.md` file. The two shapes are why the landing path cannot be derived
+/// from the stem alone.
+fn skill_document_path(directory: &Path, stem: &str, shared_directory: bool) -> PathBuf {
+ if shared_directory {
+ directory.join(stem).join("SKILL.md")
+ } else {
+ directory.join(format!("{stem}.md"))
+ }
+}
+
+/// Choose the name and file stem an arriving skill must use at a destination.
+///
+/// The scan, not the move, decides the arriving document's id: it derives the
+/// id from the frontmatter name first and only then from the path. Planning
+/// against the file stem alone therefore mismatches every document whose name
+/// slugs to something else — a Chinese name, or a name whose slug happens to be
+/// another document's id — and a mismatch hides documents: the source is
+/// already gone while the arrival is either not found or loses the scan's
+/// `seen` de-duplication. So every candidate is put through the real
+/// `capability_id` for the exact path it would land on, and only a placement
+/// the scan lists as its own record is accepted. `shared_directory` selects the
+/// destination's shape, because that shape decides what `path_stem_for_id`
+/// reads.
+fn plan_skill_placement(
+ source: &UserSkillRecord,
+ directory: &Path,
+ shared_directory: bool,
+ existing: &[UserSkillRecord],
+) -> Option<SkillPlacement> {
+ let taken_names = existing
+ .iter()
+ .map(|record| record.name.to_lowercase())
+ .collect::<HashSet<_>>();
+ // Ids are compared lowercased, like the filesystem that will hold them.
+ let taken_ids = existing
+ .iter()
+ .map(|record| record.id.to_lowercase())
+ .collect::<HashSet<_>>();
+ for ordinal in 1..=MAX_ID_SUFFIX {
+ let name = display_name_candidate(&source.name, ordinal, MAX_NAME_CHARS);
+ // A duplicate display name makes shadowing merge two records on the
+ // next scan, so the destination may not already have it.
+ if name.is_empty() || taken_names.contains(&name.to_lowercase()) {
+ continue;
+ }
+ // The scan prefers the name's slug, so a valid slug *is* the id the
+ // document will carry and the file stem has to match it.
+ let from_name = slugify(&name, 64);
+ let stem = if valid_capability_id(&from_name, 64) {
+ from_name
+ } else {
+ suffixed_capability_id(&source.id, &taken_ids, 64)?.0
+ };
+ let document_path = skill_document_path(directory, &stem, shared_directory);
+ // Something already on disk at this path is either a listed document
+ // (caught again below) or one the scan refuses to list; never write
+ // over it.
+ if document_path.exists() {
+ continue;
+ }
+ // Simulate the real scan: `capability_id` can still land on an id the
+ // name slug did not predict (the path fallback), and an id collision
+ // makes one of the two documents disappear from the catalog.
+ let id = capability_id(&name, &document_path, 64);
+ if !valid_capability_id(&id, 64) || taken_ids.contains(&id.to_lowercase()) {
+ continue;
+ }
+ return Some(SkillPlacement { name, stem });
+ }
+ None
+}
+
+/// True when a scanned record path names the document a move just wrote.
+///
+/// The record path comes back from a directory scan and the planned path from a
+/// join, so the comparison is normalized and case-insensitive — the same rules
+/// project paths use, and the only rules that hold on a volume that ignores
+/// case.
+fn same_document(record_path: &str, planned: &Path) -> bool {
+ normalize_project_path(record_path)
+ .eq_ignore_ascii_case(&normalize_project_path(&planned.to_string_lossy()))
+}
+
+impl UserSkillRegistry {
+ /// Move one skill between the global directory and a project's.
+ ///
+ /// The document moves instead of being copied: a copy would leave the old
+ /// level holding a skill the user just said belongs somewhere else. When the
+ /// destination already owns the same id or display name the arriving skill
+ /// is renamed, so both survive under names that tell them apart. The
+ /// arriving document's id is read back from a scan by path, because a
+ /// skill's id can come from its name rather than its file stem, and the
+ /// state is written only once that record exists. A landing the scan would
+ /// hide is rolled back to the source instead of stranding the skill.
+ pub fn transfer(
+ &mut self,
+ id: &str,
+ from: &CapabilityTarget,
+ to: &CapabilityTarget,
+ ) -> Result<UserSkillRecord> {
+ let Some(source) = self.find(id, Some(from.level), from.project_path.as_deref())? else {
+ bail!("SKILL_INVALID: unknown skill \"{id}\"");
+ };
+ if from.same_directory(to) {
+ return Ok(source);
+ }
+ let source_path = PathBuf::from(&source.path);
+ let raw = fs::read_to_string(&source_path)
+ .with_context(|| format!("read {}", source_path.display()))?;
+ if raw.len() > MAX_SKILL_BYTES {
+ bail!("SKILL_INVALID: document exceeds {MAX_SKILL_BYTES} bytes");
+ }
+ let existing = self.list(to.level, to.project_path.as_deref())?;
+ if existing.len() >= MAX_SKILLS {
+ bail!("SKILL_INVALID: at most {MAX_SKILLS} skills");
+ }
+
+ let source_dir = capability_dir(from.level, from.project_path.as_deref(), "skills")?;
+ let directory = capability_dir(to.level, to.project_path.as_deref(), "skills")?;
+ let owned_dir = directory_skill_root(&source_path, &source_dir);
+ let shared_directory = owned_dir.is_some();
+ let placement = plan_skill_placement(&source, &directory, shared_directory, &existing)
+ .ok_or_else(|| anyhow::anyhow!("SKILL_INVALID: no free name at the destination"))?;
+ let document_path = skill_document_path(&directory, &placement.stem, shared_directory);
+ let source_unit = owned_dir.clone().unwrap_or_else(|| source_path.clone());
+ let target_unit = if shared_directory {
+ match document_path.parent() {
+ Some(parent) => parent.to_path_buf(),
+ None => directory.join(&placement.stem),
+ }
+ } else {
+ document_path.clone()
+ };
+ let rewritten = placement.name != source.name;
+
+ if !rewritten {
+ move_capability_file(&source_unit, &target_unit)?;
+ } else {
+ let document = rewrite_document_name(&raw, &placement.name);
+ if document.len() > MAX_SKILL_BYTES {
+ bail!("SKILL_INVALID: document exceeds {MAX_SKILL_BYTES} bytes");
+ }
+ if shared_directory && target_unit.exists() {
+ // The destination id is unique at this level, so `<stem>/` is a
+ // directory this move creates. Anything already sitting there
+ // is not this skill's to overwrite or merge into.
+ bail!(
+ "SKILL_INVALID: destination already exists: {}",
+ target_unit.display()
+ );
+ }
+ if let Some(parent) = document_path.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ // Written before the source is removed, so a failure in between
+ // leaves a shadowed duplicate rather than no skill at all.
+ fs::write(&document_path, document)
+ .with_context(|| format!("write {}", document_path.display()))?;
+ if let Some(dir) = &owned_dir {
+ // Only the document travelled; resources beside it are part of
+ // the skill, so the rest of the directory follows. The landing
+ // directory is new, so overwriting a same-named leftover from
+ // an interrupted move is safe.
+ copy_directory_tree(dir, &target_unit, true)?;
+ fs::remove_dir_all(dir)
+ .map_err(|error| anyhow::anyhow!("remove {}: {error}", dir.display()))?;
+ } else {
+ fs::remove_file(&source_path)
+ .map_err(|error| anyhow::anyhow!("remove {}: {error}", source_path.display()))?;
+ }
+ }
+
+ // The record is resolved by path, never by the planned stem: the scan
+ // derives the arriving document's id from its name, and the name's slug
+ // is not necessarily the file stem this move chose.
+ let landed = self
+ .list(to.level, to.project_path.as_deref())?
+ .into_iter()
+ .find(|record| same_document(&record.path, &document_path));
+ let Some(moved) = landed else {
+ // The document is on disk but the scan will not list it (empty
+ // body, over the byte limit, or shadowed by a same-id document).
+ // The source is already gone, so the move has to be undone: put the
+ // unit back where it came from and restore the original bytes,
+ // because the rewritten name would give the restored document a
+ // different id. State was never written, so nothing else changes.
+ move_capability_file(&target_unit, &source_unit).map_err(|error| {
+ anyhow::anyhow!(
+ "SKILL_INVALID: the moved skill was not found and could not be restored to {}: {error}",
+ source_unit.display()
+ )
+ })?;
+ fs::write(&source_path, &raw)
+ .with_context(|| format!("restore {}", source_path.display()))?;
+ bail!("SKILL_INVALID: moved skill was not found");
+ };
+ set_moved_capability_state(
+ &mut self.state,
+ SKILL_KIND,
+ from.level,
+ &source.id,
+ source.project_path.as_deref(),
+ to,
+ &moved.id,
+ source.enabled,
+ )?;
+ self.find(&moved.id, Some(to.level), to.project_path.as_deref())?
+ .ok_or_else(|| anyhow::anyhow!("SKILL_INVALID: moved skill was not found"))
+ }
+}
+
impl UserSkillRegistry {
pub fn new(data_dir: &Path) -> Self {
Self {
@@ -512,6 +842,7 @@ fn scope_for(level: CapabilityLevel, project_path: Option<&str>) -> ActivationSc
#[cfg(test)]
mod tests {
use super::*;
+ use crate::agent_capabilities::test_support;
use tempfile::tempdir;
fn input(name: &str, level: &str, project_path: Option<&str>) -> UserSkillInput {
@@ -685,4 +1016,489 @@ mod tests {
let ids: Vec<_> = listed.iter().map(|record| record.id.as_str()).collect();
assert_eq!(ids, vec!["docx", "pdf"]);
}
+
+ /// A global skill document plus the project directory it can move into.
+ fn skill_home(home: &Path) {
+ fs::create_dir_all(home.join("skills")).unwrap();
+ }
+
+ fn project_dir(project: &Path) -> String {
+ project.to_str().unwrap().to_string()
+ }
+
+ fn record(id: &str, name: &str) -> UserSkillRecord {
+ UserSkillRecord {
+ id: id.into(),
+ name: name.into(),
+ level: None,
+ project_path: None,
+ description: None,
+ enabled: true,
+ scope: ActivationScope::default(),
+ source: "imported".into(),
+ path: String::new(),
+ size_bytes: 0,
+ created_at: String::new(),
+ updated_at: String::new(),
+ }
+ }
+
+ /// A level may never list two records with the same id or the same name:
+ /// either collision makes one of them disappear from the catalog.
+ fn assert_unique_records(records: &[UserSkillRecord]) {
+ let ids: HashSet<&str> = records.iter().map(|record| record.id.as_str()).collect();
+ let names: HashSet<String> = records
+ .iter()
+ .map(|record| record.name.to_lowercase())
+ .collect();
+ assert_eq!(ids.len(), records.len(), "duplicate ids: {records:?}");
+ assert_eq!(names.len(), records.len(), "duplicate names: {records:?}");
+ }
+
+ #[test]
+ fn a_global_skill_moves_into_a_project() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ fs::write(
+ home.path().join("skills/review.md"),
+ "---\nname: Review\ndescription: Check code\n---\n\nDo it.\n",
+ )
+ .unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "review",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.id, "review");
+ assert_eq!(moved.level.as_deref(), Some("project"));
+ assert_eq!(moved.project_path.as_deref(), Some(project_path.as_str()));
+ assert!(!home.path().join("skills/review.md").exists());
+ let target = project.path().join(".agents/skills/review.md");
+ assert_eq!(
+ fs::read_to_string(&target).unwrap(),
+ "---\nname: Review\ndescription: Check code\n---\n\nDo it.\n"
+ );
+ assert!(registry.list(CapabilityLevel::Global, None).unwrap().is_empty());
+ });
+ }
+
+ #[test]
+ fn a_name_collision_rewrites_only_the_documents_name_line() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ fs::create_dir_all(project.path().join(".agents/skills")).unwrap();
+ // Extra frontmatter and deliberate body formatting: a renaming move
+ // must not reformat the document the user only asked to relocate.
+ let original = "---\nname: Review\nlicense: MIT\n---\n\n## Step 1\n\n indented\n";
+ fs::write(home.path().join("skills/review.md"), original).unwrap();
+ fs::write(
+ project.path().join(".agents/skills/review.md"),
+ "---\nname: Review\n---\n\nProject copy\n",
+ )
+ .unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "review",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.id, "review-2");
+ assert_eq!(moved.name, "Review (2)");
+ let document =
+ fs::read_to_string(project.path().join(".agents/skills/review-2.md")).unwrap();
+ assert_eq!(
+ document,
+ "---\nname: Review (2)\nlicense: MIT\n---\n\n## Step 1\n\n indented\n"
+ );
+ // The skill that was already there is untouched.
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/skills/review.md")).unwrap(),
+ "---\nname: Review\n---\n\nProject copy\n"
+ );
+ });
+ }
+
+ #[test]
+ fn a_directory_skill_moves_with_its_resources() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ let source = home.path().join("skills/pdf");
+ fs::create_dir_all(source.join("templates")).unwrap();
+ fs::write(source.join("SKILL.md"), "# PDF\n\nExtract text.\n").unwrap();
+ fs::write(source.join("templates/page.html"), "<p>page</p>").unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "pdf",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.id, "pdf");
+ assert!(!source.exists());
+ let target = project.path().join(".agents/skills/pdf");
+ assert_eq!(
+ fs::read_to_string(target.join("SKILL.md")).unwrap(),
+ "# PDF\n\nExtract text.\n"
+ );
+ // The resource beside the document is part of the skill.
+ assert_eq!(
+ fs::read_to_string(target.join("templates/page.html")).unwrap(),
+ "<p>page</p>"
+ );
+ });
+ }
+
+ #[test]
+ fn a_renamed_directory_skill_keeps_its_resources() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ fs::create_dir_all(project.path().join(".agents/skills/pdf")).unwrap();
+ fs::write(
+ project.path().join(".agents/skills/pdf/SKILL.md"),
+ "# PDF\n\nProject copy.\n",
+ )
+ .unwrap();
+ let source = home.path().join("skills/pdf");
+ fs::create_dir_all(&source).unwrap();
+ fs::write(source.join("SKILL.md"), "# PDF\n\nGlobal copy.\n").unwrap();
+ fs::write(source.join("notes.txt"), "keep me").unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "pdf",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.id, "pdf-2");
+ assert!(!source.exists());
+ let target = project.path().join(".agents/skills/pdf-2");
+ assert_eq!(
+ fs::read_to_string(target.join("notes.txt")).unwrap(),
+ "keep me"
+ );
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/skills/pdf/SKILL.md")).unwrap(),
+ "# PDF\n\nProject copy.\n"
+ );
+ });
+ }
+
+ #[test]
+ fn a_disabled_project_skill_becomes_the_global_default() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ let mut registry = UserSkillRegistry::new(app.path());
+ let mut request = input("Review", "project", Some(&project_path));
+ request.enabled = Some(false);
+ registry.create(request).unwrap();
+
+ let moved = registry
+ .transfer(
+ "review",
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.level.as_deref(), Some("global"));
+ assert!(!moved.enabled);
+ assert!(home.path().join("skills/review.md").is_file());
+ assert!(!project.path().join(".agents/skills/review.md").exists());
+ // Off everywhere, because the document is off and its state is now
+ // the global default rather than one project's leftover override.
+ assert!(!registry
+ .state
+ .enabled(SKILL_KIND, CapabilityLevel::Global, "review", Some("/elsewhere")));
+ });
+ }
+
+ #[test]
+ fn a_skill_without_frontmatter_gains_a_name_when_it_has_to_rename() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ fs::create_dir_all(project.path().join(".agents/skills")).unwrap();
+ // No frontmatter: the display name falls back to the file stem, so a
+ // move that must rename has to open a block to carry the new name.
+ fs::write(home.path().join("skills/review.md"), "# Review\n\nDo it.\n").unwrap();
+ fs::write(
+ project.path().join(".agents/skills/review.md"),
+ "---\nname: Review\n---\n\nProject copy\n",
+ )
+ .unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "review",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+ // With no stored name the display name is the file stem, so that is
+ // what the suffix is applied to.
+ assert_eq!(moved.id, "review-2");
+ assert_eq!(moved.name, "review (2)");
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/skills/review-2.md")).unwrap(),
+ "---\nname: review (2)\n---\n\n# Review\n\nDo it.\n"
+ );
+ });
+ }
+
+ #[test]
+ fn placement_uses_the_id_the_scan_will_derive_from_the_name() {
+ let directory = tempdir().unwrap();
+ let source = record("code-review", "代码审查");
+ let existing = vec![record("code-review", "代码审查")];
+
+ let placement = plan_skill_placement(&source, directory.path(), true, &existing).unwrap();
+ assert_eq!(placement.name, "代码审查 (2)");
+ // The rename's slug is `2`, not the file stem the move started from, so
+ // that is what both the directory and the next scan will call it.
+ assert_eq!(placement.stem, "2");
+ let document = skill_document_path(directory.path(), &placement.stem, true);
+ assert_eq!(capability_id(&placement.name, &document, 64), placement.stem);
+
+ // A flat destination derives the same id from the `.md` stem.
+ let placement = plan_skill_placement(&source, directory.path(), false, &existing).unwrap();
+ let document = skill_document_path(directory.path(), &placement.stem, false);
+ assert_eq!(capability_id(&placement.name, &document, 64), placement.stem);
+ }
+
+ #[test]
+ fn placement_reports_exhaustion_instead_of_reusing_a_taken_name() {
+ let directory = tempdir().unwrap();
+ let source = record("review", "Review");
+ let existing: Vec<UserSkillRecord> = (1..=MAX_ID_SUFFIX)
+ .map(|ordinal| {
+ record(
+ &format!("other-{ordinal}"),
+ &display_name_candidate("Review", ordinal, MAX_NAME_CHARS),
+ )
+ })
+ .collect();
+ // Every candidate the planner could use is already a displayed name, so
+ // there is no collision-free placement and the move must refuse rather
+ // than write a duplicate.
+ assert!(plan_skill_placement(&source, directory.path(), false, &existing).is_none());
+ }
+
+ #[test]
+ fn a_chinese_named_skill_moves_without_hiding_the_other_levels_copy() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ fs::create_dir_all(project.path().join(".agents/skills")).unwrap();
+ // Both names slug to nothing, so each document's id comes from its
+ // file stem — while the renamed candidate `代码审查 (2)` slugs to
+ // `2`, which is nothing like the stem the old move would have used.
+ fs::write(
+ home.path().join("skills/code-review.md"),
+ "---\nname: 代码审查\n---\n\nGlobal copy.\n",
+ )
+ .unwrap();
+ fs::write(
+ project.path().join(".agents/skills/code-review.md"),
+ "---\nname: 代码审查\n---\n\nProject copy.\n",
+ )
+ .unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "code-review",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.id, "2");
+ assert_eq!(moved.name, "代码审查 (2)");
+ assert!(!home.path().join("skills/code-review.md").exists());
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/skills/2.md")).unwrap(),
+ "---\nname: 代码审查 (2)\n---\n\nGlobal copy.\n"
+ );
+ // The project's own copy is untouched and both documents are listed
+ // under distinct ids and names.
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/skills/code-review.md")).unwrap(),
+ "---\nname: 代码审查\n---\n\nProject copy.\n"
+ );
+ let listed = registry
+ .list(CapabilityLevel::Project, Some(&project_path))
+ .unwrap();
+ assert_eq!(listed.len(), 2);
+ assert_unique_records(&listed);
+ assert!(listed.iter().any(|record| record.name == "代码审查"));
+ assert!(listed.iter().any(|record| record.name == "代码审查 (2)"));
+
+ // The same document moves back to the global level under its new
+ // name, keeping the id the scan gave it.
+ let back = registry
+ .transfer(
+ "2",
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ )
+ .unwrap();
+ assert_eq!(back.id, "2");
+ assert_eq!(back.name, "代码审查 (2)");
+ assert!(home.path().join("skills/2.md").is_file());
+ assert_unique_records(
+ &registry
+ .list(CapabilityLevel::Project, Some(&project_path))
+ .unwrap(),
+ );
+ });
+ }
+
+ #[test]
+ fn a_names_slug_is_not_used_when_that_id_belongs_to_another_document() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ fs::create_dir_all(project.path().join(".agents/skills")).unwrap();
+ fs::write(
+ home.path().join("skills/code-review.md"),
+ "---\nname: 代码审查\n---\n\nGlobal copy.\n",
+ )
+ .unwrap();
+ fs::write(
+ project.path().join(".agents/skills/code-review.md"),
+ "---\nname: 代码审查\n---\n\nProject copy.\n",
+ )
+ .unwrap();
+ // This document's id is exactly the slug the renamed candidate
+ // `代码审查 (2)` would produce, so that candidate cannot be used.
+ fs::write(
+ project.path().join(".agents/skills/2.md"),
+ "---\nname: 2\n---\n\nTakes the id 2.\n",
+ )
+ .unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "code-review",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.name, "代码审查 (3)");
+ assert_eq!(moved.id, "3");
+ assert!(project.path().join(".agents/skills/3.md").is_file());
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/skills/2.md")).unwrap(),
+ "---\nname: 2\n---\n\nTakes the id 2.\n"
+ );
+ let listed = registry
+ .list(CapabilityLevel::Project, Some(&project_path))
+ .unwrap();
+ assert_eq!(listed.len(), 3);
+ assert_unique_records(&listed);
+ });
+ }
+ #[test]
+ fn rewriting_a_name_keeps_the_frontmatter_shaped_document_intact() {
+ // The helper is unit-tested directly because it is the only place a move
+ // edits a document, and every byte it does not touch is a byte the user
+ // gets to keep.
+ let with_extra_fields =
+ "---\nlicense: MIT\nname: Review\nallowed-tools: Read\n---\n\nBody\n";
+ assert_eq!(
+ rewrite_document_name(with_extra_fields, "Review (2)"),
+ "---\nlicense: MIT\nname: Review (2)\nallowed-tools: Read\n---\n\nBody\n"
+ );
+ assert_eq!(
+ rewrite_document_name("---\r\nname: A\r\n---\r\n\r\nBody\r\n", "B"),
+ "---\nname: B\n---\r\n\r\nBody\r\n"
+ );
+ assert_eq!(
+ rewrite_document_name("no frontmatter\n", "B"),
+ "---\nname: B\n---\n\nno frontmatter\n"
+ );
+ assert_eq!(
+ rewrite_document_name("---\nname: A\nnever closed\n", "B"),
+ "---\nname: B\n---\n\n---\nname: A\nnever closed\n"
+ );
+ // A newline in the name would break the block it is written into.
+ assert_eq!(
+ rewrite_document_name("---\nname: A\n---\n\nBody\n", "Two\nLines"),
+ "---\nname: Two Lines\n---\n\nBody\n"
+ );
+ // The parser keeps the *last* `name:` line, so a stale second one must
+ // be dropped: keeping it would make the old name win again on the next
+ // scan, silently defeating the rename.
+ assert_eq!(
+ rewrite_document_name("---\nname: A\nname: B\n---\n\nBody\n", "C"),
+ "---\nname: C\n---\n\nBody\n"
+ );
+ assert_eq!(
+ rewrite_document_name("---\nname: A\nlicense: MIT\nname: B\n---\n\nBody\n", "C"),
+ "---\nname: C\nlicense: MIT\n---\n\nBody\n"
+ );
+ // A first line that only trims to `---` still opens frontmatter. Not
+ // recognizing it would copy the old block into the new body, leaving
+ // two frontmatter blocks in the document.
+ assert_eq!(
+ rewrite_document_name("--- \nname: A\n---\n\nBody\n", "C"),
+ "---\nname: C\n---\n\nBody\n"
+ );
+ assert_eq!(
+ rewrite_document_name("--- \r\nname: A\r\n---\r\n\r\nBody\r\n", "C"),
+ "---\nname: C\n---\r\n\r\nBody\r\n"
+ );
+ // An indented `name:` is a nested map value, not the document's name.
+ assert_eq!(
+ rewrite_document_name("---\nmeta:\n name: A\nname: B\n---\n\nBody\n", "C"),
+ "---\nmeta:\n name: A\nname: C\n---\n\nBody\n"
+ );
+ }
}
diff --git a/docs/adr/0267-capability-level-transfer.md b/docs/adr/0267-capability-level-transfer.md
new file mode 100644
index 000000000..23c61d7d8
--- /dev/null
+++ b/docs/adr/0267-capability-level-transfer.md
@@ -0,0 +1,155 @@
+# ADR 0267: Move capability documents between the global and project levels
+
+- Status: Accepted for implementation
+- Date: 2026-09-16
+- Amends: ADR 0112 (agent capability management roots and Settings IA — adds a
+ cross-level move to the capability surfaces)
+- Related: ADR 0056 (user-owned MCP servers and skills), D193, D194
+
+## Context
+
+ADR 0112 made `.agents` the only capability root and separated file ownership
+from app-local activation state: an MCP server or skill lives globally
+(`~/.agents/servers`, `~/.agents/skills`) or inside a project
+(`<project>/.agents/...`), while `<data>/agent-capabilities/*.json` records
+whether it is enabled, with a per-project override for global documents. The two
+levels were reachable only as two independent lists. Changing a capability's
+level therefore meant deleting the file at one level and recreating it at the
+other: the user had to retype the document, the enablement decision was lost,
+and a mistake destroyed the only copy. Nothing in the Settings IA expressed the
+switch as one action.
+
+Users do legitimately change their mind about ownership — a scratch server
+graduates from one project to every project, or a global experiment turns out to
+belong to one repository. This ADR records the move that the MCP and Skill pages
+now expose (`mcp.transfer` / `skills.transfer`).
+
+## Decision
+
+### 1. A level switch moves the document; it does not copy it
+
+The file's level *is* its ownership. A copy would leave the source level holding
+a definition the user just said belongs elsewhere, so the same capability would
+appear twice with two names until the user cleaned up the old one — and the two
+would drift. The source level stops listing the entry, and the destination holds
+the only file.
+
+The move is one unit per capability: `McpServerRegistry::transfer` relocates the
+server's JSON file, and `UserSkillRegistry::transfer` relocates either the single
+Markdown document or, for the conventional `<skill>/SKILL.md` shape, the whole
+skill directory with the sibling resources a `Skill` invocation resolves
+(`directory_skill_root`, `copy_directory_contents`). `move_capability_file`
+tries `fs::rename` first so a same-filesystem move is atomic and cheap, and
+falls back to copy-then-remove for a project on another mount. When the document
+must be rewritten (the rename case below), the destination is written before the
+source is removed, so an interrupted move leaves a shadowed duplicate rather
+than no capability at all.
+
+### 2. A destination collision renames the arriving document; it never blocks the move
+
+The destination level may already own the same id, or the same display name /
+label compared case-insensitively, the way project-over-global shadowing
+compares it. Overwriting an existing document would be data loss, and refusing
+the move would make the level switch useless whenever both sides happen to share
+a name. The arriving document is therefore disambiguated the way a file manager
+disambiguates a copy: a colliding id takes a `-2`/`-3`… suffix (within the
+64-character id budget, `suffixed_capability_id`), and a colliding display name
+takes a ` (2)`/` (3)`… suffix (`suffixed_display_name`). The existing entry and
+its file stay untouched, and the RPC response returns the record under the id
+it landed on so the UI can follow the rename.
+
+Renaming a skill rewrites only the frontmatter `name` line
+(`rewrite_document_name`); every other frontmatter field, the whitespace, the
+line endings, and the body are copied byte for byte, because the user asked to
+relocate a document, not to reformat it. A document with no parsable frontmatter
+block gets a fresh one so the renamed file is still scannable.
+
+A skill's identity is not its file name, and the move has to plan against the
+scanner rather than the filesystem. The catalog derives a skill's id with
+`capability_id`: the slug of the frontmatter `name` when that slug is usable,
+otherwise the slug of the path stem, and a hash as a last resort. A Chinese
+name, or a name whose slug already belongs to another document, therefore lands
+on an id the file name does not predict. Choosing a file name first and reading
+the id back from it produced exactly the failure this decision avoids: the
+source file was gone while the arrival was reported missing, and a same-id
+document silently lost the scan's de-duplication and vanished from Settings.
+`plan_skill_placement` now replays the real `capability_id` for the exact path
+each candidate would occupy, accepts only a placement the scan lists as its own
+record, and `transfer` resolves the arrived record by path — never by the stem
+it chose — so the state entry is written under the id the catalog will read
+back. A landing the scan still refuses (an empty body, an oversized document)
+is rolled back to the source with its original bytes, because no state has been
+written yet and a loud error beats a stranded file.
+
+The same reasoning makes id collisions case-insensitive: macOS and Windows both
+hand back one file for `MyServer.json` and `myserver.json`, so a move that
+compared ids literally would write over a definition it never listed.
+
+
+One artifact of that pre-existing `capability_id` rule is accepted rather than
+changed here: a non-ASCII name that has to be suffixed gains ASCII characters,
+and those characters alone become its slug. A Chinese-named skill arriving
+beside a same-named one therefore lands on the id `2`, not on a readable stem.
+Making the slug ignore a purely numeric remainder would change how every
+imported document is identified, which is a wider decision than a level move.
+### 3. Activation state follows the document
+
+State is app-local and ownership-free, so a move that left the old enablement
+behind would silently change whether the capability runs, and a move that left
+entries at the source level would leave pointers to an id that no longer exists
+there. `set_moved_capability_state` therefore drops the source level's state for
+the old id — via `CapabilityState::forget`, including every project override a
+moved global document had — and writes the value the source row was showing at
+the destination:
+
+- moving into a project stores that project's own state;
+- moving into global stores that value as the new global default, never another
+ project's override, because the move says nothing about the projects the
+ document left behind.
+
+A global source read may carry a `projectPath`, which is exactly the context the
+visible value is resolved in; `CapabilityTarget` keeps that field so the two
+meanings — "owner" and "state context" — are never confused.
+
+### 4. The two ends are explicit and a same-directory move is a no-op
+
+`mcp.transfer` / `skills.transfer` take `{ id, from, to }`, each end a
+`{ level, projectPath? }` target, instead of a single level and an implicit
+"other side": the two ends can never be derived from one another wrongly, and a
+project-level end without `projectPath` fails with `CAPABILITY_INVALID`.
+`CapabilityTarget::same_directory` makes a move whose ends name the same
+directory a no-op that returns the current record, so a UI that offers the
+action redundantly can never rewrite the file.
+
+### 5. The global `.agents` root has a redirect seam
+
+`PI_DESKTOP_AGENTS_DIR` repoints the global capability root, the way
+`PI_DESKTOP_DATA_DIR` repoints the app-local data directory; an empty value
+falls back to the home directory (`AGENTS_DIR_ENV`, `global_agents_dir`). A
+cross-level move spans the real home directory and a project, so without the
+seam the global half of the feature can only be tested against the developer's
+own `~/.agents`, and an isolated or portable install cannot place its global
+capabilities anywhere but the user's home. It is a test and installation seam,
+not a user setting, and it is not exposed in Settings.
+
+## Consequences
+
+- A capability has exactly one home. The Settings row disappears from the source
+ group and appears in the destination group, which is the confirmation the move
+ happened; a same-level duplicate is impossible by construction.
+- A directory skill keeps working after the move because its resources travel
+ with the document; a renamed directory skill is written under its new id.
+- Collisions stay productive: both definitions survive under names the user can
+ tell apart, at the cost of the user having to recognize the `-2` name as the
+ one they just moved.
+- A moved global document drops its other projects' overrides. Those entries no
+ longer name any global document, so keeping them would be state for a
+ capability that does not exist; the projects simply fall back to no entry.
+- The move is host-owned and does not touch the renderer's level queries:
+ `mcp.list` / `mcp.active` / `skills.list` / `skills.active` report the result
+ after the scan, and the document itself never carries `enabled`.
+- Validation: transfer, rename, state, and directory-resource paths are covered
+ by host-core registry tests, and the move-menu destination rule has a
+ source-contract test in `apps/desktop/test/agent-capability-settings.test.mjs`.
+ The rendered journey is specified as E2E-CAPABILITY-move-across-levels and
+ remains Draft until a rendered E2E run is performed.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 9a2bb2a04..5b14e4e01 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -293,3 +293,4 @@ Each ADR includes:
| session-content-search | [Discover sessions by indexed message text](session-content-search.md) | Accepted |
| transcript-reading-ownership | [Share renderer history and search views](transcript-reading-ownership.md) | Accepted |
| 0266 | [Plugin fs roots follow the calling session](0266-plugin-fs-root-follows-the-calling-session.md) | Accepted (D093) |
+| 0267 | [Move capability documents between the global and project levels](0267-capability-level-transfer.md) | Accepted for implementation (amends ADR 0112) |
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 3944b7040..480e4f33f 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -613,14 +613,28 @@ one after the final row would be wrong.
### Agent capabilities (skills, subagents, MCP servers)
- `skills.list` / `skills.active` / `skills.read` / `skills.create` /
`skills.update` / `skills.remove` / `skills.import` /
- `skills.setEnabled` / `skills.setScope` — user skill documents
- (`SKILL_INVALID` on validation failure)
+ `skills.setEnabled` / `skills.setScope` / `skills.transfer` — user skill
+ documents (`SKILL_INVALID` on validation failure)
- `agents.list` / `agents.active` / `agents.read` / `agents.create` /
`agents.update` / `agents.remove` / `agents.setEnabled` /
`agents.setScope` — user subagent documents (`SUBAGENT_INVALID`)
- `mcp.list` / `mcp.active` / `mcp.upsert` / `mcp.remove` /
- `mcp.setEnabled` / `mcp.setScope` — user MCP server definitions
- (`MCP_INVALID`)
+ `mcp.setEnabled` / `mcp.setScope` / `mcp.transfer` — user MCP server
+ definitions (`MCP_INVALID`)
+
+`skills.transfer` and `mcp.transfer` take `{ id, from, to }`, each end a
+`{ level, projectPath? }` target (`projectPath` is required for the project
+level), and return `{ skill }` / `{ server }` for the document where it landed.
+A transfer moves the document between the two levels rather than copying it, so
+the source level stops listing the entry. A destination that already owns the
+same id gives the arriving document a `-2`/`-3` id suffix; one that owns the
+same display name / label, compared case-insensitively, gives it a matching
+` (2)`/` (3)` display suffix. The existing entry stays untouched. Enablement
+travels with the document: the source level drops every state entry for the old
+id, including its project overrides, and the destination stores the value the
+source was showing (a project target keeps that project's state, a global
+target the global default). Naming the source's own directory as the
+destination is a no-op.
`*.active` returns the entries that apply to the given project after
activation-scope filtering (`CAPABILITY_INVALID` for an unknown scope).
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index bee5e7a20..6c86b1d4e 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -373,10 +373,16 @@ system while preserving their different data ownership:
the overflow menu stay quiet until the row is hovered, focused, or has its
menu open; the switch is always visible because enablement is the state the
list is read for. Without hover the quiet actions are always shown. The
- overflow menu holds the level-aware destructive and out-of-app actions —
- Reveal and Remove for skills and subagents, Test connection and Remove for
- MCP — and Remove arms on first press, relabels to ask for confirmation, and
- disarms on its own if the menu is dismissed or left alone.
+ overflow menu holds the level-aware destructive, move, and out-of-app
+ actions — Reveal and Remove for skills and subagents, Test connection and
+ Remove for MCP, and Move to Global / Move into <project> on MCP and Skill
+ rows — and Remove arms on first press, relabels to ask for confirmation,
+ and disarms on its own if the menu is dismissed or left alone. The move
+ direction follows the row's own level: a global row offers Move into the
+ project named by the page toolbar's project picker, and a project row offers
+ Move to Global. With no project selected the Move into <project> item is not
+ offered and the project group asks for a project selection instead, so a
+ capability is never sent to an unnamed project.
- Skeleton rows appear on first paint only. A later refresh keeps the rows it
already has and dims the list instead, announcing the refresh to assistive
technology, so toggling a switch never replaces the list with skeletons.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 73bc3c825..e483e087d 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -6866,6 +6866,85 @@ identify the platform validation still needed.
full native-picker, rendered modal, project-switch, and runtime journey remain
Draft (run only in a capable environment when this surface changes)
+#### E2E-CAPABILITY-move-across-levels: MCP servers and skills move between the global and project `.agents` levels
+
+- **Preconditions**: The app runs against a disposable global `.agents` root
+ (an isolated HOME, or `PI_DESKTOP_AGENTS_DIR` when the bare host is driven
+ directly). Projects A and B are registered. The global root owns
+ `~/.agents/servers/echo.json` (id `echo`, label `Echo`),
+ `~/.agents/skills/review.md` (frontmatter name `Review`), and nothing else
+ that uses the names used below. Project A owns no `echo` server and no
+ `review` skill, and owns `<project A>/.agents/skills/with-resources/` holding
+ `SKILL.md` plus `scripts/run.sh` and `templates/report.md`. The MCP and
+ Skills pages show the project picker described in the Settings IA spec.
+- **Steps**:
+ 1. Open Settings > Agent > MCP with project A selected. Disable the global
+ `echo` row, then choose Move into A. Confirm the row leaves the global
+ group, appears under project A, and stays disabled there.
+ 2. Confirm `~/.agents/servers/echo.json` no longer exists and
+ `<project A>/.agents/servers/echo.json` does, byte-identical. Read
+ `<data>/agent-capabilities/mcp.json` and confirm it holds no global `echo`
+ entry and no project-A override for the old id, and that project A's entry
+ carries the disabled value.
+ 3. Create a new global `echo` server again (id `echo`, label `Echo`). With
+ project A selected choose Move into A and confirm the arriving row is
+ `echo-2` with label `Echo (2)`, that project A's original `echo.json` is
+ byte-identical to before the move, and that both project rows list.
+ 4. Open Skills with project A selected. Create a project `review.md` whose
+ frontmatter carries `name: Review`, a description, and an extra custom
+ field, plus a body; disable it, then choose Move to Global. Confirm it
+ appears globally as `review-2`, arrives disabled, and leaves the global
+ `review.md` unchanged.
+ 5. Diff the moved document against the project original: only the frontmatter
+ `name` line differs (`name: Review (2)`); the description, the custom
+ field, blank lines, line endings, and every body byte are identical.
+ 6. Move project A's `with-resources` skill to Global. Confirm
+ `<project A>/.agents/skills/with-resources/` is gone and
+ `~/.agents/skills/with-resources/` holds `SKILL.md`, `scripts/run.sh`, and
+ `templates/report.md` with identical bytes, and that the Skill tool still
+ resolves the document's resources.
+ 7. Reload the global and project pages. Confirm the moved rows keep the
+ enablement they had across the reload, that project B lists none of the
+ project-A capabilities, and that the moved global `review-2` applies to
+ project B with the value it had after the move.
+ 8. Clear the project selection in the toolbar. Confirm Move into <project> is
+ no longer offered on the remaining global rows and the project group asks
+ for a project selection instead; re-select project B and confirm the
+ action returns.
+ 9. Drive `mcp.transfer` and `skills.transfer` with `from` and `to` naming the
+ same directory and confirm the response returns the current record and
+ neither directory changes.
+- **Expected**:
+ - A move relocates the document: the destination directory gains the file,
+ the source level stops listing the entry, and no copy is left behind.
+ - Enablement follows the document. A global row disabled for project A
+ arrives in project A disabled; a project row arrives globally with its
+ visible value as the new global default. The source level keeps no state
+ entry — including project overrides — for the old id.
+ - A destination collision is resolved by renaming only the colliding name:
+ an id collision gives the arriving id a `-2`/`-3` suffix, a case-insensitive
+ display-name / label collision gives the display name a ` (2)`/` (3)`
+ suffix, and the existing entry is never overwritten or merged. Renaming a
+ skill rewrites only the frontmatter `name` line and preserves every other
+ byte.
+ - A directory-shaped skill moves as one unit with its sibling resources, and
+ a transfer whose two targets name the same directory is a no-op.
+ - Without a selected project the move action is unavailable with an explicit
+ explanation, and no capability file or state entry changes.
+- **Specs linked**: `03-runtime/06-host-rpc-protocol.md` §4 (Agent
+ capabilities), `03-runtime/01-ipc-protocol.md` §12a–§12b,
+ `04-ux/06-settings-ia.md` §2 (Agent capability destinations), ADR 0112,
+ ADR 0267
+- **Acceptance**: E (tools & permissions), F (persistence), Quality
+- **Milestone**: M6+
+- **Status**: Host-covered (`pnpm test:e2e:capability-move` drives the same RPC
+ surface Electron main calls against a real host-core and an isolated global
+ root, asserting the documents and the state file on disk; host-core
+ registry/state tests cover the rename, the id the scan derives, and directory
+ resources; the source contract is pinned by
+ `apps/desktop/test/agent-capability-settings.test.mjs`). The rendered Settings
+ journey — row menu, toggle, toast — remains Draft.
+
#### E2E-120: Global plugin launch, next-turn editing, and stopped throughput
- **Preconditions**: Install and enable a panel plugin whose Chinese display
@@ -7692,6 +7771,9 @@ identify the platform validation still needed.
| Security (plugin real-time capabilities) | E2E-PLUGIN-global-shortcut-owns-only-its-own-command, E2E-PLUGIN-permission-gate-for-real-time-capabilities, E2E-PLUGIN-background-audio-and-realtime-connection |
| C — Conversation & stream (disclosure reading position) | E2E-CHAT-disclosure-toggle-keeps-reading-position |
| E — Tools & permissions (disclosure reading position) | E2E-CHAT-disclosure-toggle-keeps-reading-position |
+| E — Tools & permissions (capability level move) | E2E-CAPABILITY-move-across-levels |
+| F — Persistence (capability level move) | E2E-CAPABILITY-move-across-levels |
+| Quality (capability level move) | E2E-CAPABILITY-move-across-levels |
| Milestone | Scenarios |
|---|---|
@@ -7721,6 +7803,7 @@ identify the platform validation still needed.
| C — Conversation & stream (legacy subagent turn limit) | E2E-SUBAGENT-legacy-turn-limit-frontmatter-is-ignored |
| Quality (legacy subagent turn limit) | E2E-SUBAGENT-legacy-turn-limit-frontmatter-is-ignored |
| M6+ (disclosure reading position) | E2E-CHAT-disclosure-toggle-keeps-reading-position |
+| M6+ (capability level move) | E2E-CAPABILITY-move-across-levels |
The `US-UI-*` visual scenarios (§UI shell visual scenarios) trace to the
Codex parity decisions in [decisions-log §D](../08-meta/decisions-log.md)
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 18d471636..d2a580372 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -4935,6 +4935,9 @@ IPC 请求无法关闭。
| Security (plugin real-time capabilities) | E2E-PLUGIN-global-shortcut-owns-only-its-own-command、E2E-PLUGIN-permission-gate-for-real-time-capabilities、E2E-PLUGIN-background-audio-and-realtime-connection |
| C — 对话与流式(展开详情保持阅读位置) | E2E-CHAT-disclosure-toggle-keeps-reading-position |
| E — 工具与权限(展开详情保持阅读位置) | E2E-CHAT-disclosure-toggle-keeps-reading-position |
+| E — 工具与权限(能力跨级别迁移) | E2E-CAPABILITY-move-across-levels |
+| F — 持久化(能力跨级别迁移) | E2E-CAPABILITY-move-across-levels |
+| 品质(能力跨级别迁移) | E2E-CAPABILITY-move-across-levels |
| 里程碑 | 应用场景 |
|---|---|
@@ -4964,6 +4967,7 @@ IPC 请求无法关闭。
| C — 对话和直播(旧版子代理回合上限) | E2E-SUBAGENT-legacy-turn-limit-frontmatter-is-ignored |
| 品质(旧版子代理回合上限) | E2E-SUBAGENT-legacy-turn-limit-frontmatter-is-ignored |
| M6+(展开详情保持阅读位置) | E2E-CHAT-disclosure-toggle-keeps-reading-position |
+| M6+(能力跨级别迁移) | E2E-CAPABILITY-move-across-levels |
`US-UI-*` 视觉场景(§UI shell 视觉场景)追踪到
[决策日志 §D](/zh-CN/spec/08-meta/decisions-log) 中的法典平价决策
diff --git a/package.json b/package.json
index 8cd5c18ee..b49a447a4 100644
--- a/package.json
+++ b/package.json
@@ -48,6 +48,7 @@
"lint:biome": "biome lint",
"test:e2e:mcp-market": "node scripts/e2e-mcp-market.mjs",
"test:e2e:skill-market": "node scripts/e2e-skill-market.mjs",
+ "test:e2e:capability-move": "node scripts/e2e-capability-move.mjs",
"test:e2e:plugin-import-deps": "node scripts/e2e-plugin-import-deps.mjs",
"test:e2e:trusted-extensions": "node scripts/e2e-trusted-extensions.mjs",
"test:e2e:collaboration": "node scripts/e2e-session-collaboration.mjs"
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 37b0880e1..0e414d836 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -854,6 +854,10 @@ sklm: {
"capabilityCreateInProject": "In Projekt erstellen",
"capabilityImportToGlobal": "In global importieren",
"capabilityImportToProject": "In Projekt importieren",
+ "capabilityMoveToGlobal": "Nach global verschieben",
+ "capabilityMoveToProject": "In {{project}} verschieben",
+ "capabilityMoved": "{{name}} nach {{target}} verschoben",
+ "capabilityMovedRenamed": "{{name}} nach {{target}} verschoben, umbenannt in {{newName}}",
"skillCreated": "Erstellt {{name}}",
"skillSaved": "Gespeichert {{name}}",
"subagentCreated": "Erstellt {{name}}",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 8969cc355..a1817c2b6 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -862,6 +862,10 @@ sklm: {
capabilityCreateInProject: "Create in project",
capabilityImportToGlobal: "Import into global",
capabilityImportToProject: "Import into project",
+ capabilityMoveToGlobal: "Move to Global",
+ capabilityMoveToProject: "Move into {{project}}",
+ capabilityMoved: "Moved {{name}} to {{target}}",
+ capabilityMovedRenamed: "Moved {{name}} to {{target}} as {{newName}}",
skillCreated: "Created {{name}}",
skillSaved: "Saved {{name}}",
subagentCreated: "Created {{name}}",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index d6ca67969..adad3fe06 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -854,6 +854,10 @@ sklm: {
"capabilityCreateInProject": "Crear en proyecto",
"capabilityImportToGlobal": "Importar en global",
"capabilityImportToProject": "Importar en proyecto",
+ "capabilityMoveToGlobal": "Mover a global",
+ "capabilityMoveToProject": "Mover a {{project}}",
+ "capabilityMoved": "Movido {{name}} a {{target}}",
+ "capabilityMovedRenamed": "Movido {{name}} a {{target}} como {{newName}}",
"skillCreated": "Creado {{name}}",
"skillSaved": "Guardado {{name}}",
"subagentCreated": "Creado {{name}}",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index aef3cff6f..afa197b4e 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -854,6 +854,10 @@ sklm: {
"capabilityCreateInProject": "Créer dans le projet",
"capabilityImportToGlobal": "Importer dans le global",
"capabilityImportToProject": "Importer dans le projet",
+ "capabilityMoveToGlobal": "Déplacer vers le global",
+ "capabilityMoveToProject": "Déplacer dans {{project}}",
+ "capabilityMoved": "{{name}} déplacé vers {{target}}",
+ "capabilityMovedRenamed": "{{name}} déplacé vers {{target}} et renommé en {{newName}}",
"skillCreated": "Créé {{name}}",
"skillSaved": "Enregistré {{name}}",
"subagentCreated": "Créé {{name}}",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 9cd491dc0..10590bbed 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -863,6 +863,10 @@ sklm: {
capabilityCreateInProject: "프로젝트에 만들기",
capabilityImportToGlobal: "전역으로 가져오기",
capabilityImportToProject: "프로젝트로 가져오기",
+ capabilityMoveToGlobal: "전역으로 이동",
+ capabilityMoveToProject: "{{project}}(으)로 이동",
+ capabilityMoved: "{{name}}을(를) {{target}}(으)로 이동함",
+ capabilityMovedRenamed: "{{name}}을(를) {{target}}(으)로 이동하고 {{newName}}(으)로 이름 변경함",
skillCreated: "{{name}} 생성됨",
skillSaved: "{{name}} 저장됨",
subagentCreated: "{{name}} 생성됨",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 08c1e5803..0bf17bf1a 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -863,6 +863,10 @@ sklm: {
capabilityCreateInProject: "Projede oluştur",
capabilityImportToGlobal: "Genele içe aktar",
capabilityImportToProject: "Projeye içe aktar",
+ capabilityMoveToGlobal: "Genele taşı",
+ capabilityMoveToProject: "{{project}} projesine taşı",
+ capabilityMoved: "{{name}}, {{target}} konumuna taşındı",
+ capabilityMovedRenamed: "{{name}}, {{target}} konumuna {{newName}} olarak taşındı",
skillCreated: "{{name}} oluşturuldu",
skillSaved: "{{name}} kaydedildi",
subagentCreated: "{{name}} oluşturuldu",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 0ec901bbb..6af5e8407 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -857,6 +857,10 @@ sklm: {
capabilityCreateInProject: "新建到项目级",
capabilityImportToGlobal: "导入到全局级",
capabilityImportToProject: "导入到项目级",
+ capabilityMoveToGlobal: "迁移到全局级",
+ capabilityMoveToProject: "迁移到项目“{{project}}”",
+ capabilityMoved: "已将 {{name}} 迁移到 {{target}}",
+ capabilityMovedRenamed: "已将 {{name}} 迁移到 {{target}},并重命名为“{{newName}}”",
skillCreated: "已新建 {{name}}",
skillSaved: "已保存 {{name}}",
subagentCreated: "已新建 {{name}}",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index cb4fa1c17..0cfdd5797 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -857,6 +857,10 @@ sklm: {
capabilityCreateInProject: "新建到專案級",
capabilityImportToGlobal: "匯入到全域性級",
capabilityImportToProject: "匯入到專案級",
+ capabilityMoveToGlobal: "移動到全域性級",
+ capabilityMoveToProject: "移動到專案“{{project}}”",
+ capabilityMoved: "已將 {{name}} 移動到 {{target}}",
+ capabilityMovedRenamed: "已將 {{name}} 移動到 {{target}},並重新命名為“{{newName}}”",
skillCreated: "已新建 {{name}}",
skillSaved: "已儲存 {{name}}",
subagentCreated: "已新建 {{name}}",
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index dc193aabf..5867ba1bd 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -196,6 +196,7 @@ export const IPC = {
mcpRemove: "pi-desktop/mcp/remove",
mcpSetEnabled: "pi-desktop/mcp/setEnabled",
mcpSetScope: "pi-desktop/mcp/setScope",
+ mcpTransfer: "pi-desktop/mcp/transfer",
mcpTest: "pi-desktop/mcp/test",
mcpImport: "pi-desktop/mcp/import",
mcpMarketSearch: "pi-desktop/mcp/market/search",
@@ -208,6 +209,7 @@ export const IPC = {
skillRemove: "pi-desktop/skill/remove",
skillSetEnabled: "pi-desktop/skill/setEnabled",
skillSetScope: "pi-desktop/skill/setScope",
+ skillTransfer: "pi-desktop/skill/transfer",
skillRead: "pi-desktop/skill/read",
skillReveal: "pi-desktop/skill/reveal",
subagentList: "pi-desktop/subagent/list",
diff --git a/packages/shared/src/types/capabilities.ts b/packages/shared/src/types/capabilities.ts
index 5818f57ec..b938a1333 100644
--- a/packages/shared/src/types/capabilities.ts
+++ b/packages/shared/src/types/capabilities.ts
@@ -11,6 +11,27 @@ export type AgentCapabilityQuery = {
projectPath?: string;
};
+/** One end of a level move: the level plus, for `project`, the owning root. */
+export type AgentCapabilityTarget = {
+ level: AgentCapabilityLevel;
+ projectPath?: string;
+};
+
+/**
+ * A move of one capability document between the global `.agents` directory and
+ * a project's.
+ *
+ * Both ends travel together because the host resolves each one against its own
+ * directory: a global source may still name a project, which is the context its
+ * enabled state is read in, and that must never be mistaken for the destination.
+ * The document is moved rather than copied, so the source level stops listing it.
+ */
+export type AgentCapabilityMove = {
+ id: string;
+ from: AgentCapabilityTarget;
+ to: AgentCapabilityTarget;
+};
+
/** Transport of an MCP server the user configured themselves. */
export type McpTransport = "stdio" | "http";
diff --git a/scripts/e2e-capability-move.mjs b/scripts/e2e-capability-move.mjs
new file mode 100644
index 000000000..4888221a5
--- /dev/null
+++ b/scripts/e2e-capability-move.mjs
@@ -0,0 +1,384 @@
+#!/usr/bin/env node
+/**
+ * Capability level-move E2E (headless protocol-level).
+ * Covers moving one MCP server or skill between the global `.agents` directory
+ * and a project's, over the same RPC surface Electron main drives:
+ *
+ * E2E-CAPABILITY-move-across-levels
+ * the document leaves the source directory and arrives in the destination
+ * one, the enabled value follows it, the source keeps no orphaned state, a
+ * destination collision renames the arrival instead of overwriting or
+ * blocking, a skill's id is read back from the scan (it can come from the
+ * frontmatter name rather than the file name), a directory-shaped skill
+ * carries its resources, and the request guards reject an absent level or an
+ * absent project path.
+ *
+ * The GUI half of the documented scenario — the Settings row menu, the toast —
+ * stays manual; this script is the half a headless run can prove.
+ *
+ * Env: PI_DESKTOP_HOST_BIN (optional), DEBUG_HOST for tracing.
+ * Deterministic: no live network access.
+ */
+import { spawn } from "node:child_process";
+import { createInterface } from "node:readline";
+import { randomUUID } from "node:crypto";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { PROTOCOL_VERSION } from "../packages/shared/dist/protocol.js";
+
+const SCENARIO = "E2E-CAPABILITY-move-across-levels";
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const root = join(__dirname, "..");
+const hostBinCandidates = [];
+const configuredHostBin = process.env.PI_DESKTOP_HOST_BIN?.trim();
+if (configuredHostBin) {
+ const configured = resolve(configuredHostBin);
+ hostBinCandidates.push(configured);
+ if (process.platform === "win32" && !configured.toLowerCase().endsWith(".exe")) {
+ hostBinCandidates.push(`${configured}.exe`);
+ }
+}
+const hostBinaryName = `pi-desktop-host-core${process.platform === "win32" ? ".exe" : ""}`;
+hostBinCandidates.push(join(root, "target", "debug", hostBinaryName));
+hostBinCandidates.push(join(root, "..", "..", "..", "target", "debug", hostBinaryName));
+const hostBin = hostBinCandidates.find((candidate) => existsSync(candidate));
+
+if (!hostBin) {
+ console.error("host binary missing; tried:", hostBinCandidates.join(", "));
+ process.exit(1);
+}
+
+const results = [];
+function record(label, ok, detail = "") {
+ results.push({ label, ok, detail });
+ console.log(`${ok ? "PASS" : "FAIL"} ${SCENARIO} · ${label}${detail ? " — " + detail : ""}`);
+}
+
+class Host {
+ constructor(bin, dataDir, home) {
+ this.child = spawn(bin, [], {
+ stdio: ["pipe", "pipe", "pipe"],
+ env: {
+ ...process.env,
+ HOME: home,
+ PI_DESKTOP_DATA_DIR: dataDir,
+ // Narrower than HOME: only the global capability root reads it, so the
+ // fixture cannot leak into anything else the host resolves from home.
+ PI_DESKTOP_AGENTS_DIR: join(home, ".agents"),
+ },
+ });
+ this.pending = new Map();
+ this.child.stderr.on("data", () => {});
+ const rl = createInterface({ input: this.child.stdout });
+ rl.on("line", (line) => {
+ let msg;
+ try {
+ msg = JSON.parse(line);
+ } catch {
+ return;
+ }
+ if (msg.id != null && this.pending.has(String(msg.id))) {
+ const pending = this.pending.get(String(msg.id));
+ this.pending.delete(String(msg.id));
+ if (msg.error) pending.reject(new Error(`${msg.error.code} ${msg.error.message}`));
+ else pending.resolve(msg.result);
+ }
+ });
+ this.child.on("exit", (code) => {
+ for (const pending of this.pending.values()) {
+ pending.reject(new Error(`host exited code=${code}`));
+ }
+ this.pending.clear();
+ });
+ }
+ call(method, params = {}) {
+ const id = randomUUID();
+ return new Promise((resolve, reject) => {
+ this.pending.set(String(id), { resolve, reject });
+ this.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
+ setTimeout(() => {
+ if (this.pending.has(String(id))) {
+ this.pending.delete(String(id));
+ reject(new Error(`timeout ${method}`));
+ }
+ }, 30_000);
+ });
+ }
+ dispose() {
+ this.child.kill("SIGTERM");
+ }
+}
+
+const home = mkdtempSync(join(tmpdir(), "pi-capability-move-home-"));
+const dataDir = mkdtempSync(join(tmpdir(), "pi-capability-move-data-"));
+const projectA = mkdtempSync(join(tmpdir(), "pi-capability-move-a-"));
+const projectB = mkdtempSync(join(tmpdir(), "pi-capability-move-b-"));
+mkdirSync(join(home, ".agents"), { recursive: true });
+
+const serverPath = (levelRoot, id) => join(levelRoot, ".agents", "servers", `${id}.json`);
+const skillsDir = (levelRoot) => join(levelRoot, ".agents", "skills");
+
+let host;
+try {
+ host = new Host(hostBin, dataDir, home);
+ const handshake = await host.call("app.handshake", {
+ protocolVersion: PROTOCOL_VERSION,
+ client: "electron-main",
+ clientVersion: "e2e",
+ locale: "en",
+ });
+ if (handshake.protocolVersion !== PROTOCOL_VERSION) {
+ throw new Error(`handshake mismatch: ${JSON.stringify(handshake)}`);
+ }
+
+ // ── MCP: global → project, with the per-project disabled value travelling ──
+ await host.call("mcp.upsert", {
+ server: {
+ id: "echo",
+ label: "Echo",
+ transport: "stdio",
+ command: "npx",
+ args: ["-y", "echo-mcp"],
+ },
+ });
+ await host.call("mcp.setEnabled", {
+ id: "echo",
+ enabled: false,
+ level: "global",
+ projectPath: projectA,
+ });
+ const globalBefore = await host.call("mcp.list", { level: "global", projectPath: projectA });
+ record(
+ "mcp-override-is-per-project",
+ globalBefore.servers.length === 1 &&
+ globalBefore.servers[0].level === "global" &&
+ globalBefore.servers[0].enabled === false,
+ JSON.stringify(globalBefore.servers),
+ );
+
+ const movedServer = await host.call("mcp.transfer", {
+ id: "echo",
+ from: { level: "global", projectPath: projectA },
+ to: { level: "project", projectPath: projectA },
+ });
+ record(
+ "mcp-move-reports-its-own-owner-and-state",
+ movedServer.server?.level === "project" &&
+ movedServer.server?.projectPath === projectA &&
+ movedServer.server?.id === "echo" &&
+ movedServer.server?.enabled === false,
+ JSON.stringify(movedServer.server),
+ );
+ record(
+ "mcp-document-left-one-level-and-arrived-in-the-other",
+ !existsSync(serverPath(home, "echo")) && existsSync(serverPath(projectA, "echo")),
+ `global=${existsSync(serverPath(home, "echo"))} project=${existsSync(serverPath(projectA, "echo"))}`,
+ );
+ const [globalAfter, projectAfter] = await Promise.all([
+ host.call("mcp.list", { level: "global" }),
+ host.call("mcp.list", { level: "project", projectPath: projectA }),
+ ]);
+ record(
+ "mcp-source-level-stops-listing-it",
+ globalAfter.servers.length === 0 && projectAfter.servers.length === 1,
+ `global=${globalAfter.servers.length} project=${projectAfter.servers.length}`,
+ );
+ const state = JSON.parse(readFileSync(join(dataDir, "agent-capabilities", "mcp.json"), "utf8"));
+ const globalKeys = Object.keys(state.values ?? {}).filter((key) =>
+ key.includes('"level":"global"'),
+ );
+ record(
+ "mcp-move-leaves-no-orphaned-source-state",
+ globalKeys.length === 0,
+ globalKeys.join(", ") || "no global entries",
+ );
+
+ // ── MCP: a case-differing id is a collision, not an overwrite ─────────────
+ // macOS and Windows return one file for `MyServer.json` and `myserver.json`.
+ await host.call("mcp.upsert", {
+ server: {
+ id: "MyServer",
+ label: "Shared",
+ transport: "stdio",
+ command: "npx",
+ level: "project",
+ projectPath: projectB,
+ },
+ });
+ await host.call("mcp.upsert", {
+ server: { id: "myserver", label: "Shared", transport: "stdio", command: "npx" },
+ });
+ const renamed = await host.call("mcp.transfer", {
+ id: "myserver",
+ from: { level: "global" },
+ to: { level: "project", projectPath: projectB },
+ });
+ const survivor = JSON.parse(readFileSync(serverPath(projectB, "MyServer"), "utf8"));
+ record(
+ "mcp-case-differing-id-renames-instead-of-overwriting",
+ renamed.server?.id === "myserver-2" &&
+ renamed.server?.label === "Shared (2)" &&
+ survivor.id === "MyServer" &&
+ survivor.label === "Shared",
+ JSON.stringify({ arrived: renamed.server?.id, survivor: survivor.id }),
+ );
+
+ // ── Skill: the scan, not the file name, decides the id ────────────────────
+ // A Chinese name slugs to nothing, so the id falls back to the path stem, and
+ // a same-named document at the other level collides with it. Planning the move
+ // against the file stem alone would delete the source and then fail to find
+ // the arrival, and a colliding id would let the scan hide one of the two.
+ mkdirSync(join(skillsDir(home), "code-review"), { recursive: true });
+ writeFileSync(
+ join(skillsDir(home), "code-review", "SKILL.md"),
+ "---\nname: 代码审查\n---\n\nGlobal copy.\n",
+ );
+ writeFileSync(join(skillsDir(home), "code-review", "scripts.sh"), "#!/bin/sh\necho hi\n");
+ mkdirSync(join(skillsDir(projectA), "code-review"), { recursive: true });
+ writeFileSync(
+ join(skillsDir(projectA), "code-review", "SKILL.md"),
+ "---\nname: 代码审查\n---\n\nProject copy.\n",
+ );
+ const globalSkills = await host.call("skills.list", { level: "global" });
+ record(
+ "skill-without-an-ascii-name-is-catalogued-under-its-path-stem",
+ globalSkills.skills.length === 1 &&
+ globalSkills.skills[0].id === "code-review" &&
+ globalSkills.skills[0].name === "代码审查",
+ JSON.stringify(globalSkills.skills),
+ );
+
+ const movedSkill = await host.call("skills.transfer", {
+ id: "code-review",
+ from: { level: "global" },
+ to: { level: "project", projectPath: projectA },
+ });
+ record(
+ "skill-move-succeeds-instead-of-erroring-after-deleting-the-source",
+ movedSkill.skill?.level === "project" && movedSkill.skill?.projectPath === projectA,
+ JSON.stringify(movedSkill.skill),
+ );
+ const bothSkills = await host.call("skills.list", { level: "project", projectPath: projectA });
+ const ids = new Set(bothSkills.skills.map((row) => row.id.toLowerCase()));
+ const names = new Set(bothSkills.skills.map((row) => row.name.toLowerCase()));
+ record(
+ "both-skills-stay-visible-under-distinct-ids-and-names",
+ bothSkills.skills.length === 2 && ids.size === 2 && names.size === 2,
+ JSON.stringify(bothSkills.skills.map((row) => `${row.id}:${row.name}`)),
+ );
+ const travelled = readdirSync(skillsDir(projectA)).filter((name) =>
+ existsSync(join(skillsDir(projectA), name, "scripts.sh")),
+ );
+ record(
+ "directory-skill-carries-its-resources",
+ !existsSync(join(skillsDir(home), "code-review", "SKILL.md")) && travelled.length === 1,
+ travelled.join(",") || "no resource file arrived",
+ );
+
+ // ── Skill: a rename rewrites one line and nothing else ────────────────────
+ writeFileSync(
+ join(skillsDir(home), "review.md"),
+ "---\nname: Review\nlicense: MIT\n---\n\n## Step 1\n\n indented\n",
+ );
+ await host.call("skills.create", {
+ skill: { name: "Review", level: "project", projectPath: projectA, body: "Project copy.\n" },
+ });
+ const renamedSkill = await host.call("skills.transfer", {
+ id: "review",
+ from: { level: "global" },
+ to: { level: "project", projectPath: projectA },
+ });
+ record(
+ "skill-same-name-arrives-under-a-distinct-name",
+ renamedSkill.skill?.name === "Review (2)" && renamedSkill.skill?.id !== "review",
+ JSON.stringify({ id: renamedSkill.skill?.id, name: renamedSkill.skill?.name }),
+ );
+ record(
+ "skill-rename-rewrites-only-the-name-line",
+ readFileSync(renamedSkill.skill.path, "utf8") ===
+ "---\nname: Review (2)\nlicense: MIT\n---\n\n## Step 1\n\n indented\n",
+ JSON.stringify(readFileSync(renamedSkill.skill.path, "utf8")),
+ );
+
+ const back = await host.call("skills.transfer", {
+ id: renamedSkill.skill.id,
+ from: { level: "project", projectPath: projectA },
+ to: { level: "global" },
+ });
+ record(
+ "skill-can-move-back-to-the-global-level",
+ back.skill?.level === "global" &&
+ back.skill?.name === "Review (2)" &&
+ existsSync(join(skillsDir(home), `${back.skill.id}.md`)),
+ JSON.stringify({ level: back.skill?.level, id: back.skill?.id }),
+ );
+
+ // ── Request guards ───────────────────────────────────────────────────────
+ const rejects = async (label, params, pattern) => {
+ try {
+ await host.call("mcp.transfer", params);
+ record(label, false, "call unexpectedly succeeded");
+ } catch (error) {
+ record(label, pattern.test(error.message), error.message);
+ }
+ };
+ await rejects(
+ "target-without-an-explicit-level-is-rejected",
+ { id: "echo", from: { level: "project", projectPath: projectA }, to: { projectPath: projectB } },
+ /INVALID_PARAMS|level/,
+ );
+ await rejects(
+ "project-target-without-a-project-path-is-rejected",
+ { id: "echo", from: { level: "project", projectPath: projectA }, to: { level: "project" } },
+ /CAPABILITY_INVALID|projectPath/,
+ );
+
+ const sameMove = await host.call("mcp.transfer", {
+ id: "echo",
+ from: { level: "project", projectPath: projectA },
+ to: { level: "project", projectPath: projectA },
+ });
+ record(
+ "moving-to-the-same-directory-is-a-no-op",
+ sameMove.server?.id === "echo" && existsSync(serverPath(projectA, "echo")),
+ JSON.stringify(sameMove.server?.id),
+ );
+
+ const finalProject = await host.call("skills.list", { level: "project", projectPath: projectA });
+ const finalGlobal = await host.call("skills.list", { level: "global" });
+ const unique = (rows, pick) => {
+ const values = rows.map((row) => String(pick(row)).toLowerCase());
+ return new Set(values).size === values.length;
+ };
+ record(
+ "no-level-holds-two-capabilities-under-one-id-or-name",
+ unique(finalProject.skills, (row) => row.id) &&
+ unique(finalProject.skills, (row) => row.name) &&
+ unique(finalGlobal.skills, (row) => row.id) &&
+ unique(finalGlobal.skills, (row) => row.name) &&
+ unique(projectAfter.servers, (row) => row.id) &&
+ unique(projectAfter.servers, (row) => row.label),
+ JSON.stringify(finalProject.skills.map((row) => `${row.id}:${row.name}`)),
+ );
+} catch (error) {
+ record("scenario-completed", false, error.stack ?? error.message);
+} finally {
+ host?.dispose();
+ for (const dir of [home, dataDir, projectA, projectB]) {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+const failed = results.filter((result) => !result.ok);
+console.log(`\nSummary: ${results.length - failed.length}/${results.length} passed`);
+process.exit(failed.length ? 1 : 0);