mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
feat: organize skills with nested folders and My Skills (#9633)
## Thinking Path > - Paperclip is the open source control plane people use to organize and govern AI-agent companies > - Company skills are durable resources that users browse, import, assign, and maintain over time > - A flat skill list plus tags does not provide a stable location or hierarchy for personal, company, project-imported, and bundled skills > - Folder paths need to be canonical, company-scoped, safe to move, and preserved across re-imports without changing skill IDs > - The `/skills` UI also needs traversal, breadcrumbs, move/create flows, and a dedicated My Skills namespace that work on desktop and mobile > - This pull request adds the folder data model and APIs, reserved-root lifecycle, project import behavior, and the folder-first skills experience > - The benefit is a predictable filesystem-like organization model while tags remain available for cross-cutting classification ## Linked Issues or Issue Description Refs #9619 — the reviewed folder foundation was intentionally closed and folded into this combined feature PR. Refs #9026 — earlier flat-folder attempt superseded by this integrated implementation. Refs #3281 — related skill organization proposal; this PR uses canonical persisted folders rather than deriving groups from skill keys, and does not add hidden-skill behavior. **Feature request** - **Problem:** Skills currently lack a canonical hierarchical location, making personal skills, project imports, bundled skills, and company-authored skills difficult to traverse and manage at scale. - **Proposed behavior:** Add nested company-scoped folders with stable paths, reserved My/Projects/Bundled roots, subtree queries, safe move/create operations, and a folder-first `/skills` library UI. - **Import behavior:** New project scans file skills under `projects/<project-slug>`; later imports update content without overriding a user-selected folder. - **Alternatives considered:** Tags alone remain useful for cross-cutting classification, but they do not provide canonical location, nesting, reserved namespaces, or stable import placement. - **Roadmap alignment:** Extends the completed Skills Manager and Scheduled Routines capabilities without duplicating an active roadmap item. ## What Changed - Adds `folders` persistence for routine and skill folders, nested canonical paths, parent/slug/system-key fields, migration backfills, and reapply-safe migrations `0174`–`0175` after current master migrations. - Adds company-scoped folder CRUD, cycle/depth/namespace validation, reserved My/Projects/Bundled lifecycle, item moves, subtree filtering, and folder paths on skill results. - Preserves project-import placement: first import files into the project folder, while re-import keeps user-owned placement and stable skill IDs. - Adds the `/skills` folder tree rail, tags facet, breadcrumbs, subfolder browser, move/new-folder dialog, canonical detail location, inline tag editing, and folder-aware Studio creation. - Keeps bundled skills read-only even when their source metadata is incomplete by detecting the reserved Bundled folder and hiding selection/move actions. - Extends routine folder UI and OpenAPI coverage, and adds regression tests across migrations, services, routes, tree helpers, pages, and Studio creation. ## Verification - `pnpm exec vitest run packages/db/src/nested-skill-folders-migration.test.ts server/src/__tests__/folders-routes.test.ts server/src/__tests__/folders-service.test.ts server/src/__tests__/company-skills-service.test.ts server/src/__tests__/routines-service.test.ts ui/src/components/folders/FolderControls.test.tsx ui/src/components/folders/SkillFolderTree.test.tsx ui/src/components/folders/skill-folder-tree.test.ts ui/src/pages/CompanySkills.test.tsx ui/src/pages/Routines.test.tsx ui/src/pages/SkillStudio.test.tsx ui/src/lib/company-skill-routes.test.ts ui/src/lib/skill-create.test.ts` — 13 files, 192 tests passed. - `pnpm exec vitest run ui/src/pages/CompanySkills.test.tsx ui/src/components/folders/SkillFolderTree.test.tsx` — 2 files, 20 tests passed after preserving the existing PR's bundled-skill fixes. - `pnpm -r typecheck` — passed for all workspace packages. - `pnpm test:run` — passed in an isolated CI-like environment with inherited Paperclip runtime identity and static AWS credential variables removed. - `pnpm build` — production build passed for all workspace packages. - Greptile iteration 2 — 5/5 confidence with zero unresolved threads on commit `ff2d67aa71`. - Latest-head GitHub checks — all success, neutral, or skipped; PR is mergeable with a clean merge state. - `pnpm check:token-gates` — reports nine existing `#9627` comment false positives already present on `master`; this PR introduces no new token violation. ## Risks - **Migration/backfill:** `0174` creates the foundation and `0175` adds nested/reserved semantics. Both are ordered after current master migration `0173`, are covered by numbering/safety checks, and are designed to be reapply-safe. - **Reserved namespaces:** My, Projects, and Bundled roots are service-managed. Regression coverage prevents namespace squatting, cross-company folder use, bundled writes, cycles, and excessive depth. - **Behavioral change:** Project scans choose a project folder only on initial creation; existing skills deliberately retain their current folder during refresh. - **UI scope:** The folder rail applies to the Installed library; Catalog retains the discovery-oriented category sidebar. > 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 `gpt-5.5` in Codex CLI, medium reasoning mode; runtime did not expose a context-window value. Used repository/file tools, terminal execution, Git/GitHub operations, test execution, and code editing. ## 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>
This commit is contained in:
1 parent
1d2b6af5ac
commit
52aea90263
53 files changed
+7010
-61
No files matched your search
@@ -4,7 +4,7 @@ import path from "node:path";
|
||||
import { promises as fs } from "node:fs";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { companies, companySkills, createDb } from "@paperclipai/db";
|
||||
import { companies, companySkills, createDb, folders } from "@paperclipai/db";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
@@ -132,6 +132,7 @@ describeEmbeddedPostgres("companySkillService.installFromCatalog", () => {
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(companySkills);
|
||||
await db.delete(folders);
|
||||
await db.delete(companies);
|
||||
await Promise.all(Array.from(cleanupDirs, (dir) => fs.rm(dir, { recursive: true, force: true })));
|
||||
cleanupDirs.clear();
|
||||
@@ -154,6 +155,7 @@ describeEmbeddedPostgres("companySkillService.installFromCatalog", () => {
|
||||
expect(result.action).toBe("created");
|
||||
expect(result.skill).toMatchObject({
|
||||
companyId,
|
||||
folderId: expect.any(String),
|
||||
key: sampleCatalogSkill.key,
|
||||
slug: sampleCatalogSkill.slug,
|
||||
sourceType: "catalog",
|
||||
@@ -182,6 +184,37 @@ describeEmbeddedPostgres("companySkillService.installFromCatalog", () => {
|
||||
packageName: "@paperclipai/skills-catalog",
|
||||
packageVersion: "0.3.1",
|
||||
});
|
||||
const folder = await db
|
||||
.select()
|
||||
.from(folders)
|
||||
.where(eq(folders.id, result.skill.folderId!))
|
||||
.then((rows) => rows[0]);
|
||||
expect(folder).toMatchObject({
|
||||
name: "Software Development",
|
||||
slug: "software-development",
|
||||
systemKey: "bundled:software-development",
|
||||
});
|
||||
});
|
||||
|
||||
it("repairs an existing unfiled Paperclip catalog skill during inventory refresh", async () => {
|
||||
const companyId = await createCompany();
|
||||
const installed = await svc.installFromCatalog(companyId, { catalogSkillId: sampleCatalogSkill.id });
|
||||
await db
|
||||
.update(companySkills)
|
||||
.set({ folderId: null })
|
||||
.where(eq(companySkills.id, installed.skill.id));
|
||||
|
||||
const listed = await svc.list(companyId);
|
||||
const repaired = listed.find((skill) => skill.id === installed.skill.id);
|
||||
const folder = repaired?.folderId
|
||||
? await db.select().from(folders).where(eq(folders.id, repaired.folderId)).then((rows) => rows[0])
|
||||
: null;
|
||||
|
||||
expect(repaired?.folderId).toEqual(expect.any(String));
|
||||
expect(folder).toMatchObject({
|
||||
name: "Software Development",
|
||||
systemKey: "bundled:software-development",
|
||||
});
|
||||
});
|
||||
|
||||
it("materializes catalog asset files without UTF-8 rewriting", async () => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
companySkillVersions,
|
||||
companySkills,
|
||||
createDb,
|
||||
folders,
|
||||
projects,
|
||||
projectWorkspaces,
|
||||
} from "@paperclipai/db";
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
import { companySkillService } from "../services/company-skills.ts";
|
||||
import { folderService } from "../services/folders.js";
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
@@ -63,6 +65,7 @@ describeEmbeddedPostgres("companySkillService.list", () => {
|
||||
await db.delete(companySkills);
|
||||
await db.delete(projectWorkspaces);
|
||||
await db.delete(projects);
|
||||
await db.delete(folders);
|
||||
await db.delete(companies);
|
||||
await db.delete(authUsers);
|
||||
await Promise.all(Array.from(cleanupDirs, (dir) => fs.rm(dir, { recursive: true, force: true })));
|
||||
@@ -310,6 +313,13 @@ describeEmbeddedPostgres("companySkillService.list", () => {
|
||||
const bundledSkill = initialList.find((skill) => skill.key.startsWith("paperclipai/paperclip/"));
|
||||
expect(bundledSkill).toBeDefined();
|
||||
if (!bundledSkill) throw new Error("Expected bundled Paperclip skills fixture");
|
||||
const bundledFolder = bundledSkill.folderId
|
||||
? await db.select().from(folders).where(eq(folders.id, bundledSkill.folderId)).then((rows) => rows[0])
|
||||
: null;
|
||||
expect(bundledFolder).toMatchObject({
|
||||
name: "Paperclip Core",
|
||||
systemKey: "bundled:paperclip-core",
|
||||
});
|
||||
|
||||
const preservedUpdatedAt = new Date("2026-01-01T00:00:00.000Z");
|
||||
await db
|
||||
@@ -323,6 +333,34 @@ describeEmbeddedPostgres("companySkillService.list", () => {
|
||||
expect(refreshedSkill?.updatedAt.toISOString()).toBe(preservedUpdatedAt.toISOString());
|
||||
});
|
||||
|
||||
it("repairs a squatted bundled root during bundled-skill list refresh", async () => {
|
||||
const companyId = randomUUID();
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "Paperclip",
|
||||
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
const [squatted] = await db.insert(folders).values({
|
||||
companyId,
|
||||
kind: "skill",
|
||||
parentId: null,
|
||||
name: "User Bundled",
|
||||
slug: "bundled",
|
||||
position: 0,
|
||||
}).returning();
|
||||
|
||||
const listed = await svc.list(companyId);
|
||||
const folderRows = await db.select().from(folders).where(eq(folders.companyId, companyId));
|
||||
const bundledRoot = folderRows.find((folder) => folder.systemKey === "bundled");
|
||||
const repairedSquat = folderRows.find((folder) => folder.id === squatted!.id);
|
||||
|
||||
expect(listed.some((skill) => skill.key.startsWith("paperclipai/paperclip/"))).toBe(true);
|
||||
expect(bundledRoot).toMatchObject({ slug: "bundled", parentId: null, systemKey: "bundled" });
|
||||
expect(repairedSquat).toMatchObject({ name: "User Bundled", systemKey: null });
|
||||
expect(repairedSquat?.slug).toMatch(/^bundled-[a-f0-9]{8}$/);
|
||||
});
|
||||
|
||||
it("does not retouch bundled skills with stale missing-source metadata during list refresh", async () => {
|
||||
const companyId = randomUUID();
|
||||
await db.insert(companies).values({
|
||||
@@ -686,6 +724,97 @@ describeEmbeddedPostgres("companySkillService.list", () => {
|
||||
await expect(svc.categoryCounts(companyId)).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it("filters by folder subtree, keeps search global, and returns canonical folder paths", async () => {
|
||||
const companyId = randomUUID();
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "Paperclip",
|
||||
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
const folderSvc = folderService(db);
|
||||
const engineering = await folderSvc.create(companyId, { kind: "skill", name: "Engineering" });
|
||||
const reviews = await folderSvc.create(companyId, { kind: "skill", parentId: engineering.id, name: "Reviews" });
|
||||
const operations = await folderSvc.create(companyId, { kind: "skill", name: "Operations" });
|
||||
|
||||
const reviewDir = await createManagedSkillDir(companyId, "review-");
|
||||
const deployDir = await createManagedSkillDir(companyId, "deploy-");
|
||||
await fs.writeFile(path.join(reviewDir, "SKILL.md"), "# Review\n", "utf8");
|
||||
await fs.writeFile(path.join(deployDir, "SKILL.md"), "# Deploy\n", "utf8");
|
||||
await db.insert(companySkills).values([
|
||||
{
|
||||
companyId,
|
||||
folderId: reviews.id,
|
||||
key: `company/${companyId}/review`,
|
||||
slug: "review",
|
||||
name: "Review",
|
||||
markdown: "# Review",
|
||||
sourceType: "local_path",
|
||||
sourceLocator: reviewDir,
|
||||
categories: ["engineering"],
|
||||
},
|
||||
{
|
||||
companyId,
|
||||
folderId: operations.id,
|
||||
key: `company/${companyId}/deploy`,
|
||||
slug: "deploy",
|
||||
name: "Deploy",
|
||||
markdown: "# Deploy",
|
||||
sourceType: "local_path",
|
||||
sourceLocator: deployDir,
|
||||
categories: ["operations"],
|
||||
},
|
||||
]);
|
||||
|
||||
await expect(svc.list(companyId, {
|
||||
folderId: engineering.id,
|
||||
includeSubtree: true,
|
||||
categories: ["engineering"],
|
||||
})).resolves.toEqual([
|
||||
expect.objectContaining({ name: "Review", folderPath: "engineering/reviews" }),
|
||||
]);
|
||||
await expect(svc.list(companyId, { folderId: engineering.id })).resolves.toEqual([]);
|
||||
await expect(svc.list(companyId, { folderId: engineering.id, q: "deploy" })).resolves.toEqual([
|
||||
expect.objectContaining({ name: "Deploy", folderPath: "operations" }),
|
||||
]);
|
||||
const review = (await svc.list(companyId)).find((skill) => skill.name === "Review");
|
||||
await expect(svc.getById(companyId, review!.id)).resolves.toMatchObject({
|
||||
name: "Review",
|
||||
folderPath: "engineering/reviews",
|
||||
});
|
||||
});
|
||||
|
||||
it("creates skills in same-company folders and rejects cross-company folder references", async () => {
|
||||
const companyId = randomUUID();
|
||||
const otherCompanyId = randomUUID();
|
||||
await db.insert(companies).values([
|
||||
{
|
||||
id: companyId,
|
||||
name: "Paperclip",
|
||||
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
},
|
||||
{
|
||||
id: otherCompanyId,
|
||||
name: "Other",
|
||||
issuePrefix: `T${otherCompanyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
},
|
||||
]);
|
||||
const folderSvc = folderService(db);
|
||||
const folder = await folderSvc.create(companyId, { kind: "skill", name: "Personal" });
|
||||
const otherFolder = await folderSvc.create(otherCompanyId, { kind: "skill", name: "Private" });
|
||||
|
||||
await expect(svc.createLocalSkill(companyId, {
|
||||
name: "Filed Skill",
|
||||
folderId: folder.id,
|
||||
})).resolves.toMatchObject({ folderId: folder.id });
|
||||
await expect(svc.createLocalSkill(companyId, {
|
||||
name: "Cross Company Skill",
|
||||
folderId: otherFolder.id,
|
||||
})).rejects.toMatchObject({ status: 404, message: "Skill folder not found" });
|
||||
});
|
||||
|
||||
it("resolves detail by unique skill slug for Studio deep links", async () => {
|
||||
const companyId = randomUUID();
|
||||
await db.insert(companies).values({
|
||||
@@ -2327,4 +2456,60 @@ describeEmbeddedPostgres("companySkillService.list", () => {
|
||||
const persisted = await db.select().from(companySkills).where(eq(companySkills.companyId, companyId));
|
||||
expect(persisted.filter((skill) => skill.metadata?.sourceKind === "project_scan")).toEqual([]);
|
||||
});
|
||||
|
||||
it("files new project imports without moving them back on re-import", async () => {
|
||||
const companyId = randomUUID();
|
||||
const projectId = randomUUID();
|
||||
const workspaceId = randomUUID();
|
||||
const folderSvc = folderService(db);
|
||||
const workspaceDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-skill-project-folder-"));
|
||||
cleanupDirs.add(workspaceDir);
|
||||
const skillDir = path.join(workspaceDir, "skills", "project-skill");
|
||||
const skillFile = path.join(skillDir, "SKILL.md");
|
||||
await fs.mkdir(skillDir, { recursive: true });
|
||||
await fs.writeFile(skillFile, "---\nname: Project Skill\n---\n\nInitial content.\n", "utf8");
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "Paperclip",
|
||||
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
await db.insert(projects).values({ id: projectId, companyId, name: "Skills Project" });
|
||||
await db.insert(projectWorkspaces).values({
|
||||
id: workspaceId,
|
||||
companyId,
|
||||
projectId,
|
||||
name: "Primary",
|
||||
cwd: workspaceDir,
|
||||
isPrimary: true,
|
||||
});
|
||||
|
||||
const firstImport = await svc.scanProjectWorkspaces(companyId, { projectIds: [projectId] });
|
||||
|
||||
expect(firstImport.imported).toHaveLength(1);
|
||||
const importedSkill = firstImport.imported[0]!;
|
||||
const projectFolder = await folderSvc.getFolder(companyId, importedSkill.folderId!);
|
||||
expect(projectFolder).toMatchObject({
|
||||
path: "projects/skills-project",
|
||||
systemKey: `project:${projectId}`,
|
||||
});
|
||||
|
||||
const personalFolder = await folderSvc.create(companyId, { kind: "skill", name: "Personal" });
|
||||
await folderSvc.moveItem(companyId, {
|
||||
kind: "skill",
|
||||
itemId: importedSkill.id,
|
||||
folderId: personalFolder.id,
|
||||
});
|
||||
await fs.writeFile(skillFile, "---\nname: Project Skill\n---\n\nUpdated content.\n", "utf8");
|
||||
|
||||
const reimport = await svc.scanProjectWorkspaces(companyId, { projectIds: [projectId] });
|
||||
|
||||
expect(reimport.updated).toHaveLength(1);
|
||||
expect(reimport.updated[0]).toMatchObject({
|
||||
id: importedSkill.id,
|
||||
folderId: personalFolder.id,
|
||||
markdown: expect.stringContaining("Updated content."),
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mockFolderService = vi.hoisted(() => ({
|
||||
list: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
moveFolder: vi.fn(),
|
||||
moveItem: vi.fn(),
|
||||
deleteFolder: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockLogActivity = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("../services/index.js", () => ({
|
||||
folderService: () => mockFolderService,
|
||||
logActivity: mockLogActivity,
|
||||
}));
|
||||
|
||||
async function createApp() {
|
||||
vi.resetModules();
|
||||
const [{ errorHandler }, { folderRoutes }] = await Promise.all([
|
||||
import("../middleware/index.js") as Promise<typeof import("../middleware/index.js")>,
|
||||
import("../routes/folders.js") as Promise<typeof import("../routes/folders.js")>,
|
||||
]);
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
(req as any).actor = {
|
||||
type: "board",
|
||||
userId: "user-1",
|
||||
companyIds: ["company-1"],
|
||||
source: "session",
|
||||
isInstanceAdmin: false,
|
||||
};
|
||||
next();
|
||||
});
|
||||
app.use("/api", folderRoutes({} as any));
|
||||
app.use(errorHandler);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe("folder routes", () => {
|
||||
beforeEach(() => {
|
||||
for (const mock of Object.values(mockFolderService)) mock.mockReset();
|
||||
mockLogActivity.mockReset();
|
||||
});
|
||||
|
||||
it("routes item moves to the item move handler before the folder reorder route", async () => {
|
||||
mockFolderService.moveItem.mockResolvedValue({
|
||||
kind: "routine",
|
||||
itemId: "11111111-1111-4111-8111-111111111111",
|
||||
folderId: "22222222-2222-4222-8222-222222222222",
|
||||
});
|
||||
|
||||
const app = await createApp();
|
||||
const res = await request(app)
|
||||
.post("/api/companies/company-1/folders/items/move")
|
||||
.send({
|
||||
kind: "routine",
|
||||
itemId: "11111111-1111-4111-8111-111111111111",
|
||||
folderId: "22222222-2222-4222-8222-222222222222",
|
||||
});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockFolderService.moveItem).toHaveBeenCalledWith("company-1", {
|
||||
kind: "routine",
|
||||
itemId: "11111111-1111-4111-8111-111111111111",
|
||||
folderId: "22222222-2222-4222-8222-222222222222",
|
||||
});
|
||||
expect(mockFolderService.moveFolder).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,447 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import {
|
||||
folderSlugSchema,
|
||||
} from "@paperclipai/shared";
|
||||
import {
|
||||
companies,
|
||||
companySkills,
|
||||
createDb,
|
||||
folders,
|
||||
routines,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
import { folderService } from "../services/folders.js";
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
describeEmbeddedPostgres("folder service", () => {
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
|
||||
beforeAll(async () => {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-folders-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
}, 20_000);
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(companySkills);
|
||||
await db.delete(routines);
|
||||
await db.delete(folders);
|
||||
await db.delete(companies);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
async function seedCompany() {
|
||||
const companyId = randomUUID();
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "Paperclip",
|
||||
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
defaultResponsibleUserId: "responsible-user",
|
||||
});
|
||||
return companyId;
|
||||
}
|
||||
|
||||
async function seedRoutine(companyId: string, title: string, folderId?: string | null) {
|
||||
const [routine] = await db
|
||||
.insert(routines)
|
||||
.values({
|
||||
companyId,
|
||||
title,
|
||||
folderId: folderId ?? null,
|
||||
responsibleUserId: "responsible-user",
|
||||
})
|
||||
.returning();
|
||||
return routine!;
|
||||
}
|
||||
|
||||
async function seedSkill(companyId: string, slug: string, folderId?: string | null) {
|
||||
const [skill] = await db
|
||||
.insert(companySkills)
|
||||
.values({
|
||||
companyId,
|
||||
folderId: folderId ?? null,
|
||||
key: `company/${companyId}/${slug}`,
|
||||
slug,
|
||||
name: slug,
|
||||
markdown: `# ${slug}`,
|
||||
})
|
||||
.returning();
|
||||
return skill!;
|
||||
}
|
||||
|
||||
it("creates, updates, reorders, and lists routine folders with counts", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
|
||||
const reporting = await svc.create(companyId, {
|
||||
kind: "routine",
|
||||
name: "Reporting",
|
||||
color: "green",
|
||||
});
|
||||
const cleanup = await svc.create(companyId, {
|
||||
kind: "routine",
|
||||
name: "Cleanup",
|
||||
color: null,
|
||||
});
|
||||
await seedRoutine(companyId, "Filed", reporting.id);
|
||||
await seedRoutine(companyId, "Unfiled");
|
||||
|
||||
const renamed = await svc.update(companyId, cleanup.id, { name: "Ops", color: "cyan" });
|
||||
expect(renamed).toMatchObject({ id: cleanup.id, name: "Ops", color: "cyan" });
|
||||
const cleared = await svc.update(companyId, cleanup.id, { color: null });
|
||||
expect(cleared).toMatchObject({ id: cleanup.id, color: null });
|
||||
|
||||
const movedFolder = await svc.moveFolder(companyId, reporting.id, { position: 10 });
|
||||
expect(movedFolder).toMatchObject({ id: reporting.id, position: 10 });
|
||||
|
||||
const listed = await svc.list(companyId, "routine");
|
||||
expect(listed.allCount).toBe(2);
|
||||
expect(listed.unfiledCount).toBe(1);
|
||||
expect(listed.folders).toEqual([
|
||||
expect.objectContaining({ id: cleanup.id, name: "Ops", itemCount: 0 }),
|
||||
expect.objectContaining({ id: reporting.id, name: "Reporting", itemCount: 1 }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("moves routines and skills to folders and back to virtual Unfiled", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
const routineFolder = await svc.create(companyId, { kind: "routine", name: "Reports" });
|
||||
const skillFolder = await svc.create(companyId, { kind: "skill", name: "Runtime" });
|
||||
const routine = await seedRoutine(companyId, "Daily report");
|
||||
const skill = await seedSkill(companyId, "review");
|
||||
|
||||
await expect(svc.moveItem(companyId, {
|
||||
kind: "routine",
|
||||
itemId: routine.id,
|
||||
folderId: routineFolder.id,
|
||||
})).resolves.toEqual({ kind: "routine", itemId: routine.id, folderId: routineFolder.id });
|
||||
await expect(svc.moveItem(companyId, {
|
||||
kind: "skill",
|
||||
itemId: skill.id,
|
||||
folderId: skillFolder.id,
|
||||
})).resolves.toEqual({ kind: "skill", itemId: skill.id, folderId: skillFolder.id });
|
||||
|
||||
await expect(svc.moveItem(companyId, {
|
||||
kind: "routine",
|
||||
itemId: routine.id,
|
||||
folderId: null,
|
||||
})).resolves.toEqual({ kind: "routine", itemId: routine.id, folderId: null });
|
||||
|
||||
const [updatedRoutine] = await db.select().from(routines).where(eq(routines.id, routine.id));
|
||||
const [updatedSkill] = await db.select().from(companySkills).where(eq(companySkills.id, skill.id));
|
||||
expect(updatedRoutine?.folderId).toBeNull();
|
||||
expect(updatedSkill?.folderId).toBe(skillFolder.id);
|
||||
});
|
||||
|
||||
it("rejects moving an item into a folder of the wrong kind", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
const skillFolder = await svc.create(companyId, { kind: "skill", name: "Runtime" });
|
||||
const routine = await seedRoutine(companyId, "Daily report");
|
||||
|
||||
await expect(svc.moveItem(companyId, {
|
||||
kind: "routine",
|
||||
itemId: routine.id,
|
||||
folderId: skillFolder.id,
|
||||
})).rejects.toMatchObject({
|
||||
status: 422,
|
||||
message: "Folder kind must match item kind",
|
||||
});
|
||||
});
|
||||
|
||||
it("deletes folders without deleting contents by moving items to Unfiled", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
const folder = await svc.create(companyId, { kind: "routine", name: "Reports" });
|
||||
const routine = await seedRoutine(companyId, "Daily report", folder.id);
|
||||
|
||||
const deleted = await svc.deleteFolder(companyId, folder.id);
|
||||
expect(deleted).toMatchObject({ id: folder.id, name: "Reports" });
|
||||
|
||||
const [updatedRoutine] = await db.select().from(routines).where(eq(routines.id, routine.id));
|
||||
expect(updatedRoutine?.folderId).toBeNull();
|
||||
expect(await db.select().from(folders).where(eq(folders.id, folder.id))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("computes canonical paths and updates descendant paths after rename and move", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
const root = await svc.create(companyId, { kind: "skill", name: "Engineering" });
|
||||
const child = await svc.create(companyId, { kind: "skill", parentId: root.id, name: "Code Review" });
|
||||
const destination = await svc.create(companyId, { kind: "skill", name: "Operations" });
|
||||
|
||||
expect(child).toMatchObject({ path: "engineering/code-review", depth: 2 });
|
||||
await svc.update(companyId, root.id, { name: "Product Engineering" });
|
||||
expect(await svc.getFolder(companyId, child.id)).toMatchObject({
|
||||
path: "product-engineering/code-review",
|
||||
depth: 2,
|
||||
});
|
||||
|
||||
await svc.moveFolder(companyId, child.id, { parentId: destination.id, position: 0 });
|
||||
expect(await svc.getFolder(companyId, child.id)).toMatchObject({
|
||||
parentId: destination.id,
|
||||
path: "operations/code-review",
|
||||
depth: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects invalid slugs, cycles, and folders deeper than four levels", async () => {
|
||||
expect(folderSlugSchema.safeParse("../escape").success).toBe(false);
|
||||
expect(folderSlugSchema.safeParse("Valid Slug").success).toBe(false);
|
||||
expect(folderSlugSchema.safeParse("valid-slug-2").success).toBe(true);
|
||||
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
const level1 = await svc.create(companyId, { kind: "skill", name: "Level 1" });
|
||||
const level2 = await svc.create(companyId, { kind: "skill", parentId: level1.id, name: "Level 2" });
|
||||
const level3 = await svc.create(companyId, { kind: "skill", parentId: level2.id, name: "Level 3" });
|
||||
const level4 = await svc.create(companyId, { kind: "skill", parentId: level3.id, name: "Level 4" });
|
||||
|
||||
await expect(svc.create(companyId, {
|
||||
kind: "skill",
|
||||
parentId: level4.id,
|
||||
name: "Level 5",
|
||||
})).rejects.toMatchObject({ status: 422, message: "Folder depth cannot exceed 4" });
|
||||
await expect(svc.moveFolder(companyId, level1.id, {
|
||||
parentId: level3.id,
|
||||
position: 0,
|
||||
})).rejects.toMatchObject({ status: 422, message: "A folder cannot be moved into its own subtree" });
|
||||
});
|
||||
|
||||
it("creates stable personal roots and protects bundled folders", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
const personal = await svc.ensureMyFolder(companyId, "user-1", "Ada Lovelace");
|
||||
const repeated = await svc.ensureMyFolder(companyId, "user-1", "Ada Lovelace");
|
||||
const bundled = await svc.ensureBundledCategory(companyId, "software-development");
|
||||
|
||||
expect(repeated.id).toBe(personal.id);
|
||||
expect(personal).toMatchObject({ systemKey: "my:user-1", path: "my/ada-lovelace", depth: 2 });
|
||||
expect(bundled.path).toBe("bundled/software-development");
|
||||
await expect(svc.create(companyId, {
|
||||
kind: "skill",
|
||||
parentId: bundled.id,
|
||||
name: "Nested",
|
||||
})).rejects.toMatchObject({ status: 403, message: "Bundled folders are read-only" });
|
||||
await expect(svc.update(companyId, bundled.id, { name: "Changed" })).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
|
||||
it("heals legacy bundled category names without changing folder identity", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
const legacy = await svc.ensureBundledCategory(companyId, "software-development");
|
||||
|
||||
const reconciled = await svc.ensureBundledCategory(companyId, "Software Development");
|
||||
|
||||
expect(reconciled).toMatchObject({
|
||||
id: legacy.id,
|
||||
name: "Software Development",
|
||||
path: "bundled/software-development",
|
||||
systemKey: "bundled:software-development",
|
||||
});
|
||||
});
|
||||
|
||||
it("creates reserved folders idempotently under concurrent requests", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
|
||||
const [personalA, personalB] = await Promise.all([
|
||||
svc.ensureMyFolder(companyId, "user-1", "Ada Lovelace"),
|
||||
svc.ensureMyFolder(companyId, "user-1", "Ada Lovelace"),
|
||||
]);
|
||||
const [projectA, projectB] = await Promise.all([
|
||||
svc.ensureProjectFolder(companyId, "project-1", "Core App"),
|
||||
svc.ensureProjectFolder(companyId, "project-1", "Core App"),
|
||||
]);
|
||||
const [bundledA, bundledB] = await Promise.all([
|
||||
svc.ensureBundledCategory(companyId, "software-development"),
|
||||
svc.ensureBundledCategory(companyId, "software-development"),
|
||||
]);
|
||||
|
||||
expect(personalA.id).toBe(personalB.id);
|
||||
expect(projectA.id).toBe(projectB.id);
|
||||
expect(bundledA.id).toBe(bundledB.id);
|
||||
});
|
||||
|
||||
it("reserves system skill roots from manual create, update, and move", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
|
||||
for (const slug of ["bundled", "my", "projects"]) {
|
||||
await expect(svc.create(companyId, {
|
||||
kind: "skill",
|
||||
name: slug,
|
||||
slug,
|
||||
})).rejects.toMatchObject({ status: 403, message: "Reserved skill folders are system-managed" });
|
||||
}
|
||||
|
||||
const editable = await svc.create(companyId, { kind: "skill", name: "Editable" });
|
||||
await expect(svc.update(companyId, editable.id, { slug: "bundled" })).rejects.toMatchObject({ status: 403 });
|
||||
|
||||
const parent = await svc.create(companyId, { kind: "skill", name: "Parent" });
|
||||
const nestedReserved = await svc.create(companyId, { kind: "skill", parentId: parent.id, name: "Projects" });
|
||||
await expect(svc.moveFolder(companyId, nestedReserved.id, { parentId: null, position: 0 })).rejects.toMatchObject({
|
||||
status: 403,
|
||||
message: "Reserved skill folders are system-managed",
|
||||
});
|
||||
});
|
||||
|
||||
it("allows only system helpers to create children under personal and project roots", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
const personal = await svc.ensureMyFolder(companyId, "user-1", "Ada Lovelace");
|
||||
const project = await svc.ensureProjectFolder(companyId, "project-1", "Core App");
|
||||
const myRoot = await svc.getFolder(companyId, personal.parentId!);
|
||||
const projectsRoot = await svc.getFolder(companyId, project.parentId!);
|
||||
const movable = await svc.create(companyId, { kind: "skill", name: "Movable" });
|
||||
|
||||
expect(myRoot?.systemKey).toBe("my");
|
||||
expect(projectsRoot?.systemKey).toBe("projects");
|
||||
await expect(svc.create(companyId, {
|
||||
kind: "skill",
|
||||
parentId: myRoot!.id,
|
||||
name: "Spoofed User",
|
||||
})).rejects.toMatchObject({ status: 403 });
|
||||
await expect(svc.moveFolder(companyId, movable.id, {
|
||||
parentId: projectsRoot!.id,
|
||||
position: 0,
|
||||
})).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
|
||||
it("moves squatted roots aside instead of adopting them as system containers", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
const [squattedMy, squattedProjects] = await db.insert(folders).values([
|
||||
{ companyId, kind: "skill", parentId: null, name: "Attacker My", slug: "my", position: 0 },
|
||||
{ companyId, kind: "skill", parentId: null, name: "Attacker Projects", slug: "projects", position: 1 },
|
||||
]).returning();
|
||||
|
||||
const personal = await svc.ensureMyFolder(companyId, "user-1", "Ada Lovelace");
|
||||
const project = await svc.ensureProjectFolder(companyId, "project-1", "Core App");
|
||||
const myRoot = await svc.getFolder(companyId, personal.parentId!);
|
||||
const projectsRoot = await svc.getFolder(companyId, project.parentId!);
|
||||
const repairedMy = await svc.getFolder(companyId, squattedMy!.id);
|
||||
const repairedProjects = await svc.getFolder(companyId, squattedProjects!.id);
|
||||
|
||||
expect(myRoot).toMatchObject({ slug: "my", systemKey: "my" });
|
||||
expect(projectsRoot).toMatchObject({ slug: "projects", systemKey: "projects" });
|
||||
expect(repairedMy).toMatchObject({ name: "Attacker My", systemKey: null });
|
||||
expect(repairedMy?.slug).toMatch(/^my-[a-f0-9]{8}$/);
|
||||
expect(repairedProjects).toMatchObject({ name: "Attacker Projects", systemKey: null });
|
||||
expect(repairedProjects?.slug).toMatch(/^projects-[a-f0-9]{8}$/);
|
||||
});
|
||||
|
||||
it("suffixes system children when legacy rows squat personal and project slugs", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
const initialPersonal = await svc.ensureMyFolder(companyId, "seed-user", "Seed User");
|
||||
const initialProject = await svc.ensureProjectFolder(companyId, "seed-project", "Seed Project");
|
||||
const myRootId = initialPersonal.parentId!;
|
||||
const projectsRootId = initialProject.parentId!;
|
||||
await db.insert(folders).values([
|
||||
{ companyId, kind: "skill", parentId: myRootId, name: "Ada Squat", slug: "ada-lovelace", position: 1 },
|
||||
{ companyId, kind: "skill", parentId: projectsRootId, name: "Core Squat", slug: "core-app", position: 1 },
|
||||
]);
|
||||
|
||||
const personal = await svc.ensureMyFolder(companyId, "user-12345678", "Ada Lovelace");
|
||||
const project = await svc.ensureProjectFolder(companyId, "project-12345678", "Core App");
|
||||
|
||||
expect(personal).toMatchObject({ path: "my/ada-lovelace-user-12345678", systemKey: "my:user-12345678" });
|
||||
expect(project).toMatchObject({ path: "projects/core-app-project-12345678", systemKey: "project:project-12345678" });
|
||||
});
|
||||
|
||||
it("does not adopt a legacy category row under the bundled root", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
const initialCategory = await svc.ensureBundledCategory(companyId, "initial");
|
||||
const bundledRootId = initialCategory.parentId!;
|
||||
const [squatted] = await db.insert(folders).values({
|
||||
companyId,
|
||||
kind: "skill",
|
||||
parentId: bundledRootId,
|
||||
name: "User Software Development",
|
||||
slug: "software-development",
|
||||
position: 1,
|
||||
}).returning();
|
||||
|
||||
const category = await svc.ensureBundledCategory(companyId, "software-development");
|
||||
|
||||
expect(category).toMatchObject({
|
||||
path: "bundled/software-development-bundled",
|
||||
systemKey: "bundled:software-development",
|
||||
});
|
||||
expect(await svc.getFolder(companyId, squatted!.id)).toMatchObject({
|
||||
path: "bundled/software-development",
|
||||
systemKey: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("serializes concurrent system folder ensures", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
await db.insert(folders).values({
|
||||
companyId,
|
||||
kind: "skill",
|
||||
name: "Squatted My",
|
||||
slug: "my",
|
||||
position: 0,
|
||||
});
|
||||
|
||||
const personalFolders = await Promise.all(
|
||||
Array.from({ length: 8 }, () => svc.ensureMyFolder(companyId, "user-123", "Ada Lovelace")),
|
||||
);
|
||||
|
||||
expect(new Set(personalFolders.map((folder) => folder.id)).size).toBe(1);
|
||||
const rows = await db.select().from(folders).where(eq(folders.companyId, companyId));
|
||||
expect(rows.filter((row) => row.systemKey === "my")).toHaveLength(1);
|
||||
expect(rows.filter((row) => row.systemKey === "my:user-123")).toHaveLength(1);
|
||||
expect(rows.find((row) => row.systemKey === null)).toMatchObject({ name: "Squatted My" });
|
||||
});
|
||||
|
||||
it("rechecks nested folders after waiting for the company mutation lock", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const svc = folderService(db);
|
||||
const parent = await svc.create(companyId, { kind: "routine", name: "Parent" });
|
||||
let releaseLock!: () => void;
|
||||
let markLockAcquired!: () => void;
|
||||
const lockAcquired = new Promise<void>((resolve) => { markLockAcquired = resolve; });
|
||||
const holdLock = new Promise<void>((resolve) => { releaseLock = resolve; });
|
||||
const lockKey = `paperclip:folders:${companyId}`;
|
||||
const blocker = db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))`);
|
||||
markLockAcquired();
|
||||
await holdLock;
|
||||
});
|
||||
await lockAcquired;
|
||||
|
||||
const deletion = svc.deleteFolder(companyId, parent.id);
|
||||
await db.insert(folders).values({
|
||||
companyId,
|
||||
kind: "routine",
|
||||
parentId: parent.id,
|
||||
name: "Child",
|
||||
slug: "child",
|
||||
position: 0,
|
||||
});
|
||||
releaseLock();
|
||||
await blocker;
|
||||
|
||||
await expect(deletion).rejects.toMatchObject({
|
||||
status: 409,
|
||||
message: "Move or delete nested folders first",
|
||||
});
|
||||
await expect(svc.getFolder(companyId, parent.id)).resolves.toMatchObject({ id: parent.id });
|
||||
});
|
||||
});
|
||||
@@ -30,6 +30,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"environments.ts": "/api",
|
||||
"execution-workspaces.ts": "/api",
|
||||
"file-resources.ts": "/api",
|
||||
"folders.ts": "/api",
|
||||
"goals.ts": "/api",
|
||||
"health.ts": "/api/health",
|
||||
"inbox-dismissals.ts": "/api",
|
||||
@@ -181,6 +182,10 @@ describe("openapi routes", () => {
|
||||
name: { type: "string" },
|
||||
},
|
||||
});
|
||||
expect(res.body.paths["/api/companies/{companyId}/folders"].post.responses["201"]).toBeDefined();
|
||||
expect(res.body.paths["/api/companies/{companyId}/folders/items/move"].post.summary).toBe(
|
||||
"Move an item into or out of a folder",
|
||||
);
|
||||
expect(JSON.stringify(res.body.paths["/api/tool-gateway/tools"].get)).not.toContain("sessionToken");
|
||||
expect(JSON.stringify(res.body.paths["/api/tool-gateway/tools/call"].post)).not.toContain("sessionToken");
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
documentRevisions,
|
||||
documents,
|
||||
executionWorkspaces,
|
||||
folders,
|
||||
heartbeatRuns,
|
||||
instanceSettings,
|
||||
issueInboxArchives,
|
||||
@@ -68,6 +69,7 @@ describeEmbeddedPostgres("routine service live-execution coalescing", () => {
|
||||
await db.delete(routineRuns);
|
||||
await db.delete(routineTriggers);
|
||||
await db.delete(routines);
|
||||
await db.delete(folders);
|
||||
await db.delete(routineDocuments);
|
||||
await db.delete(documents);
|
||||
await db.delete(documentRevisions);
|
||||
@@ -271,6 +273,39 @@ describeEmbeddedPostgres("routine service live-execution coalescing", () => {
|
||||
expect(allRoutines.map((entry) => entry.id)).toEqual(expect.arrayContaining([routine.id, otherRoutine.id]));
|
||||
});
|
||||
|
||||
it("does not reveal folders owned by another company", async () => {
|
||||
const { companyId, agentId, projectId, svc } = await seedFixture();
|
||||
const otherCompanyId = randomUUID();
|
||||
await db.insert(companies).values({
|
||||
id: otherCompanyId,
|
||||
name: "Other company",
|
||||
issuePrefix: `T${otherCompanyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
||||
defaultResponsibleUserId: randomUUID(),
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
const [otherFolder] = await db.insert(folders).values({
|
||||
companyId: otherCompanyId,
|
||||
kind: "routine",
|
||||
name: "Private folder",
|
||||
slug: "private-folder",
|
||||
position: 0,
|
||||
}).returning();
|
||||
|
||||
await expect(svc.create(companyId, {
|
||||
projectId,
|
||||
folderId: otherFolder!.id,
|
||||
goalId: null,
|
||||
parentIssueId: null,
|
||||
title: "cross-company folder probe",
|
||||
description: null,
|
||||
assigneeAgentId: agentId,
|
||||
priority: "medium",
|
||||
status: "active",
|
||||
concurrencyPolicy: "coalesce_if_active",
|
||||
catchUpPolicy: "skip_missed",
|
||||
}, {})).rejects.toMatchObject({ status: 404, message: "Folder not found" });
|
||||
});
|
||||
|
||||
it("defaults activity gates to always at company scope", async () => {
|
||||
const { routine } = await seedFixture();
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import { companyRoutes } from "./routes/companies.js";
|
||||
import { companySkillRoutes } from "./routes/company-skills.js";
|
||||
import { companySkillPolicyRoutes } from "./routes/company-skill-policy.js";
|
||||
import { builtInAgentRoutes } from "./routes/built-in-agents.js";
|
||||
import { folderRoutes } from "./routes/folders.js";
|
||||
import { teamsCatalogRoutes } from "./routes/teams-catalog.js";
|
||||
import { agentRoutes } from "./routes/agents.js";
|
||||
import { projectRoutes } from "./routes/projects.js";
|
||||
@@ -235,6 +236,7 @@ export async function createApp(
|
||||
api.use(openApiRoutes());
|
||||
api.use("/companies", companyRoutes(db, opts.storageService));
|
||||
api.use(llmRoutes(db));
|
||||
api.use(folderRoutes(db));
|
||||
api.use(companySkillRoutes(db));
|
||||
api.use(companySkillPolicyRoutes(db));
|
||||
api.use(builtInAgentRoutes(db));
|
||||
|
||||
@@ -38,7 +38,7 @@ import {
|
||||
listCatalogSkillsOrEmpty,
|
||||
readCatalogSkillFile,
|
||||
} from "../services/skills-catalog.js";
|
||||
import { forbidden, unauthorized } from "../errors.js";
|
||||
import { badRequest, forbidden, unauthorized } from "../errors.js";
|
||||
import { assertAuthenticated, assertCompanyAccess, getActorInfo } from "./authz.js";
|
||||
import { getTelemetryClient } from "../telemetry.js";
|
||||
import {
|
||||
@@ -115,6 +115,14 @@ export function companySkillRoutes(db: Db) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function optionalQueryBoolean(value: unknown) {
|
||||
const parsed = firstQueryString(value);
|
||||
if (parsed === undefined) return undefined;
|
||||
if (parsed === "true") return true;
|
||||
if (parsed === "false") return false;
|
||||
throw badRequest("Boolean query parameters must be true or false");
|
||||
}
|
||||
|
||||
function queryStringArray(value: unknown): string[] {
|
||||
if (typeof value === "string") return [value];
|
||||
if (Array.isArray(value)) return value.filter((entry): entry is string => typeof entry === "string");
|
||||
@@ -305,12 +313,17 @@ export function companySkillRoutes(db: Db) {
|
||||
...queryStringArray(req.query.category),
|
||||
...queryStringArray(req.query.categories),
|
||||
...queryStringArray(req.query["categories[]"]),
|
||||
...queryStringArray(req.query.tag),
|
||||
...queryStringArray(req.query.tags),
|
||||
...queryStringArray(req.query["tags[]"]),
|
||||
],
|
||||
scope: firstQueryString(req.query.scope),
|
||||
include: [
|
||||
...queryStringArray(req.query.include),
|
||||
...queryStringArray(req.query["include[]"]),
|
||||
],
|
||||
folderId: firstQueryString(req.query.folderId),
|
||||
includeSubtree: optionalQueryBoolean(req.query.includeSubtree),
|
||||
}));
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { Router } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
createFolderSchema,
|
||||
ensureMySkillFolderSchema,
|
||||
folderKindSchema,
|
||||
moveFolderItemSchema,
|
||||
moveFolderSchema,
|
||||
updateFolderSchema,
|
||||
} from "@paperclipai/shared";
|
||||
import { validate } from "../middleware/validate.js";
|
||||
import { badRequest, forbidden } from "../errors.js";
|
||||
import { folderService, logActivity } from "../services/index.js";
|
||||
import { assertCompanyAccess, getActorInfo } from "./authz.js";
|
||||
|
||||
export function folderRoutes(db: Db) {
|
||||
const router = Router();
|
||||
const svc = folderService(db);
|
||||
|
||||
function parseKind(value: unknown) {
|
||||
const result = folderKindSchema.safeParse(value);
|
||||
if (!result.success) throw badRequest("Folder kind query parameter is required");
|
||||
return result.data;
|
||||
}
|
||||
|
||||
router.get("/companies/:companyId/folders", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
res.json(await svc.list(companyId, parseKind(req.query.kind)));
|
||||
});
|
||||
|
||||
router.post("/companies/:companyId/folders", validate(createFolderSchema), async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
const created = await svc.create(companyId, req.body);
|
||||
const actor = getActorInfo(req);
|
||||
await logActivity(db, {
|
||||
companyId,
|
||||
actorType: actor.actorType,
|
||||
actorId: actor.actorId,
|
||||
agentId: actor.agentId,
|
||||
runId: actor.runId,
|
||||
action: "folder.created",
|
||||
entityType: "folder",
|
||||
entityId: created.id,
|
||||
details: { kind: created.kind, name: created.name, path: created.path, parentId: created.parentId, position: created.position },
|
||||
});
|
||||
res.status(201).json(created);
|
||||
});
|
||||
|
||||
router.post(
|
||||
"/companies/:companyId/folders/ensure-my",
|
||||
validate(ensureMySkillFolderSchema),
|
||||
async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
if (req.actor.type !== "board" || !req.actor.userId) {
|
||||
throw forbidden("A signed-in board user is required to create a personal skill folder");
|
||||
}
|
||||
const folder = await svc.ensureMyFolder(companyId, req.actor.userId, req.actor.userName ?? null, req.body.slug);
|
||||
const actor = getActorInfo(req);
|
||||
await logActivity(db, {
|
||||
companyId,
|
||||
actorType: actor.actorType,
|
||||
actorId: actor.actorId,
|
||||
agentId: actor.agentId,
|
||||
runId: actor.runId,
|
||||
action: "folder.personal_ensured",
|
||||
entityType: "folder",
|
||||
entityId: folder.id,
|
||||
details: { path: folder.path, systemKey: folder.systemKey },
|
||||
});
|
||||
res.json(folder);
|
||||
},
|
||||
);
|
||||
|
||||
router.patch("/companies/:companyId/folders/:folderId", validate(updateFolderSchema), async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const folderId = req.params.folderId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
const updated = await svc.update(companyId, folderId, req.body);
|
||||
if (!updated) {
|
||||
res.status(404).json({ error: "Folder not found" });
|
||||
return;
|
||||
}
|
||||
const actor = getActorInfo(req);
|
||||
await logActivity(db, {
|
||||
companyId,
|
||||
actorType: actor.actorType,
|
||||
actorId: actor.actorId,
|
||||
agentId: actor.agentId,
|
||||
runId: actor.runId,
|
||||
action: "folder.updated",
|
||||
entityType: "folder",
|
||||
entityId: updated.id,
|
||||
details: { kind: updated.kind, name: updated.name, path: updated.path, position: updated.position },
|
||||
});
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
router.post("/companies/:companyId/folders/items/move", validate(moveFolderItemSchema), async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
const moved = await svc.moveItem(companyId, req.body);
|
||||
const actor = getActorInfo(req);
|
||||
await logActivity(db, {
|
||||
companyId,
|
||||
actorType: actor.actorType,
|
||||
actorId: actor.actorId,
|
||||
agentId: actor.agentId,
|
||||
runId: actor.runId,
|
||||
action: "folder.item_moved",
|
||||
entityType: req.body.kind === "routine" ? "routine" : "company_skill",
|
||||
entityId: moved.itemId,
|
||||
details: { kind: moved.kind, folderId: moved.folderId },
|
||||
});
|
||||
res.json(moved);
|
||||
});
|
||||
|
||||
router.post("/companies/:companyId/folders/:folderId/move", validate(moveFolderSchema), async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const folderId = req.params.folderId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
const updated = await svc.moveFolder(companyId, folderId, req.body);
|
||||
if (!updated) {
|
||||
res.status(404).json({ error: "Folder not found" });
|
||||
return;
|
||||
}
|
||||
const actor = getActorInfo(req);
|
||||
await logActivity(db, {
|
||||
companyId,
|
||||
actorType: actor.actorType,
|
||||
actorId: actor.actorId,
|
||||
agentId: actor.agentId,
|
||||
runId: actor.runId,
|
||||
action: "folder.moved",
|
||||
entityType: "folder",
|
||||
entityId: updated.id,
|
||||
details: { kind: updated.kind, parentId: updated.parentId, path: updated.path, position: updated.position },
|
||||
});
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
router.delete("/companies/:companyId/folders/:folderId", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const folderId = req.params.folderId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
const deleted = await svc.deleteFolder(companyId, folderId);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: "Folder not found" });
|
||||
return;
|
||||
}
|
||||
const actor = getActorInfo(req);
|
||||
await logActivity(db, {
|
||||
companyId,
|
||||
actorType: actor.actorType,
|
||||
actorId: actor.actorId,
|
||||
agentId: actor.agentId,
|
||||
runId: actor.runId,
|
||||
action: "folder.deleted",
|
||||
entityType: "folder",
|
||||
entityId: deleted.id,
|
||||
details: { kind: deleted.kind, name: deleted.name },
|
||||
});
|
||||
res.json({ deleted });
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ export { companyRoutes } from "./companies.js";
|
||||
export { companySkillRoutes } from "./company-skills.js";
|
||||
export { companySkillPolicyRoutes } from "./company-skill-policy.js";
|
||||
export { builtInAgentRoutes } from "./built-in-agents.js";
|
||||
export { folderRoutes } from "./folders.js";
|
||||
export { teamsCatalogRoutes } from "./teams-catalog.js";
|
||||
export { agentRoutes } from "./agents.js";
|
||||
export { projectRoutes } from "./projects.js";
|
||||
|
||||
@@ -47,6 +47,13 @@ import {
|
||||
updateRoutineTriggerSchema,
|
||||
rotateRoutineTriggerSecretSchema,
|
||||
runRoutineSchema,
|
||||
// Folders
|
||||
createFolderSchema,
|
||||
ensureMySkillFolderSchema,
|
||||
folderKindSchema,
|
||||
moveFolderItemSchema,
|
||||
moveFolderSchema,
|
||||
updateFolderSchema,
|
||||
// Goal
|
||||
createGoalSchema,
|
||||
updateGoalSchema,
|
||||
@@ -862,6 +869,8 @@ const CREATED_OPERATIONS = new Set([
|
||||
"POST /api/companies/{companyId}/projects",
|
||||
"POST /api/projects/{id}/workspaces",
|
||||
"POST /api/companies/{companyId}/routines",
|
||||
"POST /api/companies/{companyId}/folders",
|
||||
"POST /api/companies/{companyId}/folders/ensure-my",
|
||||
"POST /api/routines/{id}/triggers",
|
||||
"POST /api/companies/{companyId}/secrets",
|
||||
"POST /api/companies/{companyId}/user-secret-definitions",
|
||||
@@ -5168,6 +5177,61 @@ for (const route of [
|
||||
});
|
||||
}
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "get",
|
||||
path: "/api/companies/{companyId}/folders",
|
||||
tags: ["folders"],
|
||||
summary: "List folders for a company item kind",
|
||||
query: z.object({ kind: folderKindSchema }),
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "post",
|
||||
path: "/api/companies/{companyId}/folders",
|
||||
tags: ["folders"],
|
||||
summary: "Create a folder",
|
||||
body: createFolderSchema,
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "post",
|
||||
path: "/api/companies/{companyId}/folders/ensure-my",
|
||||
tags: ["folders"],
|
||||
summary: "Ensure the current user's personal skill folder exists",
|
||||
body: ensureMySkillFolderSchema,
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "patch",
|
||||
path: "/api/companies/{companyId}/folders/{folderId}",
|
||||
tags: ["folders"],
|
||||
summary: "Update a folder",
|
||||
body: updateFolderSchema,
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "post",
|
||||
path: "/api/companies/{companyId}/folders/items/move",
|
||||
tags: ["folders"],
|
||||
summary: "Move an item into or out of a folder",
|
||||
body: moveFolderItemSchema,
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "post",
|
||||
path: "/api/companies/{companyId}/folders/{folderId}/move",
|
||||
tags: ["folders"],
|
||||
summary: "Move or reorder a folder",
|
||||
body: moveFolderSchema,
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "delete",
|
||||
path: "/api/companies/{companyId}/folders/{folderId}",
|
||||
tags: ["folders"],
|
||||
summary: "Delete a folder",
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "get",
|
||||
path: "/api/issues/{id}/cost-summary",
|
||||
|
||||
@@ -97,6 +97,7 @@ import { issueDocumentSelect, mapIssueDocumentRow } from "./documents.js";
|
||||
import { toIssueWorkProduct } from "./work-products.js";
|
||||
import { projectService } from "./projects.js";
|
||||
import { normalizePortablePath } from "./portable-path.js";
|
||||
import { folderService } from "./folders.js";
|
||||
import {
|
||||
copyCatalogSkillFile,
|
||||
getCatalogPackageMetadata,
|
||||
@@ -119,6 +120,7 @@ type CompanySkillListDbRow = Pick<
|
||||
CompanySkillRow,
|
||||
| "id"
|
||||
| "companyId"
|
||||
| "folderId"
|
||||
| "key"
|
||||
| "slug"
|
||||
| "name"
|
||||
@@ -151,6 +153,8 @@ type CompanySkillListRow = Pick<
|
||||
CompanySkill,
|
||||
| "id"
|
||||
| "companyId"
|
||||
| "folderId"
|
||||
| "folderPath"
|
||||
| "key"
|
||||
| "slug"
|
||||
| "name"
|
||||
@@ -213,6 +217,7 @@ type ImportedSkill = {
|
||||
type ImportedSkillPersistValues = Pick<
|
||||
CompanySkill,
|
||||
| "companyId"
|
||||
| "folderId"
|
||||
| "key"
|
||||
| "slug"
|
||||
| "name"
|
||||
@@ -376,6 +381,7 @@ function selectCompanySkillColumns() {
|
||||
return {
|
||||
id: companySkills.id,
|
||||
companyId: companySkills.companyId,
|
||||
folderId: companySkills.folderId,
|
||||
key: companySkills.key,
|
||||
slug: companySkills.slug,
|
||||
name: companySkills.name,
|
||||
@@ -1208,6 +1214,26 @@ function isPaperclipBundledSkillKey(key: string) {
|
||||
return key.startsWith("paperclipai/paperclip/");
|
||||
}
|
||||
|
||||
function paperclipBundledFolderCategory(key: string, metadata?: unknown) {
|
||||
const keyParts = key.split("/");
|
||||
if (keyParts[0] === "paperclipai" && keyParts[1] === "bundled" && keyParts[2]) {
|
||||
return keyParts[2];
|
||||
}
|
||||
if (isPaperclipBundledSkillKey(key)) return "paperclip-core";
|
||||
if (isPlainRecord(metadata) && asString(metadata.sourceKind) === "paperclip_bundled") {
|
||||
return "paperclip-core";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function bundledFolderLabel(category: string) {
|
||||
return category
|
||||
.split(/[-_\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function stripDerivedPaperclipBundledMetadata(key: string, metadata: unknown): unknown {
|
||||
if (metadata === null || metadata === undefined) return {};
|
||||
const comparable = stableJsonComparable(metadata);
|
||||
@@ -1239,6 +1265,7 @@ function importedSkillPersistValuesMatchExisting(
|
||||
values: ImportedSkillPersistValues,
|
||||
) {
|
||||
return existing.companyId === values.companyId
|
||||
&& existing.folderId === values.folderId
|
||||
&& existing.key === values.key
|
||||
&& existing.slug === values.slug
|
||||
&& existing.name === values.name
|
||||
@@ -2643,6 +2670,8 @@ function toCompanySkillListItem(skill: CompanySkillListRow, attachedAgentCount:
|
||||
return {
|
||||
id: skill.id,
|
||||
companyId: skill.companyId,
|
||||
folderId: skill.folderId,
|
||||
folderPath: skill.folderPath ?? null,
|
||||
key: skill.key,
|
||||
slug: skill.slug,
|
||||
name: skill.name,
|
||||
@@ -2743,6 +2772,7 @@ async function listLastEditorsBySkillId(
|
||||
}
|
||||
|
||||
export function companySkillService(db: Db) {
|
||||
const folderSvc = folderService(db);
|
||||
const agents = agentService(db);
|
||||
const projects = projectService(db);
|
||||
|
||||
@@ -2798,6 +2828,39 @@ export function companySkillService(db: Db) {
|
||||
return [];
|
||||
}
|
||||
|
||||
async function reconcilePaperclipSkillFolders(companyId: string) {
|
||||
const shippedSkills = await db
|
||||
.select({
|
||||
id: companySkills.id,
|
||||
key: companySkills.key,
|
||||
folderId: companySkills.folderId,
|
||||
metadata: companySkills.metadata,
|
||||
})
|
||||
.from(companySkills)
|
||||
.where(eq(companySkills.companyId, companyId))
|
||||
.then((rows) => rows.flatMap((skill) => {
|
||||
const category = paperclipBundledFolderCategory(skill.key, skill.metadata);
|
||||
return category ? [{ ...skill, category }] : [];
|
||||
}));
|
||||
const foldersByCategory = new Map<string, Awaited<ReturnType<typeof folderSvc.ensureBundledCategory>>>();
|
||||
for (const skill of shippedSkills) {
|
||||
let folder = foldersByCategory.get(skill.category);
|
||||
if (!folder) {
|
||||
folder = await folderSvc.ensureBundledCategory(companyId, bundledFolderLabel(skill.category));
|
||||
foldersByCategory.set(skill.category, folder);
|
||||
}
|
||||
if (skill.folderId === folder.id) continue;
|
||||
await db
|
||||
.update(companySkills)
|
||||
.set({ folderId: folder.id, updatedAt: new Date() })
|
||||
.where(and(eq(companySkills.companyId, companyId), eq(companySkills.id, skill.id)));
|
||||
}
|
||||
await folderSvc.pruneEmptyBundledCategories(
|
||||
companyId,
|
||||
Array.from(foldersByCategory.keys(), bundledFolderLabel),
|
||||
);
|
||||
}
|
||||
|
||||
async function reconcileLocalPathSkillSources(companyId: string) {
|
||||
const rows = await db
|
||||
.select({
|
||||
@@ -2889,6 +2952,7 @@ export function companySkillService(db: Db) {
|
||||
throw notFound("Company not found");
|
||||
}
|
||||
await ensureBundledSkills(companyId);
|
||||
await reconcilePaperclipSkillFolders(companyId);
|
||||
await reconcileLocalPathSkillSources(companyId);
|
||||
})();
|
||||
|
||||
@@ -2904,10 +2968,11 @@ export function companySkillService(db: Db) {
|
||||
|
||||
async function list(companyId: string, query: CompanySkillListQuery = {}): Promise<CompanySkillListItem[]> {
|
||||
await ensureSkillInventoryCurrent(companyId);
|
||||
const rows = await db
|
||||
const [dbRows, folderListing] = await Promise.all([db
|
||||
.select({
|
||||
id: companySkills.id,
|
||||
companyId: companySkills.companyId,
|
||||
folderId: companySkills.folderId,
|
||||
key: companySkills.key,
|
||||
slug: companySkills.slug,
|
||||
name: companySkills.name,
|
||||
@@ -2939,7 +3004,21 @@ export function companySkillService(db: Db) {
|
||||
.from(companySkills)
|
||||
.where(eq(companySkills.companyId, companyId))
|
||||
.orderBy(asc(companySkills.name), asc(companySkills.key))
|
||||
.then((entries) => entries.map((entry) => toCompanySkillListRow(entry as CompanySkillListDbRow)));
|
||||
.then((entries) => entries.map((entry) => toCompanySkillListRow(entry as CompanySkillListDbRow))),
|
||||
folderSvc.list(companyId, "skill"),
|
||||
]);
|
||||
const folderPaths = new Map(folderListing.folders.map((folder) => [folder.id, folder.path]));
|
||||
const rows = dbRows.map((skill) => ({
|
||||
...skill,
|
||||
folderPath: skill.folderId ? folderPaths.get(skill.folderId) ?? null : null,
|
||||
}));
|
||||
let selectedFolderIds: Set<string> | null = null;
|
||||
if (query.folderId) {
|
||||
await folderSvc.validateSkillFolder(companyId, query.folderId, { allowBundled: true });
|
||||
selectedFolderIds = query.includeSubtree
|
||||
? await folderSvc.descendantIds(companyId, "skill", query.folderId)
|
||||
: new Set([query.folderId]);
|
||||
}
|
||||
const agentRows = await agents.list(companyId);
|
||||
const q = query.q?.trim().toLowerCase() ?? "";
|
||||
const categories = new Set(
|
||||
@@ -2950,6 +3029,7 @@ export function companySkillService(db: Db) {
|
||||
);
|
||||
const filtered = rows.filter((skill) => {
|
||||
if (query.scope && skill.sharingScope !== query.scope) return false;
|
||||
if (!q && selectedFolderIds && (!skill.folderId || !selectedFolderIds.has(skill.folderId))) return false;
|
||||
if (categories.size > 0 && !skill.categories.some((category) => categories.has(categoryLookupKey(category)))) return false;
|
||||
if (q) {
|
||||
const haystack = [
|
||||
@@ -3032,7 +3112,7 @@ export function companySkillService(db: Db) {
|
||||
.from(companySkills)
|
||||
.where(and(eq(companySkills.companyId, companyId), eq(companySkills.id, id)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
return row ? toCompanySkill(row) : null;
|
||||
return row ? enrichFolderPath(companyId, toCompanySkill(row)) : null;
|
||||
}
|
||||
|
||||
async function getByKey(companyId: string, key: string) {
|
||||
@@ -3041,7 +3121,7 @@ export function companySkillService(db: Db) {
|
||||
.from(companySkills)
|
||||
.where(and(eq(companySkills.companyId, companyId), eq(companySkills.key, key)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
return row ? toCompanySkill(row) : null;
|
||||
return row ? enrichFolderPath(companyId, toCompanySkill(row)) : null;
|
||||
}
|
||||
|
||||
async function getBySlugIfUnique(companyId: string, slug: string) {
|
||||
@@ -3049,7 +3129,13 @@ export function companySkillService(db: Db) {
|
||||
.select(selectCompanySkillColumns())
|
||||
.from(companySkills)
|
||||
.where(and(eq(companySkills.companyId, companyId), eq(companySkills.slug, slug)));
|
||||
return rows.length === 1 ? toCompanySkill(rows[0]!) : null;
|
||||
return rows.length === 1 ? enrichFolderPath(companyId, toCompanySkill(rows[0]!)) : null;
|
||||
}
|
||||
|
||||
async function enrichFolderPath(companyId: string, skill: CompanySkill): Promise<CompanySkill> {
|
||||
if (!skill.folderId) return { ...skill, folderPath: null };
|
||||
const folder = await folderSvc.getFolder(companyId, skill.folderId);
|
||||
return { ...skill, folderPath: folder?.kind === "skill" ? folder.path : null };
|
||||
}
|
||||
|
||||
async function getByRouteRef(companyId: string, ref: string) {
|
||||
@@ -3927,6 +4013,7 @@ export function companySkillService(db: Db) {
|
||||
input: CompanySkillCreateRequest,
|
||||
actor: SkillActor | null = null,
|
||||
): Promise<CompanySkill> {
|
||||
if (input.folderId) await folderSvc.validateSkillFolder(companyId, input.folderId);
|
||||
const slug = normalizeSkillSlug(input.slug ?? input.name) ?? "skill";
|
||||
const key = `company/${companyId}/${slug}`;
|
||||
const existing = await getByKey(companyId, key);
|
||||
@@ -4013,6 +4100,7 @@ export function companySkillService(db: Db) {
|
||||
authorName: normalizeStoreText(input.authorName, 200) ?? forkSource?.authorName ?? created.authorName,
|
||||
homepageUrl: normalizeStoreText(input.homepageUrl, 2000) ?? forkSource?.homepageUrl ?? created.homepageUrl,
|
||||
categories: input.categories ? normalizeCategoryList(input.categories) : forkSource?.categories ?? created.categories,
|
||||
folderId: input.folderId ?? null,
|
||||
sharingScope,
|
||||
forkedFromSkillId: forkSource?.id ?? null,
|
||||
forkedFromCompanyId: forkSource?.companyId ?? null,
|
||||
@@ -4557,6 +4645,15 @@ export function companySkillService(db: Db) {
|
||||
existingSkillId: existingBySource.id,
|
||||
reason: "This skill is already installed from the same path.",
|
||||
});
|
||||
if (mode === "preview" || !selected) continue;
|
||||
const persisted = (await upsertImportedSkills(companyId, [{
|
||||
...nextSkill,
|
||||
key: existingBySource.key,
|
||||
slug: existingBySource.slug,
|
||||
}]))[0];
|
||||
if (!persisted) continue;
|
||||
updated.push(persisted);
|
||||
upsertAcceptedSkill(persisted);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -5050,6 +5147,10 @@ export function companySkillService(db: Db) {
|
||||
}
|
||||
const markdown = await fs.readFile(path.join(originSnapshotLocator, catalogSkill.entrypoint), "utf8");
|
||||
const metadata = buildCatalogSkillMetadata(catalogSkill, existingByKey, originSnapshotLocator);
|
||||
const bundledCategory = paperclipBundledFolderCategory(catalogSkill.key, metadata);
|
||||
const bundledFolder = bundledCategory
|
||||
? await folderSvc.ensureBundledCategory(companyId, bundledFolderLabel(bundledCategory))
|
||||
: null;
|
||||
const parsed = parseFrontmatterMarkdown(markdown);
|
||||
const storeMetadata = readSkillStoreMetadata(parsed.frontmatter, {
|
||||
...metadata,
|
||||
@@ -5057,6 +5158,7 @@ export function companySkillService(db: Db) {
|
||||
});
|
||||
const values = {
|
||||
companyId,
|
||||
folderId: bundledFolder?.id ?? existingByKey?.folderId ?? null,
|
||||
key: catalogSkill.key,
|
||||
slug,
|
||||
name: catalogSkill.name,
|
||||
@@ -5446,8 +5548,18 @@ export function companySkillService(db: Db) {
|
||||
};
|
||||
const parsed = parseFrontmatterMarkdown(skill.markdown);
|
||||
const storeMetadata = readSkillStoreMetadata(parsed.frontmatter, metadata);
|
||||
const bundledCategory = paperclipBundledFolderCategory(skill.key, incomingMeta);
|
||||
const bundledFolder = bundledCategory
|
||||
? await folderSvc.ensureBundledCategory(companyId, bundledFolderLabel(bundledCategory))
|
||||
: null;
|
||||
const projectId = asString(incomingMeta.projectId);
|
||||
const projectName = asString(incomingMeta.projectName);
|
||||
const projectFolder = !existing && incomingKind === "project_scan" && projectId && projectName
|
||||
? await folderSvc.ensureProjectFolder(companyId, projectId, projectName)
|
||||
: null;
|
||||
const values: ImportedSkillPersistValues = {
|
||||
companyId,
|
||||
folderId: bundledFolder?.id ?? projectFolder?.id ?? existing?.folderId ?? null,
|
||||
key: skill.key,
|
||||
slug: skill.slug,
|
||||
name: skill.name,
|
||||
|
||||
@@ -0,0 +1,619 @@
|
||||
import { and, asc, eq, max, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { companySkills, folders, routines } from "@paperclipai/db";
|
||||
import type {
|
||||
CreateFolder,
|
||||
Folder,
|
||||
FolderKind,
|
||||
FolderListResult,
|
||||
MoveFolder,
|
||||
MoveFolderItem,
|
||||
UpdateFolder,
|
||||
} from "@paperclipai/shared";
|
||||
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
|
||||
|
||||
const MAX_FOLDER_DEPTH = 4;
|
||||
const RESERVED_ROOT_SLUGS = new Set(["bundled", "my", "projects"]);
|
||||
const RESERVED_CHILD_ROOT_SYSTEM_KEYS = new Set(["my", "projects"]);
|
||||
|
||||
type FolderRow = typeof folders.$inferSelect;
|
||||
|
||||
function isPostgresError(error: unknown, code: string) {
|
||||
return typeof error === "object" && error !== null && "code" in error && error.code === code;
|
||||
}
|
||||
|
||||
function normalizeName(name: string) {
|
||||
return name.trim();
|
||||
}
|
||||
|
||||
function normalizeColor(color: string | null | undefined) {
|
||||
if (color === undefined) return undefined;
|
||||
const trimmed = color?.trim() ?? "";
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
export function normalizeFolderSlug(value: string) {
|
||||
const slug = value
|
||||
.normalize("NFKD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.replace(/-+/g, "-");
|
||||
return slug || "folder";
|
||||
}
|
||||
|
||||
function buildFolderViews(rows: FolderRow[]) {
|
||||
const byId = new Map(rows.map((row) => [row.id, row]));
|
||||
const views = new Map<string, Folder>();
|
||||
const visiting = new Set<string>();
|
||||
|
||||
function resolve(row: FolderRow): Folder {
|
||||
const existing = views.get(row.id);
|
||||
if (existing) return existing;
|
||||
if (visiting.has(row.id)) throw unprocessable("Folder hierarchy contains a cycle");
|
||||
visiting.add(row.id);
|
||||
const parent = row.parentId ? byId.get(row.parentId) : null;
|
||||
if (row.parentId && !parent) throw unprocessable("Folder hierarchy contains an invalid parent");
|
||||
const parentView = parent ? resolve(parent) : null;
|
||||
const view: Folder = {
|
||||
...row,
|
||||
parentId: row.parentId ?? null,
|
||||
systemKey: row.systemKey ?? null,
|
||||
color: row.color ?? null,
|
||||
path: parentView ? `${parentView.path}/${row.slug}` : row.slug,
|
||||
depth: (parentView?.depth ?? 0) + 1,
|
||||
};
|
||||
visiting.delete(row.id);
|
||||
views.set(row.id, view);
|
||||
return view;
|
||||
}
|
||||
|
||||
for (const row of rows) resolve(row);
|
||||
return views;
|
||||
}
|
||||
|
||||
export function folderService(db: Db, mutationLockHeld = false) {
|
||||
async function withCompanyFolderLock<T>(companyId: string, operation: (lockedDb: Db) => Promise<T>) {
|
||||
if (mutationLockHeld) return operation(db);
|
||||
return db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`paperclip:folders:${companyId}`}, 0))`);
|
||||
return operation(tx as unknown as Db);
|
||||
});
|
||||
}
|
||||
|
||||
async function getRows(companyId: string, kind: FolderKind) {
|
||||
return db
|
||||
.select()
|
||||
.from(folders)
|
||||
.where(and(eq(folders.companyId, companyId), eq(folders.kind, kind)))
|
||||
.orderBy(asc(folders.position), asc(folders.name), asc(folders.id));
|
||||
}
|
||||
|
||||
async function getFolderRow(companyId: string, folderId: string) {
|
||||
return db
|
||||
.select()
|
||||
.from(folders)
|
||||
.where(and(eq(folders.companyId, companyId), eq(folders.id, folderId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
}
|
||||
|
||||
async function getFolder(companyId: string, folderId: string) {
|
||||
const row = await getFolderRow(companyId, folderId);
|
||||
if (!row) return null;
|
||||
const views = buildFolderViews(await getRows(companyId, row.kind));
|
||||
return views.get(row.id) ?? null;
|
||||
}
|
||||
|
||||
async function assertNoSlugConflict(
|
||||
companyId: string,
|
||||
kind: FolderKind,
|
||||
parentId: string | null,
|
||||
slug: string,
|
||||
excludeFolderId?: string,
|
||||
) {
|
||||
const existing = await db
|
||||
.select({ id: folders.id })
|
||||
.from(folders)
|
||||
.where(and(
|
||||
eq(folders.companyId, companyId),
|
||||
eq(folders.kind, kind),
|
||||
parentId === null ? sql`${folders.parentId} is null` : eq(folders.parentId, parentId),
|
||||
eq(folders.slug, slug),
|
||||
))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (existing && existing.id !== excludeFolderId) {
|
||||
throw conflict("Folder slug already exists under this parent");
|
||||
}
|
||||
}
|
||||
|
||||
async function nextPosition(companyId: string, kind: FolderKind, parentId: string | null) {
|
||||
const row = await db
|
||||
.select({ value: max(folders.position) })
|
||||
.from(folders)
|
||||
.where(and(
|
||||
eq(folders.companyId, companyId),
|
||||
eq(folders.kind, kind),
|
||||
parentId === null ? sql`${folders.parentId} is null` : eq(folders.parentId, parentId),
|
||||
))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
return Number(row?.value ?? -1) + 1;
|
||||
}
|
||||
|
||||
async function routineCounts(companyId: string) {
|
||||
return db
|
||||
.select({ folderId: routines.folderId, count: sql<number>`count(*)::int` })
|
||||
.from(routines)
|
||||
.where(eq(routines.companyId, companyId))
|
||||
.groupBy(routines.folderId);
|
||||
}
|
||||
|
||||
async function skillCounts(companyId: string) {
|
||||
return db
|
||||
.select({ folderId: companySkills.folderId, count: sql<number>`count(*)::int` })
|
||||
.from(companySkills)
|
||||
.where(eq(companySkills.companyId, companyId))
|
||||
.groupBy(companySkills.folderId);
|
||||
}
|
||||
|
||||
async function list(companyId: string, kind: FolderKind): Promise<FolderListResult> {
|
||||
const [folderRows, countRows] = await Promise.all([
|
||||
getRows(companyId, kind),
|
||||
kind === "routine" ? routineCounts(companyId) : skillCounts(companyId),
|
||||
]);
|
||||
const views = buildFolderViews(folderRows);
|
||||
const countsByFolderId = new Map<string | null, number>();
|
||||
for (const row of countRows) countsByFolderId.set(row.folderId ?? null, Number(row.count ?? 0));
|
||||
return {
|
||||
kind,
|
||||
folders: folderRows.map((row) => ({
|
||||
...views.get(row.id)!,
|
||||
itemCount: countsByFolderId.get(row.id) ?? 0,
|
||||
})),
|
||||
allCount: Array.from(countsByFolderId.values()).reduce((sum, count) => sum + count, 0),
|
||||
unfiledCount: countsByFolderId.get(null) ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
function isReservedRootSlug(kind: FolderKind, parentId: string | null, slug: string) {
|
||||
return kind === "skill" && parentId === null && RESERVED_ROOT_SLUGS.has(slug);
|
||||
}
|
||||
|
||||
async function isBundledFolder(companyId: string, folderId: string) {
|
||||
let current = await getFolder(companyId, folderId);
|
||||
const visited = new Set<string>();
|
||||
while (current) {
|
||||
if (current.systemKey === "bundled") return true;
|
||||
if (!current.parentId || visited.has(current.id)) return false;
|
||||
visited.add(current.id);
|
||||
current = await getFolder(companyId, current.parentId);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function assertMutableFolder(companyId: string, folder: Folder) {
|
||||
if (folder.systemKey || await isBundledFolder(companyId, folder.id)) {
|
||||
throw forbidden("System-managed folders cannot be changed");
|
||||
}
|
||||
}
|
||||
|
||||
async function validateParent(companyId: string, kind: FolderKind, parentId: string | null) {
|
||||
if (!parentId) return null;
|
||||
const parent = await getFolder(companyId, parentId);
|
||||
if (!parent || parent.kind !== kind) throw notFound("Parent folder not found");
|
||||
if (await isBundledFolder(companyId, parent.id)) throw forbidden("Bundled folders are read-only");
|
||||
if (
|
||||
parent.kind === "skill"
|
||||
&& parent.parentId === null
|
||||
&& (RESERVED_CHILD_ROOT_SYSTEM_KEYS.has(parent.systemKey ?? "") || RESERVED_CHILD_ROOT_SYSTEM_KEYS.has(parent.slug))
|
||||
) {
|
||||
throw forbidden("Reserved skill folders are system-managed");
|
||||
}
|
||||
return parent;
|
||||
}
|
||||
|
||||
async function create(companyId: string, input: CreateFolder): Promise<Folder> {
|
||||
if (!mutationLockHeld) {
|
||||
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).create(companyId, input));
|
||||
}
|
||||
const parentId = input.parentId ?? null;
|
||||
const parent = await validateParent(companyId, input.kind, parentId);
|
||||
if ((parent?.depth ?? 0) + 1 > MAX_FOLDER_DEPTH) {
|
||||
throw unprocessable(`Folder depth cannot exceed ${MAX_FOLDER_DEPTH}`);
|
||||
}
|
||||
const name = normalizeName(input.name);
|
||||
const slug = input.slug ?? normalizeFolderSlug(name);
|
||||
if (isReservedRootSlug(input.kind, parentId, slug)) {
|
||||
throw forbidden("Reserved skill folders are system-managed");
|
||||
}
|
||||
await assertNoSlugConflict(companyId, input.kind, parentId, slug);
|
||||
const position = input.position ?? await nextPosition(companyId, input.kind, parentId);
|
||||
let row: FolderRow;
|
||||
try {
|
||||
row = await db
|
||||
.insert(folders)
|
||||
.values({ companyId, kind: input.kind, parentId, name, slug, color: normalizeColor(input.color) ?? null, position })
|
||||
.returning()
|
||||
.then((rows) => rows[0]!);
|
||||
} catch (error) {
|
||||
if (isPostgresError(error, "23505")) throw conflict("Folder slug already exists under this parent");
|
||||
throw error;
|
||||
}
|
||||
return (await getFolder(companyId, row.id))!;
|
||||
}
|
||||
|
||||
async function update(companyId: string, folderId: string, patch: UpdateFolder): Promise<Folder | null> {
|
||||
if (!mutationLockHeld) {
|
||||
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).update(companyId, folderId, patch));
|
||||
}
|
||||
const existing = await getFolder(companyId, folderId);
|
||||
if (!existing) return null;
|
||||
await assertMutableFolder(companyId, existing);
|
||||
const name = patch.name === undefined ? existing.name : normalizeName(patch.name);
|
||||
const slug = patch.slug ?? (patch.name === undefined ? existing.slug : normalizeFolderSlug(name));
|
||||
if (isReservedRootSlug(existing.kind, existing.parentId, slug)) {
|
||||
throw forbidden("Reserved skill folders are system-managed");
|
||||
}
|
||||
await assertNoSlugConflict(companyId, existing.kind, existing.parentId, slug, existing.id);
|
||||
try {
|
||||
await db
|
||||
.update(folders)
|
||||
.set({
|
||||
name,
|
||||
slug,
|
||||
color: patch.color === undefined ? existing.color : normalizeColor(patch.color),
|
||||
position: patch.position ?? existing.position,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(and(eq(folders.companyId, companyId), eq(folders.id, folderId)));
|
||||
} catch (error) {
|
||||
if (isPostgresError(error, "23505")) throw conflict("Folder slug already exists under this parent");
|
||||
throw error;
|
||||
}
|
||||
return getFolder(companyId, folderId);
|
||||
}
|
||||
|
||||
function descendantIdsFromRows(rows: FolderRow[], folderId: string) {
|
||||
if (!rows.some((row) => row.id === folderId)) throw notFound("Folder not found");
|
||||
const children = new Map<string, string[]>();
|
||||
for (const row of rows) {
|
||||
if (!row.parentId) continue;
|
||||
children.set(row.parentId, [...(children.get(row.parentId) ?? []), row.id]);
|
||||
}
|
||||
const result = new Set([folderId]);
|
||||
const queue = [folderId];
|
||||
while (queue.length > 0) {
|
||||
const current = queue.shift()!;
|
||||
for (const childId of children.get(current) ?? []) {
|
||||
if (result.has(childId)) throw unprocessable("Folder hierarchy contains a cycle");
|
||||
result.add(childId);
|
||||
queue.push(childId);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function descendantIds(companyId: string, kind: FolderKind, folderId: string) {
|
||||
return descendantIdsFromRows(await getRows(companyId, kind), folderId);
|
||||
}
|
||||
|
||||
async function moveFolder(companyId: string, folderId: string, input: MoveFolder): Promise<Folder | null> {
|
||||
if (!mutationLockHeld) {
|
||||
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).moveFolder(companyId, folderId, input));
|
||||
}
|
||||
const existing = await getFolder(companyId, folderId);
|
||||
if (!existing) return null;
|
||||
await assertMutableFolder(companyId, existing);
|
||||
const parentId = input.parentId === undefined ? existing.parentId : input.parentId;
|
||||
if (parentId === existing.id) throw unprocessable("A folder cannot be its own parent");
|
||||
const rows = await getRows(companyId, existing.kind);
|
||||
const descendants = descendantIdsFromRows(rows, existing.id);
|
||||
if (parentId && descendants.has(parentId)) throw unprocessable("A folder cannot be moved into its own subtree");
|
||||
const parent = await validateParent(companyId, existing.kind, parentId);
|
||||
const views = buildFolderViews(rows);
|
||||
const relativeDepth = Math.max(...Array.from(descendants).map((id) => views.get(id)!.depth - existing.depth + 1));
|
||||
if ((parent?.depth ?? 0) + relativeDepth > MAX_FOLDER_DEPTH) {
|
||||
throw unprocessable(`Folder depth cannot exceed ${MAX_FOLDER_DEPTH}`);
|
||||
}
|
||||
if (isReservedRootSlug(existing.kind, parentId, existing.slug)) {
|
||||
throw forbidden("Reserved skill folders are system-managed");
|
||||
}
|
||||
await assertNoSlugConflict(companyId, existing.kind, parentId, existing.slug, existing.id);
|
||||
try {
|
||||
await db
|
||||
.update(folders)
|
||||
.set({ parentId, position: input.position, updatedAt: new Date() })
|
||||
.where(and(eq(folders.companyId, companyId), eq(folders.id, folderId)));
|
||||
} catch (error) {
|
||||
if (isPostgresError(error, "23505")) throw conflict("Folder slug already exists under this parent");
|
||||
if (isPostgresError(error, "23503")) throw conflict("Parent folder changed during move");
|
||||
throw error;
|
||||
}
|
||||
return getFolder(companyId, folderId);
|
||||
}
|
||||
|
||||
async function deleteFolder(companyId: string, folderId: string): Promise<Folder | null> {
|
||||
if (!mutationLockHeld) {
|
||||
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).deleteFolder(companyId, folderId));
|
||||
}
|
||||
const existing = await getFolder(companyId, folderId);
|
||||
if (!existing) return null;
|
||||
await assertMutableFolder(companyId, existing);
|
||||
const child = await db
|
||||
.select({ id: folders.id })
|
||||
.from(folders)
|
||||
.where(and(eq(folders.companyId, companyId), eq(folders.parentId, folderId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (child) throw conflict("Move or delete nested folders first");
|
||||
try {
|
||||
await db.delete(folders).where(and(eq(folders.companyId, companyId), eq(folders.id, folderId)));
|
||||
} catch (error) {
|
||||
if (isPostgresError(error, "23503")) throw conflict("Move or delete nested folders first");
|
||||
throw error;
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
async function validateSkillFolder(companyId: string, folderId: string, options?: { allowBundled?: boolean }) {
|
||||
const folder = await getFolder(companyId, folderId);
|
||||
if (!folder || folder.kind !== "skill") throw notFound("Skill folder not found");
|
||||
if (!options?.allowBundled && await isBundledFolder(companyId, folder.id)) {
|
||||
throw forbidden("Bundled folders are read-only");
|
||||
}
|
||||
return folder;
|
||||
}
|
||||
|
||||
async function moveItem(companyId: string, input: MoveFolderItem) {
|
||||
if (input.folderId) {
|
||||
const target = await getFolder(companyId, input.folderId);
|
||||
if (!target) throw notFound("Folder not found");
|
||||
if (target.kind !== input.kind) throw unprocessable("Folder kind must match item kind");
|
||||
if (await isBundledFolder(companyId, target.id)) throw forbidden("Bundled folders are read-only");
|
||||
}
|
||||
if (input.kind === "routine") {
|
||||
const row = await db
|
||||
.update(routines)
|
||||
.set({ folderId: input.folderId ?? null, updatedAt: new Date() })
|
||||
.where(and(eq(routines.companyId, companyId), eq(routines.id, input.itemId)))
|
||||
.returning({ id: routines.id, folderId: routines.folderId })
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!row) throw notFound("Routine not found");
|
||||
return { kind: input.kind, itemId: row.id, folderId: row.folderId ?? null };
|
||||
}
|
||||
const existing = await db
|
||||
.select({ id: companySkills.id, folderId: companySkills.folderId })
|
||||
.from(companySkills)
|
||||
.where(and(eq(companySkills.companyId, companyId), eq(companySkills.id, input.itemId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!existing) throw notFound("Skill not found");
|
||||
if (existing.folderId && await isBundledFolder(companyId, existing.folderId)) {
|
||||
throw forbidden("Bundled skills cannot be moved");
|
||||
}
|
||||
const row = await db
|
||||
.update(companySkills)
|
||||
.set({ folderId: input.folderId ?? null, updatedAt: new Date() })
|
||||
.where(and(eq(companySkills.companyId, companyId), eq(companySkills.id, input.itemId)))
|
||||
.returning({ id: companySkills.id, folderId: companySkills.folderId })
|
||||
.then((rows) => rows[0]!);
|
||||
return { kind: input.kind, itemId: row.id, folderId: row.folderId ?? null };
|
||||
}
|
||||
|
||||
async function uniqueSiblingSlug(companyId: string, parentId: string | null, baseSlug: string, stableSuffix: string) {
|
||||
const siblingSlugs = new Set(await db
|
||||
.select({ slug: folders.slug })
|
||||
.from(folders)
|
||||
.where(and(
|
||||
eq(folders.companyId, companyId),
|
||||
eq(folders.kind, "skill"),
|
||||
parentId === null ? sql`${folders.parentId} is null` : eq(folders.parentId, parentId),
|
||||
))
|
||||
.then((rows) => rows.map((row) => row.slug)));
|
||||
if (!siblingSlugs.has(baseSlug)) return baseSlug;
|
||||
const suffix = normalizeFolderSlug(stableSuffix).slice(0, 24);
|
||||
let candidate = `${baseSlug}-${suffix}`;
|
||||
let duplicateNumber = 2;
|
||||
while (siblingSlugs.has(candidate)) {
|
||||
candidate = `${baseSlug}-${suffix}-${duplicateNumber}`;
|
||||
duplicateNumber += 1;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
async function findSystemFolder(companyId: string, systemKey: string) {
|
||||
return db
|
||||
.select()
|
||||
.from(folders)
|
||||
.where(and(
|
||||
eq(folders.companyId, companyId),
|
||||
eq(folders.kind, "skill"),
|
||||
eq(folders.systemKey, systemKey),
|
||||
))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
}
|
||||
|
||||
async function insertSystemFolder(input: {
|
||||
companyId: string;
|
||||
parentId: string | null;
|
||||
name: string;
|
||||
slug: string;
|
||||
systemKey: string;
|
||||
}) {
|
||||
const inserted = await db
|
||||
.insert(folders)
|
||||
.values({
|
||||
companyId: input.companyId,
|
||||
kind: "skill",
|
||||
parentId: input.parentId,
|
||||
name: input.name,
|
||||
slug: input.slug,
|
||||
systemKey: input.systemKey,
|
||||
position: await nextPosition(input.companyId, "skill", input.parentId),
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning({ id: folders.id })
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (inserted) return (await getFolder(input.companyId, inserted.id))!;
|
||||
const existing = await findSystemFolder(input.companyId, input.systemKey);
|
||||
return existing ? (await getFolder(input.companyId, existing.id))! : null;
|
||||
}
|
||||
|
||||
async function ensureContainer(companyId: string, slug: "bundled" | "my" | "projects", name: string) {
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
const existingSystem = await findSystemFolder(companyId, slug);
|
||||
if (existingSystem) return (await getFolder(companyId, existingSystem.id))!;
|
||||
const squatted = await db
|
||||
.select({ id: folders.id })
|
||||
.from(folders)
|
||||
.where(and(
|
||||
eq(folders.companyId, companyId),
|
||||
eq(folders.kind, "skill"),
|
||||
sql`${folders.parentId} is null`,
|
||||
eq(folders.slug, slug),
|
||||
))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (squatted) {
|
||||
await db
|
||||
.update(folders)
|
||||
.set({ slug: await uniqueSiblingSlug(companyId, null, slug, squatted.id.slice(0, 8)), updatedAt: new Date() })
|
||||
.where(and(eq(folders.companyId, companyId), eq(folders.id, squatted.id)));
|
||||
}
|
||||
const created = await insertSystemFolder({ companyId, parentId: null, name, slug, systemKey: slug });
|
||||
if (created) return created;
|
||||
}
|
||||
throw conflict(`Could not create ${name} folder`);
|
||||
}
|
||||
|
||||
async function uniqueSystemSlug(
|
||||
companyId: string,
|
||||
parentId: string,
|
||||
baseSlug: string,
|
||||
systemKey: string,
|
||||
stableSuffix = systemKey.split(":").at(-1) ?? systemKey,
|
||||
) {
|
||||
const existingSystem = await db
|
||||
.select({ id: folders.id })
|
||||
.from(folders)
|
||||
.where(and(eq(folders.companyId, companyId), eq(folders.kind, "skill"), eq(folders.systemKey, systemKey)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (existingSystem) return { id: existingSystem.id, slug: null };
|
||||
return {
|
||||
id: null,
|
||||
slug: await uniqueSiblingSlug(companyId, parentId, baseSlug, stableSuffix),
|
||||
};
|
||||
}
|
||||
|
||||
async function ensureMyFolder(companyId: string, userId: string, userName: string | null, requestedSlug?: string | null): Promise<Folder> {
|
||||
if (!mutationLockHeld) {
|
||||
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).ensureMyFolder(companyId, userId, userName, requestedSlug));
|
||||
}
|
||||
const parent = await ensureContainer(companyId, "my", "My Skills");
|
||||
const systemKey = `my:${userId}`;
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
const resolved = await uniqueSystemSlug(companyId, parent.id, requestedSlug ?? normalizeFolderSlug(userName ?? userId), systemKey);
|
||||
if (resolved.id) return (await getFolder(companyId, resolved.id))!;
|
||||
const created = await insertSystemFolder({
|
||||
companyId,
|
||||
parentId: parent.id,
|
||||
name: userName?.trim() || "My Skills",
|
||||
slug: resolved.slug!,
|
||||
systemKey,
|
||||
});
|
||||
if (created) return created;
|
||||
}
|
||||
throw conflict("Could not create personal skill folder");
|
||||
}
|
||||
|
||||
async function ensureProjectFolder(companyId: string, projectId: string, projectName: string): Promise<Folder> {
|
||||
if (!mutationLockHeld) {
|
||||
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).ensureProjectFolder(companyId, projectId, projectName));
|
||||
}
|
||||
const parent = await ensureContainer(companyId, "projects", "Projects");
|
||||
const systemKey = `project:${projectId}`;
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
const resolved = await uniqueSystemSlug(companyId, parent.id, normalizeFolderSlug(projectName), systemKey);
|
||||
if (resolved.id) return (await getFolder(companyId, resolved.id))!;
|
||||
const created = await insertSystemFolder({
|
||||
companyId,
|
||||
parentId: parent.id,
|
||||
name: projectName,
|
||||
slug: resolved.slug!,
|
||||
systemKey,
|
||||
});
|
||||
if (created) return created;
|
||||
}
|
||||
throw conflict("Could not create project skill folder");
|
||||
}
|
||||
|
||||
async function ensureBundledCategory(companyId: string, category: string): Promise<Folder> {
|
||||
if (!mutationLockHeld) {
|
||||
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).ensureBundledCategory(companyId, category));
|
||||
}
|
||||
const root = await ensureContainer(companyId, "bundled", "Bundled");
|
||||
const name = normalizeName(category);
|
||||
const slug = normalizeFolderSlug(category);
|
||||
const systemKey = `bundled:${slug}`;
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
const resolved = await uniqueSystemSlug(companyId, root.id, slug, systemKey, "bundled");
|
||||
if (resolved.id) {
|
||||
const existing = await getFolder(companyId, resolved.id);
|
||||
if (!existing) continue;
|
||||
if (existing.name === name) return existing;
|
||||
await db
|
||||
.update(folders)
|
||||
.set({ name, updatedAt: new Date() })
|
||||
.where(and(eq(folders.companyId, companyId), eq(folders.id, existing.id)));
|
||||
return (await getFolder(companyId, existing.id))!;
|
||||
}
|
||||
const created = await insertSystemFolder({
|
||||
companyId,
|
||||
parentId: root.id,
|
||||
name,
|
||||
slug: resolved.slug!,
|
||||
systemKey,
|
||||
});
|
||||
if (created) return created;
|
||||
}
|
||||
throw conflict("Could not create bundled skill folder");
|
||||
}
|
||||
|
||||
async function pruneEmptyBundledCategories(companyId: string, retainedCategories: string[]): Promise<void> {
|
||||
if (!mutationLockHeld) {
|
||||
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).pruneEmptyBundledCategories(companyId, retainedCategories));
|
||||
}
|
||||
const root = await findSystemFolder(companyId, "bundled");
|
||||
if (!root) return;
|
||||
const rows = await getRows(companyId, "skill");
|
||||
const retainedSystemKeys = new Set(
|
||||
retainedCategories.map((category) => `bundled:${normalizeFolderSlug(category)}`),
|
||||
);
|
||||
const usedFolderIds = new Set(
|
||||
await db
|
||||
.select({ folderId: companySkills.folderId })
|
||||
.from(companySkills)
|
||||
.where(eq(companySkills.companyId, companyId))
|
||||
.then((skills) => skills.flatMap((skill) => skill.folderId ? [skill.folderId] : [])),
|
||||
);
|
||||
const parentIds = new Set(rows.flatMap((row) => row.parentId ? [row.parentId] : []));
|
||||
for (const row of rows) {
|
||||
if (row.parentId !== root.id || !row.systemKey?.startsWith("bundled:")) continue;
|
||||
if (retainedSystemKeys.has(row.systemKey) || usedFolderIds.has(row.id) || parentIds.has(row.id)) continue;
|
||||
await db.delete(folders).where(and(eq(folders.companyId, companyId), eq(folders.id, row.id)));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
list,
|
||||
create,
|
||||
update,
|
||||
moveFolder,
|
||||
deleteFolder,
|
||||
moveItem,
|
||||
getFolder,
|
||||
descendantIds,
|
||||
validateSkillFolder,
|
||||
ensureMyFolder,
|
||||
ensureProjectFolder,
|
||||
ensureBundledCategory,
|
||||
pruneEmptyBundledCategories,
|
||||
};
|
||||
}
|
||||
@@ -5,6 +5,7 @@ export { companySearchExtractService } from "./company-search-extract.js";
|
||||
export { feedbackService } from "./feedback.js";
|
||||
export { companySkillService } from "./company-skills.js";
|
||||
export { companySkillPolicyService, normalizeSkillPolicySourceType } from "./company-skill-policy.js";
|
||||
export { folderService } from "./folders.js";
|
||||
export { agentService, deduplicateAgentName } from "./agents.js";
|
||||
export {
|
||||
builtInAgentService,
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
documentRevisions,
|
||||
documents,
|
||||
executionWorkspaces,
|
||||
folders,
|
||||
goals,
|
||||
heartbeatRuns,
|
||||
issueInboxArchives,
|
||||
@@ -974,6 +975,17 @@ export function routineService(
|
||||
if (parentIssue.companyId !== companyId) throw unprocessable("Parent issue must belong to same company");
|
||||
}
|
||||
|
||||
async function assertRoutineFolder(companyId: string, folderId: string | null | undefined) {
|
||||
if (!folderId) return;
|
||||
const folder = await db
|
||||
.select({ id: folders.id, kind: folders.kind })
|
||||
.from(folders)
|
||||
.where(and(eq(folders.companyId, companyId), eq(folders.id, folderId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!folder) throw notFound("Folder not found");
|
||||
if (folder.kind !== "routine") throw unprocessable("Folder kind must match routine");
|
||||
}
|
||||
|
||||
async function listTriggersForRoutineIds(companyId: string, routineIds: string[]) {
|
||||
if (routineIds.length === 0) return new Map<string, RoutineTrigger[]>();
|
||||
const rows = await db
|
||||
@@ -2066,6 +2078,7 @@ export function routineService(
|
||||
|
||||
create: async (companyId: string, input: CreateRoutine, actor: Actor): Promise<Routine> => {
|
||||
await assertProject(companyId, input.projectId ?? null);
|
||||
await assertRoutineFolder(companyId, input.folderId ?? null);
|
||||
await assertAssignableAgent(db, companyId, input.assigneeAgentId ?? null, { kind: "routine" });
|
||||
if (input.goalId) await assertGoal(companyId, input.goalId);
|
||||
if (input.parentIssueId) await assertParentIssue(companyId, input.parentIssueId);
|
||||
@@ -2092,6 +2105,7 @@ export function routineService(
|
||||
.values({
|
||||
companyId,
|
||||
projectId: input.projectId ?? null,
|
||||
folderId: input.folderId ?? null,
|
||||
goalId: input.goalId ?? null,
|
||||
parentIssueId: input.parentIssueId ?? null,
|
||||
title: input.title,
|
||||
@@ -2130,6 +2144,7 @@ export function routineService(
|
||||
const existing = await getRoutineById(id);
|
||||
if (!existing) return null;
|
||||
const nextProjectId = patch.projectId === undefined ? existing.projectId : patch.projectId;
|
||||
const nextFolderId = patch.folderId === undefined ? existing.folderId : patch.folderId;
|
||||
const nextAssigneeAgentId = patch.assigneeAgentId === undefined ? existing.assigneeAgentId : patch.assigneeAgentId;
|
||||
const nextTitle = patch.title ?? existing.title;
|
||||
const nextDescription = patch.description === undefined ? existing.description : patch.description;
|
||||
@@ -2153,6 +2168,7 @@ export function routineService(
|
||||
patch.variables === undefined ? existing.variables : sanitizeRoutineVariableInputs(patch.variables),
|
||||
);
|
||||
if (patch.projectId !== undefined) await assertProject(existing.companyId, nextProjectId);
|
||||
if (patch.folderId !== undefined) await assertRoutineFolder(existing.companyId, nextFolderId);
|
||||
if (patch.assigneeAgentId !== undefined || patch.status === "active") {
|
||||
await assertAssignableAgent(db, existing.companyId, nextAssigneeAgentId, { kind: "routine" });
|
||||
}
|
||||
@@ -2202,6 +2218,7 @@ export function routineService(
|
||||
const candidate: RoutineRow = {
|
||||
...locked,
|
||||
projectId: nextProjectId,
|
||||
folderId: nextFolderId,
|
||||
goalId: patch.goalId === undefined ? locked.goalId : patch.goalId,
|
||||
parentIssueId: patch.parentIssueId === undefined ? locked.parentIssueId : patch.parentIssueId,
|
||||
title: nextTitle,
|
||||
@@ -2218,8 +2235,20 @@ export function routineService(
|
||||
updatedByUserId: actor.userId ?? null,
|
||||
};
|
||||
|
||||
const folderChanged = patch.folderId !== undefined && locked.folderId !== candidate.folderId;
|
||||
if (locked.latestRevisionId && routineCurrentFieldsMatch(locked, candidate)) {
|
||||
return locked;
|
||||
if (!folderChanged) return locked;
|
||||
const [updated] = await txDb
|
||||
.update(routines)
|
||||
.set({
|
||||
folderId: candidate.folderId,
|
||||
updatedByAgentId: actor.agentId ?? null,
|
||||
updatedByUserId: actor.userId ?? null,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(routines.id, id))
|
||||
.returning();
|
||||
return updated ?? locked;
|
||||
}
|
||||
|
||||
const nextSnapshot = await buildRoutineRevisionSnapshot(txDb, candidate);
|
||||
@@ -2252,6 +2281,7 @@ export function routineService(
|
||||
.update(routines)
|
||||
.set({
|
||||
projectId: candidate.projectId,
|
||||
folderId: candidate.folderId,
|
||||
goalId: candidate.goalId,
|
||||
parentIssueId: candidate.parentIssueId,
|
||||
title: candidate.title,
|
||||
|
||||
Reference in new issue
Block a user