Files
PaperClipAI/server/src/__tests__/company-skills.test.ts
T
DottaandPaperclip 717684ad8f Add project folder browsing to skill imports (#9930)
## Thinking Path

> - Paperclip is the control plane teams use to manage AI agents and
their reusable capabilities.
> - Skills Manager lets operators discover and import skills from
project workspaces.
> - Automatic discovery only surfaces skills in conventional locations,
so valid skills stored elsewhere in a project are invisible.
> - Operators need a safe way to navigate project folders without
exposing paths outside the selected workspace.
> - This pull request adds company-scoped workspace folder browsing and
selection to the project skill import flow.
> - The benefit is that operators can find and import valid skill
folders regardless of repository layout while preserving workspace
boundaries.

## Linked Issues or Issue Description

- **Subsystem affected:** Cross-cutting (`server/`, `ui/`, and
`packages/shared`).
- **Problem or motivation:** Project skill imports rely on conventional
directory discovery, which prevents operators from selecting valid
`SKILL.md` folders stored in atypical locations.
- **Proposed solution:** Add a company-scoped browse endpoint and a
folder browser in the import dialog. The server resolves real paths,
rejects traversal outside the workspace, skips symlinks and high-noise
directories, identifies skill directories/files, and caps listings at
250 entries.
- **Alternatives considered:** Expanding the automatic scan to every
directory would be slower and noisier, while accepting arbitrary
filesystem paths would weaken project/workspace scoping.
- **Roadmap alignment:** This extends the completed “Skills Manager,
Skill Studio & Skills Store” capability in `ROADMAP.md` without
duplicating planned core work.
- **Additional context:** GitHub search found no duplicate or closely
related public issues or pull requests.

## What Changed

- Added shared browse request/result contracts and validation for
project workspace navigation.
- Added a company-scoped API route and service that safely lists local
workspace folders and detects `SKILL.md` entries.
- Added project workspace/folder navigation to the import dialog,
including parent navigation, workspace switching, truncation feedback,
and direct skill selection.
- Added service and route regression tests for browsing, skill
detection, company isolation, and traversal rejection.
- Added shared response schemas and OpenAPI documentation for the browse
endpoint.
- Hardened explicit skill selections with realpath containment so
symlinked directories cannot escape the project workspace.

## Verification

- `pnpm exec vitest run
server/src/__tests__/company-skills-service.test.ts
server/src/__tests__/company-skills.test.ts` — 64 tests passed.
- `pnpm --filter @paperclipai/shared typecheck` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm exec vitest run server/src/__tests__/openapi-routes.test.ts` — 3
tests passed.
- Focused post-review reruns: `company-skills-service.test.ts` — 45
tests passed; shared/server typechecks passed.
- GitHub latest-head checks — all green after one transient e2e rerun;
no pending or failing checks.
- `pnpm check:token-gates` — all gates clean on the rebased head.

## Risks

- Low-to-moderate risk: this adds a filesystem browsing surface.
Realpath containment checks prevent workspace escape, symlinks are
excluded, remote-managed workspaces are rejected, and directory listings
are capped.
- The browser intentionally hides `.git` and `node_modules`; skills
inside those directories cannot be selected through this flow.

> 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

- OpenAI Codex, exact model ID `gpt-5.5`, reasoning-enabled with
terminal/tool use and code execution; runtime context-window size is not
exposed.

## 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)
- [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
— the execution harness requires preserving the assigned branch name.
- [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 — no
user-facing docs changes are needed beyond this PR description because
the flow is self-explanatory UI behavior.
- [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>
2026-08-02 10:55:36 -05:00

434 lines
15 KiB
TypeScript

import os from "node:os";
import path from "node:path";
import { promises as fs } from "node:fs";
import { afterEach, describe, expect, it } from "vitest";
import {
discoverProjectWorkspaceSkillDirectories,
findMissingLocalSkillIds,
normalizeGitHubSkillDirectory,
parseSkillImportSourceInput,
readLocalSkillImportFromDirectory,
} from "../services/company-skills.js";
const cleanupDirs = new Set<string>();
afterEach(async () => {
await Promise.all(Array.from(cleanupDirs, (dir) => fs.rm(dir, { recursive: true, force: true })));
cleanupDirs.clear();
});
async function makeTempDir(prefix: string) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
cleanupDirs.add(dir);
return dir;
}
async function writeSkillDir(skillDir: string, name: string) {
await fs.mkdir(skillDir, { recursive: true });
await fs.writeFile(path.join(skillDir, "SKILL.md"), `---\nname: ${name}\n---\n\n# ${name}\n`, "utf8");
}
describe("company skill import source parsing", () => {
it("parses a skills.sh command without executing shell input", () => {
const parsed = parseSkillImportSourceInput(
"npx skills add https://github.com/vercel-labs/skills --skill find-skills",
);
expect(parsed.resolvedSource).toBe("https://github.com/vercel-labs/skills");
expect(parsed.requestedSkillSlug).toBe("find-skills");
expect(parsed.originalSkillsShUrl).toBeNull();
expect(parsed.warnings).toEqual([]);
});
it("parses owner/repo/skill shorthand as skills.sh-managed", () => {
const parsed = parseSkillImportSourceInput("vercel-labs/skills/find-skills");
expect(parsed.resolvedSource).toBe("https://github.com/vercel-labs/skills");
expect(parsed.requestedSkillSlug).toBe("find-skills");
expect(parsed.originalSkillsShUrl).toBe("https://skills.sh/vercel-labs/skills/find-skills");
});
it("resolves skills.sh URL with org/repo/skill to GitHub repo and preserves original URL", () => {
const parsed = parseSkillImportSourceInput(
"https://skills.sh/google-labs-code/stitch-skills/design-md",
);
expect(parsed.resolvedSource).toBe("https://github.com/google-labs-code/stitch-skills");
expect(parsed.requestedSkillSlug).toBe("design-md");
expect(parsed.originalSkillsShUrl).toBe("https://skills.sh/google-labs-code/stitch-skills/design-md");
});
it("resolves skills.sh URL with org/repo (no skill) to GitHub repo and preserves original URL", () => {
const parsed = parseSkillImportSourceInput(
"https://skills.sh/vercel-labs/skills",
);
expect(parsed.resolvedSource).toBe("https://github.com/vercel-labs/skills");
expect(parsed.requestedSkillSlug).toBeNull();
expect(parsed.originalSkillsShUrl).toBe("https://skills.sh/vercel-labs/skills");
});
it("parses skills.sh commands whose requested skill differs from the folder name", () => {
const parsed = parseSkillImportSourceInput(
"npx skills add https://github.com/remotion-dev/skills --skill remotion-best-practices",
);
expect(parsed.resolvedSource).toBe("https://github.com/remotion-dev/skills");
expect(parsed.requestedSkillSlug).toBe("remotion-best-practices");
expect(parsed.originalSkillsShUrl).toBeNull();
});
it("does not set originalSkillsShUrl for owner/repo shorthand", () => {
const parsed = parseSkillImportSourceInput("vercel-labs/skills");
expect(parsed.resolvedSource).toBe("https://github.com/vercel-labs/skills");
expect(parsed.originalSkillsShUrl).toBeNull();
});
it("rejects secret-bearing remote URLs without echoing the secret", () => {
const source = "https://github.com/acme/private-skill?token=secret#token=secret";
expect(() => parseSkillImportSourceInput(source)).toThrow(
"Remote skill source URLs cannot include credentials, query parameters, or fragments.",
);
try {
parseSkillImportSourceInput(source);
} catch (error) {
expect((error as Error).message).not.toContain("secret");
}
});
it("rejects malformed remote URLs as validation errors", () => {
expect(() => parseSkillImportSourceInput("https://")).toThrow(
"Invalid remote skill source URL.",
);
});
it("canonicalizes clean GitHub URLs before persistence", () => {
const parsed = parseSkillImportSourceInput(
"https://www.github.com/Vercel-Labs/Agent-Browser/blob/main/skills/Upper/SKILL.MD",
);
expect(parsed.resolvedSource).toBe(
"https://github.com/vercel-labs/agent-browser/blob/main/skills/Upper/SKILL.MD",
);
expect(parsed.originalSkillsShUrl).toBeNull();
});
});
describe("project workspace skill discovery", () => {
it("normalizes GitHub skill directories for blob imports and legacy metadata", () => {
expect(normalizeGitHubSkillDirectory("retro/.", "retro")).toBe("retro");
expect(normalizeGitHubSkillDirectory("retro/SKILL.md", "retro")).toBe("retro");
expect(normalizeGitHubSkillDirectory("SKILL.md", "root-skill")).toBe("");
expect(normalizeGitHubSkillDirectory("", "fallback-skill")).toBe("fallback-skill");
});
it("finds bounded skill roots under supported workspace paths", async () => {
const workspace = await makeTempDir("paperclip-skill-workspace-");
await writeSkillDir(workspace, "Workspace Root");
await writeSkillDir(path.join(workspace, "skills", "find-skills"), "Find Skills");
await writeSkillDir(path.join(workspace, ".agents", "skills", "release"), "Release");
await writeSkillDir(path.join(workspace, "skills", ".system", "paperclip"), "Paperclip");
await fs.writeFile(path.join(workspace, "README.md"), "# ignore\n", "utf8");
const discovered = await discoverProjectWorkspaceSkillDirectories({
projectId: "11111111-1111-1111-1111-111111111111",
projectName: "Repo",
workspaceId: "22222222-2222-2222-2222-222222222222",
workspaceName: "Main",
workspaceCwd: workspace,
});
expect(discovered).toEqual([
{ skillDir: path.resolve(workspace), directoryRoot: ".", relativePath: ".", inventoryMode: "project_root" },
{
skillDir: path.resolve(workspace, ".agents", "skills", "release"),
directoryRoot: ".agents/skills",
relativePath: ".agents/skills/release",
inventoryMode: "full",
},
{
skillDir: path.resolve(workspace, "skills", ".system", "paperclip"),
directoryRoot: "skills/.system",
relativePath: "skills/.system/paperclip",
inventoryMode: "full",
},
{
skillDir: path.resolve(workspace, "skills", "find-skills"),
directoryRoot: "skills",
relativePath: "skills/find-skills",
inventoryMode: "full",
},
]);
});
it("limits root SKILL.md imports to skill-related support folders", async () => {
const workspace = await makeTempDir("paperclip-root-skill-");
await writeSkillDir(workspace, "Workspace Skill");
await fs.mkdir(path.join(workspace, "references"), { recursive: true });
await fs.mkdir(path.join(workspace, "scripts"), { recursive: true });
await fs.mkdir(path.join(workspace, "assets"), { recursive: true });
await fs.mkdir(path.join(workspace, "src"), { recursive: true });
await fs.writeFile(path.join(workspace, "references", "checklist.md"), "# Checklist\n", "utf8");
await fs.writeFile(path.join(workspace, "scripts", "run.sh"), "echo ok\n", "utf8");
await fs.writeFile(path.join(workspace, "assets", "logo.svg"), "<svg />\n", "utf8");
await fs.writeFile(path.join(workspace, "README.md"), "# Repo\n", "utf8");
await fs.writeFile(path.join(workspace, "src", "index.ts"), "export {};\n", "utf8");
const imported = await readLocalSkillImportFromDirectory(
"33333333-3333-4333-8333-333333333333",
workspace,
{ inventoryMode: "project_root", metadata: { sourceKind: "project_scan" } },
);
expect(new Set(imported.fileInventory.map((entry) => entry.path))).toEqual(new Set([
"assets/logo.svg",
"references/checklist.md",
"scripts/run.sh",
"SKILL.md",
]));
expect(imported.fileInventory.map((entry) => entry.kind)).toContain("script");
expect(imported.metadata?.sourceKind).toBe("project_scan");
});
it("rejects symlinks reachable from a project-scanned skill", async () => {
const workspace = await makeTempDir("paperclip-linked-skill-file-");
const skillDir = path.join(workspace, ".codex", "skills", "linked-file");
const outsideFile = path.join(await makeTempDir("paperclip-linked-skill-outside-"), "outside.md");
await writeSkillDir(skillDir, "Linked File");
await fs.mkdir(path.join(skillDir, "references"), { recursive: true });
await fs.writeFile(outsideFile, "outside workspace\n", "utf8");
await fs.symlink(outsideFile, path.join(skillDir, "references", "outside.md"));
await expect(readLocalSkillImportFromDirectory(
"33333333-3333-4333-8333-333333333333",
skillDir,
{ inventoryMode: "full", workspaceRoot: workspace },
)).rejects.toThrow(/symbolic link/);
});
it("parses inline object array items in skill frontmatter metadata", async () => {
const workspace = await makeTempDir("paperclip-inline-skill-yaml-");
await fs.mkdir(workspace, { recursive: true });
await fs.writeFile(
path.join(workspace, "SKILL.md"),
[
"---",
"name: Inline Metadata Skill",
"metadata:",
" sources:",
" - kind: github-dir",
" repo: paperclipai/paperclip",
" path: skills/paperclip",
"---",
"",
"# Inline Metadata Skill",
"",
].join("\n"),
"utf8",
);
const imported = await readLocalSkillImportFromDirectory(
"33333333-3333-4333-8333-333333333333",
workspace,
{ inventoryMode: "full" },
);
expect(imported.metadata).toMatchObject({
sourceKind: "local_path",
sources: [
{
kind: "github-dir",
repo: "paperclipai/paperclip",
path: "skills/paperclip",
},
],
});
});
it("parses folded and literal block scalar descriptions in skill frontmatter", async () => {
const foldedWorkspace = await makeTempDir("paperclip-folded-skill-yaml-");
await fs.mkdir(foldedWorkspace, { recursive: true });
await fs.writeFile(
path.join(foldedWorkspace, "SKILL.md"),
[
"---",
"name: Folded Metadata Skill",
"description: >",
" Use when you need website engagement data - sessions,",
" pageviews, and conversions.",
"",
"---",
"",
"# Folded Metadata Skill",
"",
].join("\n"),
"utf8",
);
const literalWorkspace = await makeTempDir("paperclip-literal-skill-yaml-");
await fs.mkdir(literalWorkspace, { recursive: true });
await fs.writeFile(
path.join(literalWorkspace, "SKILL.md"),
[
"---",
"name: Literal Metadata Skill",
"description: |",
" First line.",
" Second line.",
"",
"metadata:",
" clipNote: |",
" Keep this line.",
" And this one.",
"",
" stripNote: |-",
" Strip this line.",
" And this one.",
"---",
"",
"# Literal Metadata Skill",
"",
].join("\n"),
"utf8",
);
const stripWorkspace = await makeTempDir("paperclip-strip-skill-yaml-");
await fs.mkdir(stripWorkspace, { recursive: true });
await fs.writeFile(
path.join(stripWorkspace, "SKILL.md"),
[
"---",
"name: Strip Metadata Skill",
"description: >-",
" Strip this folded description",
" without a trailing newline.",
"---",
"",
"# Strip Metadata Skill",
"",
].join("\n"),
"utf8",
);
const folded = await readLocalSkillImportFromDirectory(
"33333333-3333-4333-8333-333333333333",
foldedWorkspace,
{ inventoryMode: "full" },
);
const literal = await readLocalSkillImportFromDirectory(
"33333333-3333-4333-8333-333333333333",
literalWorkspace,
{ inventoryMode: "full" },
);
const strip = await readLocalSkillImportFromDirectory(
"33333333-3333-4333-8333-333333333333",
stripWorkspace,
{ inventoryMode: "full" },
);
expect(folded.description).toBe(
"Use when you need website engagement data - sessions, pageviews, and conversions.",
);
expect(literal.description).toBe("First line.\nSecond line.");
expect(literal.metadata).toMatchObject({
clipNote: "Keep this line.\nAnd this one.\n",
stripNote: "Strip this line.\nAnd this one.",
});
expect(strip.description).toBe("Strip this folded description without a trailing newline.");
});
it("parses YAML block-scalar chomping variants from SKILL.md frontmatter", async () => {
const workspace = await makeTempDir("paperclip-block-scalar-chomp-skill-");
await fs.mkdir(workspace, { recursive: true });
await fs.writeFile(
path.join(workspace, "SKILL.md"),
[
"---",
"name: Block Scalar Chomp Skill",
"description: >-",
" First line",
" second line",
"---",
"",
"# Block Scalar Chomp Skill",
"",
].join("\n"),
"utf8",
);
const imported = await readLocalSkillImportFromDirectory(
"33333333-3333-4333-8333-333333333333",
workspace,
{ inventoryMode: "full" },
);
expect(imported.description).toBe("First line second line");
});
it("includes explicitly selected skills from non-standard folders", async () => {
const workspace = await makeTempDir("paperclip-skill-workspace-");
await writeSkillDir(path.join(workspace, "content", "specialists", "editorial"), "Editorial");
const discovered = await discoverProjectWorkspaceSkillDirectories({
projectId: "11111111-1111-1111-1111-111111111111",
projectName: "Repo",
workspaceId: "22222222-2222-2222-2222-222222222222",
workspaceName: "Main",
workspaceCwd: workspace,
}, ["content/specialists/editorial"]);
expect(discovered).toEqual([
{
skillDir: path.resolve(workspace, "content", "specialists", "editorial"),
directoryRoot: "content/specialists",
relativePath: "content/specialists/editorial",
inventoryMode: "full",
},
]);
});
});
describe("missing local skill reconciliation", () => {
it("flags local-path skills whose directory was removed", async () => {
const workspace = await makeTempDir("paperclip-missing-skill-dir-");
const skillDir = path.join(workspace, "skills", "ghost");
await writeSkillDir(skillDir, "Ghost");
await fs.rm(skillDir, { recursive: true, force: true });
const missingIds = await findMissingLocalSkillIds([
{
id: "skill-1",
sourceType: "local_path",
sourceLocator: skillDir,
},
{
id: "skill-2",
sourceType: "github",
sourceLocator: "https://github.com/vercel-labs/agent-browser",
},
]);
expect(missingIds).toEqual(["skill-1"]);
});
it("flags local-path skills whose SKILL.md file was removed", async () => {
const workspace = await makeTempDir("paperclip-missing-skill-file-");
const skillDir = path.join(workspace, "skills", "ghost");
await writeSkillDir(skillDir, "Ghost");
await fs.rm(path.join(skillDir, "SKILL.md"), { force: true });
const missingIds = await findMissingLocalSkillIds([
{
id: "skill-1",
sourceType: "local_path",
sourceLocator: skillDir,
},
]);
expect(missingIds).toEqual(["skill-1"]);
});
});