import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { join } from "node:path"; // --------------------------------------------------------------------------- // Mock node:fs // --------------------------------------------------------------------------- const mockExistsSync = vi.fn(); const mockRmSync = vi.fn(); const mockLstatSync = vi.fn((): never => { throw Object.assign(new Error("ENOENT"), { code: "ENOENT" }); }); vi.mock("node:fs", () => ({ existsSync: (...args: unknown[]) => mockExistsSync(...args), rmSync: (...args: unknown[]) => mockRmSync(...args), lstatSync: (...args: unknown[]) => (mockLstatSync as (...a: unknown[]) => unknown)(...args), readFileSync: vi.fn(), writeFileSync: vi.fn(), })); // --------------------------------------------------------------------------- // Mock agents registry // --------------------------------------------------------------------------- const mockDetectInstalledAgents = vi.fn(); vi.mock("../agents/agents-registry.js", () => ({ detectInstalledAgents: (...args: unknown[]) => mockDetectInstalledAgents(...args), })); // --------------------------------------------------------------------------- // Mock lockfile // --------------------------------------------------------------------------- const mockReadLockfile = vi.fn(); const mockRemoveSkillFromLock = vi.fn(); const mockProjectRoot = vi.fn(); vi.mock("../lockfile/project-root.js", () => ({ getProjectRoot: () => mockProjectRoot(), })); vi.mock("../lockfile/index.js", () => ({ readLockfile: (...args: unknown[]) => mockReadLockfile(...args), removeSkillFromLock: (...args: unknown[]) => mockRemoveSkillFromLock(...args), })); // --------------------------------------------------------------------------- // Mock paths // --------------------------------------------------------------------------- vi.mock("../utils/paths.js", () => ({ resolveTilde: (p: string) => p.startsWith("~/") ? `/home/testuser${p.slice(1)}` : p, })); // --------------------------------------------------------------------------- // Mock settings / claude-plugin (F-002 multi-scope path) // --------------------------------------------------------------------------- const mockIsPluginEnabled = vi.fn(); const mockClaudePluginUninstall = vi.fn(); vi.mock("../settings/index.js", () => ({ isPluginEnabled: (...args: unknown[]) => mockIsPluginEnabled(...args), })); vi.mock("../utils/claude-plugin.js", () => ({ claudePluginUninstall: (...args: unknown[]) => mockClaudePluginUninstall(...args), })); // Import after mocks const { removeCommand } = await import("./remove.js"); // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- const MOCK_AGENTS = [ { id: "claude-code", displayName: "Claude Code", localSkillsDir: ".claude/commands", globalSkillsDir: "~/.claude/commands", }, { id: "cursor", displayName: "Cursor", localSkillsDir: ".cursor/skills", globalSkillsDir: "~/.cursor/skills", }, ]; function makeLockfile(skills: Record = {}) { return { version: 1, agents: ["claude-code", "cursor"], skills, createdAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", }; } // --------------------------------------------------------------------------- // Tests // --------------------------------------------------------------------------- beforeEach(() => { vi.clearAllMocks(); mockProjectRoot.mockReturnValue(process.cwd()); mockDetectInstalledAgents.mockResolvedValue(MOCK_AGENTS); // Default: no plugin registered anywhere — auto-discovered fixtures // short-circuit the F-002 multi-scope path. Marketplace tests override. mockIsPluginEnabled.mockReturnValue(false); }); describe("removeCommand", () => { it("0877: --global preserves the project lock and project plugin registration", async () => { const entry = { marketplace: "specweave", scope: "user" }; mockReadLockfile.mockReturnValue(makeLockfile({ sw: entry })); mockExistsSync.mockReturnValue(false); mockIsPluginEnabled.mockReturnValue(true); await removeCommand("sw", { force: true, global: true }); expect(mockRemoveSkillFromLock).not.toHaveBeenCalledWith("sw", process.cwd()); expect(mockRemoveSkillFromLock).toHaveBeenCalledWith("sw", "/home/testuser/.agents"); expect(mockClaudePluginUninstall).toHaveBeenCalledTimes(1); expect(mockClaudePluginUninstall).toHaveBeenCalledWith("sw@specweave", "user", undefined); }); it("0877: --local preserves global locks and global plugin registration", async () => { mockReadLockfile.mockReturnValue(makeLockfile({ sw: { marketplace: "specweave" } })); mockExistsSync.mockReturnValue(false); mockIsPluginEnabled.mockReturnValue(true); await removeCommand("sw", { force: true, local: true }); expect(mockRemoveSkillFromLock).toHaveBeenCalledWith("sw", process.cwd()); expect(mockRemoveSkillFromLock).not.toHaveBeenCalledWith("sw", "/home/testuser/.agents"); expect(mockClaudePluginUninstall).toHaveBeenCalledTimes(1); expect(mockClaudePluginUninstall).toHaveBeenCalledWith("sw@specweave", "project", { cwd: process.cwd() }); }); it("0877: global removal resolves plugin provenance from the global lock", async () => { mockReadLockfile.mockImplementation((dir?: string) => makeLockfile({ sw: { marketplace: dir === "/home/testuser/.agents" ? "global-market" : "project-market" }, })); mockExistsSync.mockReturnValue(false); mockIsPluginEnabled.mockReturnValue(true); await removeCommand("sw", { force: true, global: true }); expect(mockClaudePluginUninstall).toHaveBeenCalledWith("sw@global-market", "user", undefined); expect(mockClaudePluginUninstall).not.toHaveBeenCalledWith("sw@project-market", expect.anything(), expect.anything()); }); it("0877: removes global marketplace plugin even when project skill is auto-discovered", async () => { mockReadLockfile.mockImplementation((dir?: string) => makeLockfile({ sw: dir === "/home/testuser/.agents" ? { marketplace: "global-market" } : { source: "local:skill" }, })); mockExistsSync.mockReturnValue(false); mockIsPluginEnabled.mockReturnValue(true); await removeCommand("sw", { force: true }); expect(mockClaudePluginUninstall).toHaveBeenCalledTimes(1); expect(mockClaudePluginUninstall).toHaveBeenCalledWith("sw@global-market", "user", undefined); }); it("0877: nested invocation removes files and plugin registration at the lockfile project root", async () => { mockProjectRoot.mockReturnValue("/workspace/project"); mockReadLockfile.mockReturnValue(makeLockfile({ sw: { marketplace: "team" } })); mockExistsSync.mockReturnValue(true); mockIsPluginEnabled.mockReturnValue(true); await removeCommand("sw", { force: true, local: true }); expect(mockRmSync).toHaveBeenCalledWith("/workspace/project/.claude/commands/sw", expect.anything()); expect(mockClaudePluginUninstall).toHaveBeenCalledWith("sw@team", "project", { cwd: "/workspace/project" }); expect(mockRmSync.mock.calls.every(([path]) => path.startsWith("/workspace/project/"))).toBe(true); }); it("0877: legacy home lock supplies global provenance and is removed in that scope", async () => { mockReadLockfile.mockImplementation((dir?: string) => makeLockfile( dir === "/home/testuser" ? { sw: { marketplace: "legacy" } } : {}, )); mockExistsSync.mockReturnValue(false); mockIsPluginEnabled.mockReturnValue(true); await removeCommand("sw", { force: true, global: true }); expect(mockRemoveSkillFromLock).toHaveBeenCalledWith("sw", "/home/testuser"); expect(mockRemoveSkillFromLock).not.toHaveBeenCalledWith("sw", process.cwd()); expect(mockClaudePluginUninstall).toHaveBeenCalledWith("sw@legacy", "user", undefined); }); it("removes skill from all detected agent directories", async () => { mockReadLockfile.mockReturnValue( makeLockfile({ sw: { version: "1.0.0", sha: "abc123", tier: "VERIFIED", installedAt: "2026-01-01T00:00:00.000Z", source: "local:/path", }, }), ); // All dirs exist mockExistsSync.mockReturnValue(true); await removeCommand("sw", { force: true }); // Should attempt to remove from both agents (local + global = 4 paths) expect(mockRmSync).toHaveBeenCalled(); expect(mockRemoveSkillFromLock).toHaveBeenCalledWith("sw", process.cwd()); }); it("errors when skill not in lockfile and no --force", async () => { mockReadLockfile.mockReturnValue(makeLockfile({})); const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {}); const exitSpy = vi .spyOn(process, "exit") .mockImplementation(() => undefined as never); await removeCommand("unknown-skill", {}); expect(consoleSpy).toHaveBeenCalled(); expect(exitSpy).toHaveBeenCalledWith(1); consoleSpy.mockRestore(); exitSpy.mockRestore(); }); it("proceeds with --force even when skill not in lockfile", async () => { mockReadLockfile.mockReturnValue(makeLockfile({})); mockExistsSync.mockReturnValue(false); // Should not throw or exit await removeCommand("unknown-skill", { force: true }); // Still tries detection, just nothing to remove expect(mockDetectInstalledAgents).toHaveBeenCalled(); }); it("only removes global dirs when --global flag set", async () => { mockReadLockfile.mockReturnValue( makeLockfile({ sw: { version: "1.0.0", sha: "abc123", tier: "VERIFIED", installedAt: "2026-01-01T00:00:00.000Z", source: "local:/path", }, }), ); mockExistsSync.mockReturnValue(true); await removeCommand("sw", { force: true, global: true }); // Should only remove from global dirs (tilde-resolved paths) const removedPaths = mockRmSync.mock.calls.map( (c: unknown[]) => c[0] as string, ); for (const p of removedPaths) { expect(p).toMatch(/^\/home\/testuser/); } }); it("only removes local dirs when --local flag set", async () => { mockReadLockfile.mockReturnValue( makeLockfile({ sw: { version: "1.0.0", sha: "abc123", tier: "VERIFIED", installedAt: "2026-01-01T00:00:00.000Z", source: "local:/path", }, }), ); mockExistsSync.mockReturnValue(true); await removeCommand("sw", { force: true, local: true }); // Should only remove from local dirs (relative paths resolved with cwd) const removedPaths = mockRmSync.mock.calls.map( (c: unknown[]) => c[0] as string, ); for (const p of removedPaths) { expect(p).not.toMatch(/^\/home\/testuser/); } }); it("handles missing directories gracefully", async () => { mockReadLockfile.mockReturnValue( makeLockfile({ sw: { version: "1.0.0", sha: "abc123", tier: "VERIFIED", installedAt: "2026-01-01T00:00:00.000Z", source: "local:/path", }, }), ); // No dirs exist mockExistsSync.mockReturnValue(false); // Should not throw await removeCommand("sw", { force: true }); // rmSync should not be called since dirs don't exist expect(mockRmSync).not.toHaveBeenCalled(); // But lockfile should still be updated expect(mockRemoveSkillFromLock).toHaveBeenCalledWith("sw", process.cwd()); }); // 0724 F-002 regression — marketplace plugin path (multi-scope uninstall) // Reason this test exists: prior fixtures had no `marketplace` field, so // resolvePluginId() always returned null and the multi-scope block in // remove.ts was unexercised. That coverage gap let an unimported // `isPluginEnabled` symbol slip through (F-001). This test pins the // marketplace path and asserts the F-002 contract: only enabled scopes // are uninstalled, and the JSON envelope reports pluginId/pluginUninstallOk. it("0724 F-002: marketplace plugin enabled at user-only scope uninstalls user only", async () => { mockReadLockfile.mockReturnValue( makeLockfile({ foo: { version: "1.0.0", sha: "abc123", tier: "VERIFIED", installedAt: "2026-01-01T00:00:00.000Z", source: "marketplace:specweave", marketplace: "specweave", scope: "user", }, }), ); mockExistsSync.mockReturnValue(false); // Plugin registered at user scope only — F-002 should walk both scopes // but only invoke uninstall for the enabled one. mockIsPluginEnabled.mockImplementation( (_id: string, opts: { scope: string }) => opts.scope === "user", ); const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); await removeCommand("foo", { force: true, json: true }); // Walked both scopes, called uninstall only for user expect(mockIsPluginEnabled).toHaveBeenCalledWith("foo@specweave", { scope: "user", }); expect(mockIsPluginEnabled).toHaveBeenCalledWith( "foo@specweave", expect.objectContaining({ scope: "project" }), ); expect(mockClaudePluginUninstall).toHaveBeenCalledTimes(1); expect(mockClaudePluginUninstall).toHaveBeenCalledWith( "foo@specweave", "user", undefined, ); // JSON envelope reports the marketplace contract const last = logSpy.mock.calls[logSpy.mock.calls.length - 1]; const parsed = JSON.parse(last.join(" ")); expect(parsed.pluginId).toBe("foo@specweave"); expect(parsed.pluginUninstallOk).toBe(true); logSpy.mockRestore(); }); // 0724 T-007 ---------------------------------------------------------- it("0724 T-007: emits structured per-agent JSON when --json passed", async () => { mockReadLockfile.mockReturnValue( makeLockfile({ sw: { version: "1.0.0", sha: "abc123", tier: "VERIFIED", installedAt: "2026-01-01T00:00:00.000Z", source: "local:/path", }, }), ); mockExistsSync.mockReturnValue(false); const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); await removeCommand("sw", { force: true, json: true }); const last = logSpy.mock.calls[logSpy.mock.calls.length - 1]; const parsed = JSON.parse(last.join(" ")); expect(parsed.skill).toBe("sw"); expect(parsed).toHaveProperty("perAgent"); expect(Array.isArray(parsed.perAgent)).toBe(true); expect(parsed.perAgent.length).toBeGreaterThanOrEqual(1); logSpy.mockRestore(); }); // F5 — canonical .agents/skills/ payload cleanup ------------------ // remove previously only deleted per-agent copies/symlinks; the canonical // store written by installSymlink() was stranded on disk forever. describe("F5: canonical store cleanup", () => { const ENTRY = { version: "1.0.0", sha: "abc123", tier: "VERIFIED", installedAt: "2026-01-01T00:00:00.000Z", source: "local:/path", }; const PROJECT_CANONICAL = join(process.cwd(), ".agents", "skills", "sw"); const GLOBAL_AGENTS_ROOT = "/home/testuser/.agents"; const GLOBAL_CANONICAL = join(GLOBAL_AGENTS_ROOT, "skills", "sw"); it("removes the project canonical payload once the lockfile entry is gone", async () => { mockReadLockfile .mockReturnValueOnce(makeLockfile({ sw: ENTRY })) // initial read .mockReturnValue(makeLockfile({})); // re-reads after removeSkillFromLock mockExistsSync.mockImplementation((p: string) => p === PROJECT_CANONICAL); await removeCommand("sw", { force: true, local: true }); expect(mockRmSync).toHaveBeenCalledWith(PROJECT_CANONICAL, { recursive: true, force: true, }); }); it("removes the global canonical payload on --global, leaving project alone", async () => { mockReadLockfile .mockReturnValueOnce(makeLockfile({ sw: ENTRY })) .mockReturnValue(makeLockfile({})); mockExistsSync.mockImplementation((p: string) => p === GLOBAL_CANONICAL); await removeCommand("sw", { force: true, global: true }); expect(mockRmSync).toHaveBeenCalledWith(GLOBAL_CANONICAL, { recursive: true, force: true, }); expect(mockRmSync).not.toHaveBeenCalledWith( PROJECT_CANONICAL, expect.anything(), ); }); it("drops the global lockfile entry but keeps the canonical while still referenced", async () => { // Global lockfile stubbornly keeps the entry (removal did not land) — // the still-referenced global canonical payload must survive. let projectReads = 0; mockReadLockfile.mockImplementation((dir?: string) => { if (dir === GLOBAL_AGENTS_ROOT) return makeLockfile({ sw: ENTRY }); projectReads++; return projectReads === 1 ? makeLockfile({ sw: ENTRY }) : makeLockfile({}); }); mockExistsSync.mockImplementation( (p: string) => p === GLOBAL_CANONICAL || p === PROJECT_CANONICAL, ); await removeCommand("sw", { force: true }); // remove syncs the global lockfile for the global files it deletes expect(mockRemoveSkillFromLock).toHaveBeenCalledWith( "sw", GLOBAL_AGENTS_ROOT, ); // ...but the still-referenced global canonical stays on disk expect(mockRmSync).not.toHaveBeenCalledWith( GLOBAL_CANONICAL, expect.anything(), ); // project canonical (no longer referenced) is removed expect(mockRmSync).toHaveBeenCalledWith(PROJECT_CANONICAL, { recursive: true, force: true, }); }); it("reports action 'removed' only for agents whose files were deleted", async () => { mockReadLockfile .mockReturnValueOnce(makeLockfile({ sw: ENTRY })) .mockReturnValue(makeLockfile({})); // Only Cursor has installed files mockExistsSync.mockImplementation((p: string) => p.includes(".cursor")); const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); await removeCommand("sw", { force: true, json: true }); const last = logSpy.mock.calls[logSpy.mock.calls.length - 1]; const parsed = JSON.parse(last.join(" ")); const cursor = parsed.perAgent.find( (r: { id: string }) => r.id === "cursor", ); const cc = parsed.perAgent.find( (r: { id: string }) => r.id === "claude-code", ); expect(cursor.action).toBe("removed"); expect(cc.action).toBe("not-applicable"); logSpy.mockRestore(); }); it("0894: removing the canonical payload reports shared-reader agents as removed", async () => { mockDetectInstalledAgents.mockResolvedValue([ MOCK_AGENTS[0], { ...MOCK_AGENTS[1], readsSharedSkills: { project: true, global: true } }, ]); mockReadLockfile .mockReturnValueOnce(makeLockfile({ sw: ENTRY })) .mockReturnValue(makeLockfile({})); // Cursor has no link of its own — only the canonical folder exists. mockExistsSync.mockImplementation((p: string) => p === PROJECT_CANONICAL); const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); await removeCommand("sw", { force: true, local: true, json: true }); expect(mockRmSync).toHaveBeenCalledWith(PROJECT_CANONICAL, { recursive: true, force: true }); const parsed = JSON.parse(logSpy.mock.calls[logSpy.mock.calls.length - 1].join(" ")); const byId = Object.fromEntries(parsed.perAgent.map((r: { id: string; action: string }) => [r.id, r.action])); expect(byId.cursor).toBe("removed"); expect(byId["claude-code"]).toBe("not-applicable"); logSpy.mockRestore(); }); it("0894: an agent whose skills dir IS the canonical folder keeps the lockfile guard", async () => { mockDetectInstalledAgents.mockResolvedValue([ { id: "codex", displayName: "Codex CLI", localSkillsDir: ".agents/skills", globalSkillsDir: "~/.agents/skills", readsSharedSkills: { project: true, global: true }, }, ]); // Global lockfile still references the skill → global canonical stays. mockReadLockfile.mockImplementation((dir?: string) => dir === GLOBAL_AGENTS_ROOT ? makeLockfile({ sw: ENTRY }) : makeLockfile({}), ); mockExistsSync.mockImplementation((p: string) => p === GLOBAL_CANONICAL); await removeCommand("sw", { force: true, global: true }); expect(mockRmSync).not.toHaveBeenCalledWith(GLOBAL_CANONICAL, expect.anything()); }); }); describe("0894: Antigravity legacy global dir and dangling links", () => { const ANTIGRAVITY = { id: "antigravity", displayName: "Antigravity", localSkillsDir: ".agents/skills", globalSkillsDir: "~/.gemini/config/skills", readsSharedSkills: { project: true, global: false }, }; it("removes a global install in the legacy ~/.gemini/antigravity/skills", async () => { mockDetectInstalledAgents.mockResolvedValue([ANTIGRAVITY]); mockReadLockfile.mockReturnValue(makeLockfile({})); const legacy = "/home/testuser/.gemini/antigravity/skills"; mockExistsSync.mockImplementation((p: string) => p === legacy || p === `${legacy}/sw`); await removeCommand("sw", { force: true, global: true }); expect(mockRmSync).toHaveBeenCalledWith(`${legacy}/sw`, { recursive: true, force: true }); }); it("removes an agent link left dangling after its target is gone", async () => { mockDetectInstalledAgents.mockResolvedValue([MOCK_AGENTS[1]]); mockReadLockfile.mockReturnValue(makeLockfile({})); mockExistsSync.mockReturnValue(false); // existsSync follows the dead link const link = "/home/testuser/.cursor/skills/sw"; mockLstatSync.mockImplementation(((p: string) => { if (p === link) return { isSymbolicLink: () => true }; throw Object.assign(new Error("ENOENT"), { code: "ENOENT" }); }) as never); await removeCommand("sw", { force: true, global: true }); expect(mockRmSync).toHaveBeenCalledWith(link, { recursive: true, force: true }); mockLstatSync.mockReset(); mockLstatSync.mockImplementation((): never => { throw Object.assign(new Error("ENOENT"), { code: "ENOENT" }); }); }); }); });