Files
PaperClipAI/server/src/__tests__/plugin-install-autobuild.test.ts
T
3ae2c30f2f feat(skills): import skills from projects (#9620)
## Thinking Path

> - Paperclip is the open source control plane people use to manage
AI-agent companies.
> - Company skills make reusable agent behavior discoverable and
editable from one place.
> - Projects already contain skill directories, but operators had to
import each skill path manually.
> - Copying those skills would break the desired write-through workflow
between Skill Studio and the source project.
> - The server therefore needs a safe preview/select/import contract
that only accepts rediscovered, workspace-contained candidates.
> - The UI needs a guided project picker that explains reference
semantics, handles conflicts, and remains usable on mobile.
> - This pull request adds that end-to-end project skill import flow
with authorization, tenant-scope, traversal, and symlink regression
coverage.
> - The benefit is faster bulk onboarding while keeping project files as
the single source of truth.

## Linked Issues or Issue Description

**Feature request**

**Problem:** Importing several skills already stored in a Paperclip
project requires operators to discover and submit each local path
individually. This is slow, hides which well-known directories were
searched, and makes conflict/already-imported states difficult to
evaluate before mutation.

**Proposed solution:** Add an “Import skills from project” flow that
previews skills from well-known directories, lets operators selectively
import eligible candidates, and stores local-path references so Skill
Studio edits write through to the project files.

**Alternatives considered:** Copying files into company-managed skill
storage was rejected because it creates divergent copies. Trusting
client-supplied paths was rejected because imports must be constrained
to server-rediscovered, workspace-contained candidates.

**Additional context:** GitHub duplicate search found no existing issue
or PR for this exact workflow. Refs #3799 for related skill-import
inventory behavior; this PR does not claim to close that issue.

## What Changed

- Extend `scan-projects` with backward-compatible preview and
selective-import modes, typed validation, candidate statuses, and
OpenAPI coverage.
- Discover project skills under `skills`, `.agents/skills`,
`.claude/skills`, `.codex/skills`, `.cursor/skills`, `.opencode/skills`,
and `.gemini/skills`.
- Re-discover selections server-side, enforce company/project/workspace
scope, and reject traversal or symlink escapes before creating
`local_path` references.
- Add the Skills-page menu entry and responsive project import dialog
with project selection, grouped candidates, select all/deselect all,
conflicts, empty/error/403 states, and import results.
- Add route, service, and component regressions for preview
authorization, cross-tenant selections, traversal/symlink safety,
selection counts, grouping, and result semantics.

### Screenshots

**Choose a project**

![Choose a
project](https://raw.githubusercontent.com/cryppadotta/paperclip-prs/refs/heads/pr-assets/import-skills-from-project/01-pick-project.png)

**Review discovered skills**

![Review discovered
skills](https://raw.githubusercontent.com/cryppadotta/paperclip-prs/refs/heads/pr-assets/import-skills-from-project/03-select.png)

**Mobile selection footer**

![Mobile selection
footer](https://raw.githubusercontent.com/cryppadotta/paperclip-prs/refs/heads/pr-assets/import-skills-from-project/select-390.png)

**Import result**

![Import
result](https://raw.githubusercontent.com/cryppadotta/paperclip-prs/refs/heads/pr-assets/import-skills-from-project/06-result.png)

## Verification

- `pnpm exec vitest run
server/src/__tests__/company-skills-service.test.ts
server/src/__tests__/company-skills-routes.test.ts
ui/src/pages/skills/ImportSkillsFromProjectDialog.test.tsx` — 3 files,
81 tests passed.
- `pnpm check:token-gates` — all token gates clean.
- `pnpm --filter @paperclipai/shared typecheck` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- Security review passed after adding tenant-scope and
unauthorized-preview regressions; UX re-review approved desktop/mobile
surfaces; QA passed all seven acceptance areas including write-through
editing, deduplication, conflicts, empty state, and permission denial.

## Risks

- Files remain referenced in project workspaces, so moving or deleting a
source directory can make an imported skill unavailable; the UI
explicitly communicates the reference behavior.
- New well-known directory scans may discover more candidates than older
versions, but preview mode prevents mutation until the operator confirms
a selection.
- The endpoint remains backward compatible: omitting `mode` preserves
the prior full-import behavior.
- No schema migration or telemetry event changes.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Anthropic Claude Opus 4.8 with tool use/code execution assisted with
the UI implementation and UX polish. OpenAI Codex CLI with tool use/code
execution assisted with server implementation, security fixes,
regression coverage, integration, and PR preparation; the runtime did
not expose Codex's exact backing model ID or context-window size.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 18:01:44 -05:00

403 lines
15 KiB
TypeScript

import express from "express";
import { randomUUID } from "node:crypto";
import { existsSync } from "node:fs";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import request from "supertest";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { createDb, plugins } from "@paperclipai/db";
import {
ensureLocalPluginBuilt,
pluginLoader,
REPO_ROOT,
} from "../services/plugin-loader.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
const mockLifecycle = vi.hoisted(() => ({
load: vi.fn(),
upgrade: vi.fn(),
unload: vi.fn(),
enable: vi.fn(),
disable: vi.fn(),
}));
vi.mock("../services/plugin-lifecycle.js", () => ({
pluginLifecycleManager: () => mockLifecycle,
}));
vi.mock("../services/activity-log.js", () => ({
logActivity: vi.fn(),
}));
vi.mock("../services/live-events.js", () => ({
publishGlobalLiveEvent: vi.fn(),
}));
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe.sequential : describe.skip;
if (!embeddedPostgresSupport.supported) {
console.warn(
`Skipping plugin install auto-build tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
);
}
type FixturePlugin = {
packageName: string;
pluginKey: string;
packageRoot: string;
distDir: string;
};
const repoPluginRoot = path.join(REPO_ROOT, "packages", "plugins");
const standaloneRepoPluginRoot = path.join(repoPluginRoot, "sandbox-providers");
async function createBundledPluginFixture(
nameSuffix: string,
options: { rootDir?: string; buildDistImmediately?: boolean } = {},
): Promise<FixturePlugin> {
const slug = `plugin-autobuild-${nameSuffix}-${randomUUID().slice(0, 8)}`;
const packageName = `@paperclipai/${slug}`;
const pluginKey = `paperclip.${slug.replace(/^plugin-/, "").replace(/-/g, "_")}`;
const packageRoot = path.join(options.rootDir ?? repoPluginRoot, slug);
const distDir = path.join(packageRoot, "dist");
const isStandaloneFixture = (options.rootDir ?? repoPluginRoot) === standaloneRepoPluginRoot;
const postinstallScript = isStandaloneFixture
? `node ${path.relative(packageRoot, path.join(REPO_ROOT, "scripts", "link-plugin-dev-sdk.mjs"))}`
: null;
await mkdir(path.join(packageRoot, "scripts"), { recursive: true });
await writeFile(
path.join(packageRoot, "package.json"),
JSON.stringify({
name: packageName,
version: "0.1.0",
private: true,
type: "module",
scripts: {
...(postinstallScript ? { postinstall: postinstallScript } : {}),
build: "node ./scripts/build.mjs",
},
paperclipPlugin: {
manifest: "./dist/manifest.js",
worker: "./dist/worker.js",
ui: "./dist/ui/",
},
}, null, 2),
"utf8",
);
const manifest = {
id: pluginKey,
apiVersion: 1,
version: "0.1.0",
displayName: "Autobuild Fixture",
description: "Bundled plugin fixture for install-time auto-build coverage.",
author: "Paperclip",
categories: ["automation"],
capabilities: ["companies.read"],
entrypoints: {
worker: "./dist/worker.js",
},
};
await writeFile(
path.join(packageRoot, "scripts", "build.mjs"),
[
"import { mkdir, writeFile } from \"node:fs/promises\";",
"import path from \"node:path\";",
"import { fileURLToPath } from \"node:url\";",
"",
"const scriptDir = path.dirname(fileURLToPath(import.meta.url));",
"const packageRoot = path.resolve(scriptDir, \"..\");",
"const distDir = path.join(packageRoot, \"dist\");",
"const uiDir = path.join(distDir, \"ui\");",
`const manifest = ${JSON.stringify(manifest, null, 2)};`,
"",
"await mkdir(uiDir, { recursive: true });",
"await writeFile(path.join(distDir, \"manifest.js\"), `export default ${JSON.stringify(manifest, null, 2)};\\n`, \"utf8\");",
"await writeFile(path.join(distDir, \"worker.js\"), \"export {};\\n\", \"utf8\");",
"await writeFile(path.join(uiDir, \"index.js\"), \"export default {};\\n\", \"utf8\");",
].join("\n"),
"utf8",
);
if (options.buildDistImmediately) {
await mkdir(path.join(distDir, "ui"), { recursive: true });
await writeFile(path.join(distDir, "manifest.js"), `export default ${JSON.stringify(manifest, null, 2)};\n`, "utf8");
await writeFile(path.join(distDir, "worker.js"), "export {};\n", "utf8");
await writeFile(path.join(distDir, "ui", "index.js"), "export default {};\n", "utf8");
}
return { packageName, pluginKey, packageRoot, distDir };
}
async function createInstallApp(db: ReturnType<typeof createDb>) {
const [{ pluginRoutes }, { errorHandler }] = await Promise.all([
import("../routes/plugins.js"),
import("../middleware/index.js"),
]);
const loader = pluginLoader(db, {
enableLocalFilesystem: false,
enableNpmDiscovery: false,
});
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = {
type: "board",
userId: "admin-1",
source: "session",
isInstanceAdmin: true,
companyIds: [],
} as typeof req.actor;
next();
});
app.use("/api", pluginRoutes(db as never, loader as never, {} as never, undefined, {} as never, {} as never));
app.use(errorHandler);
return app;
}
describe("ensureLocalPluginBuilt", () => {
const cleanupPaths = new Set<string>();
afterEach(async () => {
for (const cleanupPath of cleanupPaths) {
await rm(cleanupPath, { recursive: true, force: true });
}
cleanupPaths.clear();
});
it("skips auto-build for local plugin paths outside the repo", async () => {
const tempRoot = await mkdtemp(path.join(os.tmpdir(), "paperclip-plugin-outside-"));
const packageRoot = path.join(tempRoot, "plugin-outside");
cleanupPaths.add(path.dirname(packageRoot));
await mkdir(packageRoot, { recursive: true });
const execStub = vi.fn().mockResolvedValue({ stdout: "", stderr: "" });
await ensureLocalPluginBuilt(
packageRoot,
{
name: "@paperclipai/plugin-outside",
paperclipPlugin: {
manifest: "./dist/manifest.js",
worker: "./dist/worker.js",
},
},
{ execFileAsyncImpl: execStub },
);
expect(execStub).not.toHaveBeenCalled();
});
it("skips auto-build when PAPERCLIP_DISABLE_PLUGIN_AUTOBUILD=1", async () => {
const fixture = await createBundledPluginFixture("skip");
cleanupPaths.add(fixture.packageRoot);
const execStub = vi.fn().mockResolvedValue({ stdout: "", stderr: "" });
await ensureLocalPluginBuilt(
fixture.packageRoot,
JSON.parse(await readFile(path.join(fixture.packageRoot, "package.json"), "utf8")) as Record<string, unknown>,
{
processEnv: { PAPERCLIP_DISABLE_PLUGIN_AUTOBUILD: "1" },
execFileAsyncImpl: execStub,
},
);
expect(execStub).not.toHaveBeenCalled();
});
it("bootstraps standalone bundled plugins before building them", async () => {
const fixture = await createBundledPluginFixture("standalone", { rootDir: standaloneRepoPluginRoot });
cleanupPaths.add(fixture.packageRoot);
const execStub = vi.fn(async (_file: string, args: readonly string[]) => {
if (args.join(" ") === "install --ignore-workspace --no-lockfile") {
await mkdir(path.join(fixture.packageRoot, "node_modules", "@paperclipai", "plugin-sdk"), { recursive: true });
}
if (args.join(" ") === "build") {
await mkdir(path.join(fixture.distDir, "ui"), { recursive: true });
await writeFile(path.join(fixture.distDir, "manifest.js"), "export default {};\n", "utf8");
await writeFile(path.join(fixture.distDir, "worker.js"), "export {};\n", "utf8");
await writeFile(path.join(fixture.distDir, "ui", "index.js"), "export default {};\n", "utf8");
}
return { stdout: "", stderr: "" };
});
await ensureLocalPluginBuilt(
fixture.packageRoot,
JSON.parse(await readFile(path.join(fixture.packageRoot, "package.json"), "utf8")) as Record<string, unknown>,
{ execFileAsyncImpl: execStub },
);
expect(execStub).toHaveBeenCalledTimes(2);
expect(execStub).toHaveBeenNthCalledWith(
1,
"pnpm",
["install", "--ignore-workspace", "--no-lockfile"],
{ cwd: fixture.packageRoot, timeout: 120_000 },
);
expect(execStub).toHaveBeenNthCalledWith(
2,
"pnpm",
["build"],
{ cwd: fixture.packageRoot, timeout: 120_000 },
);
});
it("bootstraps standalone bundled plugin runtime dependencies when dist already exists", async () => {
const fixture = await createBundledPluginFixture("standalone-runtime", {
rootDir: standaloneRepoPluginRoot,
buildDistImmediately: true,
});
cleanupPaths.add(fixture.packageRoot);
const execStub = vi.fn(async () => {
await mkdir(path.join(fixture.packageRoot, "node_modules", "@paperclipai", "plugin-sdk"), { recursive: true });
return { stdout: "", stderr: "" };
});
await ensureLocalPluginBuilt(
fixture.packageRoot,
JSON.parse(await readFile(path.join(fixture.packageRoot, "package.json"), "utf8")) as Record<string, unknown>,
{ execFileAsyncImpl: execStub },
);
expect(execStub).toHaveBeenCalledTimes(1);
expect(execStub).toHaveBeenNthCalledWith(
1,
"pnpm",
["install", "--ignore-workspace", "--no-lockfile"],
{ cwd: fixture.packageRoot, timeout: 120_000 },
);
});
});
describeEmbeddedPostgres("plugin install auto-build route", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
const cleanupPaths = new Set<string>();
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-plugin-autobuild-");
db = createDb(tempDb.connectionString);
}, 20_000);
afterEach(async () => {
vi.clearAllMocks();
await db.delete(plugins);
for (const cleanupPath of cleanupPaths) {
await rm(cleanupPath, { recursive: true, force: true });
}
cleanupPaths.clear();
delete process.env["PAPERCLIP_DISABLE_PLUGIN_AUTOBUILD"];
});
afterAll(async () => {
await tempDb?.cleanup();
}, 30_000);
it("auto-builds bundled local plugins during POST /api/plugins/install when dist is missing", async () => {
const fixture = await createBundledPluginFixture("success");
cleanupPaths.add(fixture.packageRoot);
const app = await createInstallApp(db);
expect(existsSync(path.join(fixture.distDir, "manifest.js"))).toBe(false);
const res = await request(app)
.post("/api/plugins/install")
.send({ packageName: fixture.packageRoot, isLocalPath: true });
expect(res.status).toBe(200);
expect(res.body.packageName).toBe(fixture.packageName);
expect(res.body.pluginKey).toBe(fixture.pluginKey);
expect(existsSync(path.join(fixture.distDir, "manifest.js"))).toBe(true);
expect(existsSync(path.join(fixture.distDir, "worker.js"))).toBe(true);
expect(existsSync(path.join(fixture.distDir, "ui", "index.js"))).toBe(true);
expect(mockLifecycle.load).toHaveBeenCalledTimes(1);
}, 60_000);
it("auto-builds standalone bundled local plugins outside the root pnpm workspace", async () => {
const fixture = await createBundledPluginFixture("standalone-success", { rootDir: standaloneRepoPluginRoot });
cleanupPaths.add(fixture.packageRoot);
const app = await createInstallApp(db);
expect(existsSync(path.join(fixture.distDir, "manifest.js"))).toBe(false);
expect(existsSync(path.join(fixture.packageRoot, "node_modules"))).toBe(false);
const res = await request(app)
.post("/api/plugins/install")
.send({ packageName: fixture.packageRoot, isLocalPath: true });
expect(res.status).toBe(200);
expect(res.body.packageName).toBe(fixture.packageName);
expect(res.body.pluginKey).toBe(fixture.pluginKey);
expect(existsSync(path.join(fixture.distDir, "manifest.js"))).toBe(true);
expect(existsSync(path.join(fixture.distDir, "worker.js"))).toBe(true);
expect(existsSync(path.join(fixture.distDir, "ui", "index.js"))).toBe(true);
expect(existsSync(path.join(fixture.packageRoot, "node_modules", "@paperclipai", "plugin-sdk"))).toBe(true);
expect(mockLifecycle.load).toHaveBeenCalledTimes(1);
}, 60_000);
it("bootstraps standalone bundled local plugin runtime dependencies when dist already exists", async () => {
const fixture = await createBundledPluginFixture("standalone-runtime-success", {
rootDir: standaloneRepoPluginRoot,
buildDistImmediately: true,
});
cleanupPaths.add(fixture.packageRoot);
const app = await createInstallApp(db);
expect(existsSync(path.join(fixture.distDir, "manifest.js"))).toBe(true);
expect(existsSync(path.join(fixture.packageRoot, "node_modules", "@paperclipai", "plugin-sdk"))).toBe(false);
const res = await request(app)
.post("/api/plugins/install")
.send({ packageName: fixture.packageRoot, isLocalPath: true });
expect(res.status).toBe(200);
expect(res.body.packageName).toBe(fixture.packageName);
expect(res.body.pluginKey).toBe(fixture.pluginKey);
expect(existsSync(path.join(fixture.packageRoot, "node_modules", "@paperclipai", "plugin-sdk"))).toBe(true);
expect(mockLifecycle.load).toHaveBeenCalledTimes(1);
}, 60_000);
it("returns the manual build command when auto-build is disabled and dist is missing", async () => {
process.env["PAPERCLIP_DISABLE_PLUGIN_AUTOBUILD"] = "1";
const fixture = await createBundledPluginFixture("disabled");
cleanupPaths.add(fixture.packageRoot);
const app = await createInstallApp(db);
const res = await request(app)
.post("/api/plugins/install")
.send({ packageName: fixture.packageRoot, isLocalPath: true });
expect(res.status).toBe(400);
expect(res.body.error).toContain("does not appear to be a Paperclip plugin (no manifest found)");
expect(res.body.error).toContain(`pnpm --filter ${fixture.packageName} build`);
expect(existsSync(path.join(fixture.distDir, "manifest.js"))).toBe(false);
expect(mockLifecycle.load).not.toHaveBeenCalled();
}, 20_000);
it("returns the standalone bootstrap command when auto-build is disabled for sandbox-provider plugins", async () => {
process.env["PAPERCLIP_DISABLE_PLUGIN_AUTOBUILD"] = "1";
const fixture = await createBundledPluginFixture("standalone-disabled", { rootDir: standaloneRepoPluginRoot });
cleanupPaths.add(fixture.packageRoot);
const app = await createInstallApp(db);
const res = await request(app)
.post("/api/plugins/install")
.send({ packageName: fixture.packageRoot, isLocalPath: true });
expect(res.status).toBe(400);
expect(res.body.error).toContain("does not appear to be a Paperclip plugin (no manifest found)");
expect(res.body.error).toContain(path.relative(REPO_ROOT, fixture.packageRoot));
expect(res.body.error).toContain("pnpm install --ignore-workspace --no-lockfile && pnpm build");
expect(existsSync(path.join(fixture.distDir, "manifest.js"))).toBe(false);
expect(mockLifecycle.load).not.toHaveBeenCalled();
}, 20_000);
});