Skip to content

The open-source app everyone uses to manage agents at work

Build the Skills Store (#7990)

Dotta1413729a06ce
diff --git a/packages/adapter-utils/src/server-utils.ts b/packages/adapter-utils/src/server-utils.ts
index 44eb5bbd14..392e607337 100644
--- a/packages/adapter-utils/src/server-utils.ts
+++ b/packages/adapter-utils/src/server-utils.ts
@@ -133,12 +133,19 @@ export interface PaperclipSkillEntry {
key: string;
runtimeName: string;
source: string;
+ versionId?: string | null;
+ currentVersionId?: string | null;
sourceStatus?: "available" | "missing";
missingDetail?: string | null;
required?: boolean;
requiredReason?: string | null;
}
+export interface PaperclipDesiredSkillEntry {
+ key: string;
+ versionId: string | null;
+}
+
export interface InstalledSkillTarget {
targetPath: string | null;
kind: "symlink" | "directory" | "file";
@@ -1446,6 +1453,8 @@ export function buildRuntimeMountedSkillSnapshot(
entries.push({
key: available.key,
runtimeName: available.runtimeName,
+ versionId: available.versionId ?? null,
+ currentVersionId: available.currentVersionId ?? null,
desired,
managed: true,
state: "missing",
@@ -1463,6 +1472,8 @@ export function buildRuntimeMountedSkillSnapshot(
entries.push({
key: available.key,
runtimeName: available.runtimeName,
+ versionId: available.versionId ?? null,
+ currentVersionId: available.currentVersionId ?? null,
desired,
managed: true,
state: configured ? "configured" : "available",
@@ -1528,6 +1539,10 @@ export function buildRuntimeMountedSkillSnapshot(
supported,
mode,
desiredSkills,
+ desiredSkillEntries: desiredSkills.map((key) => ({
+ key,
+ versionId: availableByKey.get(key)?.versionId ?? null,
+ })),
entries,
warnings,
};
@@ -1560,6 +1575,8 @@ export function buildPersistentSkillSnapshot(
entries.push({
key: available.key,
runtimeName: available.runtimeName,
+ versionId: available.versionId ?? null,
+ currentVersionId: available.currentVersionId ?? null,
desired,
managed: true,
state: "missing",
@@ -1595,6 +1612,8 @@ export function buildPersistentSkillSnapshot(
entries.push({
key: available.key,
runtimeName: available.runtimeName,
+ versionId: available.versionId ?? null,
+ currentVersionId: available.currentVersionId ?? null,
desired,
managed,
state,
@@ -1650,6 +1669,10 @@ export function buildPersistentSkillSnapshot(
supported: true,
mode: "persistent",
desiredSkills,
+ desiredSkillEntries: desiredSkills.map((key) => ({
+ key,
+ versionId: availableByKey.get(key)?.versionId ?? null,
+ })),
entries,
warnings,
};
@@ -1668,6 +1691,14 @@ function normalizeConfiguredPaperclipRuntimeSkills(value: unknown): PaperclipSki
key,
runtimeName,
source,
+ versionId:
+ typeof entry.versionId === "string" && entry.versionId.trim().length > 0
+ ? entry.versionId.trim()
+ : null,
+ currentVersionId:
+ typeof entry.currentVersionId === "string" && entry.currentVersionId.trim().length > 0
+ ? entry.currentVersionId.trim()
+ : null,
sourceStatus: entry.sourceStatus === "missing" ? "missing" : "available",
missingDetail:
typeof entry.missingDetail === "string" && entry.missingDetail.trim().length > 0
@@ -1714,22 +1745,41 @@ export async function readPaperclipSkillMarkdown(
export function readPaperclipSkillSyncPreference(config: Record<string, unknown>): {
explicit: boolean;
desiredSkills: string[];
+ desiredSkillEntries: PaperclipDesiredSkillEntry[];
} {
const raw = config.paperclipSkillSync;
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
- return { explicit: false, desiredSkills: [] };
+ return { explicit: false, desiredSkills: [], desiredSkillEntries: [] };
}
const syncConfig = raw as Record<string, unknown>;
const desiredValues = syncConfig.desiredSkills;
const desired = Array.isArray(desiredValues)
- ? desiredValues
- .filter((value): value is string => typeof value === "string")
- .map((value) => value.trim())
- .filter(Boolean)
+ ? desiredValues.flatMap((value): PaperclipDesiredSkillEntry[] => {
+ if (typeof value === "string") {
+ const key = value.trim();
+ return key ? [{ key, versionId: null }] : [];
+ }
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
+ const record = value as Record<string, unknown>;
+ const key = typeof record.key === "string" ? record.key.trim() : "";
+ if (!key) return [];
+ const versionId = typeof record.versionId === "string" && record.versionId.trim()
+ ? record.versionId.trim()
+ : null;
+ return [{ key, versionId }];
+ }
+ return [];
+ })
: [];
+ const byKey = new Map<string, PaperclipDesiredSkillEntry>();
+ for (const entry of desired) {
+ if (!byKey.has(entry.key)) byKey.set(entry.key, entry);
+ }
+ const desiredSkillEntries = Array.from(byKey.values());
return {
explicit: Object.prototype.hasOwnProperty.call(raw, "desiredSkills"),
- desiredSkills: Array.from(new Set(desired)),
+ desiredSkills: desiredSkillEntries.map((entry) => entry.key),
+ desiredSkillEntries,
};
}
@@ -1775,7 +1825,7 @@ export function resolvePaperclipDesiredSkillNames(
export function writePaperclipSkillSyncPreference(
config: Record<string, unknown>,
- desiredSkills: string[],
+ desiredSkills: Array<string | PaperclipDesiredSkillEntry>,
): Record<string, unknown> {
const next = { ...config };
const raw = next.paperclipSkillSync;
@@ -1783,13 +1833,23 @@ export function writePaperclipSkillSyncPreference(
typeof raw === "object" && raw !== null && !Array.isArray(raw)
? { ...(raw as Record<string, unknown>) }
: {};
- current.desiredSkills = Array.from(
- new Set(
- desiredSkills
- .map((value) => value.trim())
- .filter(Boolean),
- ),
- );
+ const entries = desiredSkills.flatMap((value): PaperclipDesiredSkillEntry[] => {
+ if (typeof value === "string") {
+ const key = value.trim();
+ return key ? [{ key, versionId: null }] : [];
+ }
+ const key = value.key.trim();
+ if (!key) return [];
+ return [{ key, versionId: value.versionId ?? null }];
+ });
+ const byKey = new Map<string, PaperclipDesiredSkillEntry>();
+ for (const entry of entries) {
+ if (!byKey.has(entry.key)) byKey.set(entry.key, entry);
+ }
+ const normalized = Array.from(byKey.values());
+ current.desiredSkills = normalized.some((entry) => entry.versionId)
+ ? normalized
+ : normalized.map((entry) => entry.key);
next.paperclipSkillSync = current;
return next;
}
diff --git a/packages/adapter-utils/src/types.ts b/packages/adapter-utils/src/types.ts
index 3d87f7a284..2aac3d8c30 100644
--- a/packages/adapter-utils/src/types.ts
+++ b/packages/adapter-utils/src/types.ts
@@ -193,6 +193,8 @@ export type AdapterSkillOrigin =
export interface AdapterSkillEntry {
key: string;
runtimeName: string | null;
+ versionId?: string | null;
+ currentVersionId?: string | null;
desired: boolean;
managed: boolean;
required?: boolean;
@@ -212,6 +214,7 @@ export interface AdapterSkillSnapshot {
supported: boolean;
mode: AdapterSkillSyncMode;
desiredSkills: string[];
+ desiredSkillEntries?: Array<{ key: string; versionId: string | null }>;
entries: AdapterSkillEntry[];
warnings: string[];
}
diff --git a/packages/db/src/migrations/0099_skills_store_foundation.sql b/packages/db/src/migrations/0099_skills_store_foundation.sql
new file mode 100644
index 0000000000..1c541a79c9
--- /dev/null
+++ b/packages/db/src/migrations/0099_skills_store_foundation.sql
@@ -0,0 +1,121 @@
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "icon_url" text;--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "color" text;--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "tagline" text;--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "author_name" text;--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "homepage_url" text;--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "categories" text[] NOT NULL DEFAULT '{}';--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "sharing_scope" text NOT NULL DEFAULT 'company';--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "public_share_token" text;--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "forked_from_skill_id" uuid;--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "forked_from_company_id" uuid;--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "star_count" integer NOT NULL DEFAULT 0;--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "install_count" integer NOT NULL DEFAULT 0;--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "fork_count" integer NOT NULL DEFAULT 0;--> statement-breakpoint
+ALTER TABLE "company_skills" ADD COLUMN IF NOT EXISTS "current_version_id" uuid;--> statement-breakpoint
+CREATE TABLE IF NOT EXISTS "company_skill_versions" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "company_id" uuid NOT NULL,
+ "company_skill_id" uuid NOT NULL,
+ "revision_number" integer NOT NULL,
+ "label" text,
+ "file_inventory" jsonb DEFAULT '[]'::jsonb NOT NULL,
+ "author_agent_id" uuid,
+ "author_user_id" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);--> statement-breakpoint
+CREATE TABLE IF NOT EXISTS "company_skill_stars" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "company_id" uuid NOT NULL,
+ "company_skill_id" uuid NOT NULL,
+ "agent_id" uuid,
+ "user_id" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);--> statement-breakpoint
+CREATE TABLE IF NOT EXISTS "company_skill_comments" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "company_id" uuid NOT NULL,
+ "company_skill_id" uuid NOT NULL,
+ "parent_comment_id" uuid,
+ "author_agent_id" uuid,
+ "author_user_id" text,
+ "body" text NOT NULL,
+ "deleted_at" timestamp with time zone,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skills" ADD CONSTRAINT "company_skills_forked_from_skill_id_company_skills_id_fk" FOREIGN KEY ("forked_from_skill_id") REFERENCES "public"."company_skills"("id") ON DELETE set null ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skills" ADD CONSTRAINT "company_skills_forked_from_company_id_companies_id_fk" FOREIGN KEY ("forked_from_company_id") REFERENCES "public"."companies"("id") ON DELETE set null ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_versions" ADD CONSTRAINT "company_skill_versions_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_versions" ADD CONSTRAINT "company_skill_versions_company_skill_id_company_skills_id_fk" FOREIGN KEY ("company_skill_id") REFERENCES "public"."company_skills"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_versions" ADD CONSTRAINT "company_skill_versions_author_agent_id_agents_id_fk" FOREIGN KEY ("author_agent_id") REFERENCES "public"."agents"("id") ON DELETE set null ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skills" ADD CONSTRAINT "company_skills_current_version_id_company_skill_versions_id_fk" FOREIGN KEY ("current_version_id") REFERENCES "public"."company_skill_versions"("id") ON DELETE set null ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_stars" ADD CONSTRAINT "company_skill_stars_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_stars" ADD CONSTRAINT "company_skill_stars_company_skill_id_company_skills_id_fk" FOREIGN KEY ("company_skill_id") REFERENCES "public"."company_skills"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_stars" ADD CONSTRAINT "company_skill_stars_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_comments" ADD CONSTRAINT "company_skill_comments_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_comments" ADD CONSTRAINT "company_skill_comments_company_skill_id_company_skills_id_fk" FOREIGN KEY ("company_skill_id") REFERENCES "public"."company_skills"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_comments" ADD CONSTRAINT "company_skill_comments_parent_comment_id_company_skill_comments_id_fk" FOREIGN KEY ("parent_comment_id") REFERENCES "public"."company_skill_comments"("id") ON DELETE set null ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_comments" ADD CONSTRAINT "company_skill_comments_author_agent_id_agents_id_fk" FOREIGN KEY ("author_agent_id") REFERENCES "public"."agents"("id") ON DELETE set null ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skills_company_categories_idx" ON "company_skills" USING gin ("categories");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skills_company_sharing_scope_idx" ON "company_skills" USING btree ("company_id","sharing_scope");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skills_company_current_version_idx" ON "company_skills" USING btree ("company_id","current_version_id");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skills_company_forked_from_idx" ON "company_skills" USING btree ("company_id","forked_from_skill_id");--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS "company_skill_versions_skill_revision_idx" ON "company_skill_versions" USING btree ("company_skill_id","revision_number");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skill_versions_company_skill_created_idx" ON "company_skill_versions" USING btree ("company_id","company_skill_id","created_at");--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS "company_skill_stars_skill_agent_idx" ON "company_skill_stars" USING btree ("company_skill_id","agent_id");--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS "company_skill_stars_skill_user_idx" ON "company_skill_stars" USING btree ("company_skill_id","user_id");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skill_stars_company_skill_created_idx" ON "company_skill_stars" USING btree ("company_id","company_skill_id","created_at");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skill_comments_company_skill_created_idx" ON "company_skill_comments" USING btree ("company_id","company_skill_id","created_at");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skill_comments_parent_idx" ON "company_skill_comments" USING btree ("parent_comment_id");
diff --git a/packages/db/src/migrations/0100_skill_install_count_backfill.sql b/packages/db/src/migrations/0100_skill_install_count_backfill.sql
new file mode 100644
index 0000000000..a464c92275
--- /dev/null
+++ b/packages/db/src/migrations/0100_skill_install_count_backfill.sql
@@ -0,0 +1,3 @@
+UPDATE "company_skills" SET "install_count" = 0 WHERE "install_count" IS NULL;--> statement-breakpoint
+ALTER TABLE "company_skills" ALTER COLUMN "install_count" SET DEFAULT 0;--> statement-breakpoint
+ALTER TABLE "company_skills" ALTER COLUMN "install_count" SET NOT NULL;
diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json
index 96c9209ead..f5e72cf46d 100644
--- a/packages/db/src/migrations/meta/_journal.json
+++ b/packages/db/src/migrations/meta/_journal.json
@@ -694,6 +694,20 @@
"when": 1780534200000,
"tag": "0098_project_icon",
"breakpoints": true
+ },
+ {
+ "idx": 99,
+ "version": "7",
+ "when": 1781130000000,
+ "tag": "0099_skills_store_foundation",
+ "breakpoints": true
+ },
+ {
+ "idx": 100,
+ "version": "7",
+ "when": 1781480000000,
+ "tag": "0100_skill_install_count_backfill",
+ "breakpoints": true
}
]
}
diff --git a/packages/db/src/schema/company_skills.ts b/packages/db/src/schema/company_skills.ts
index aff17c8eaf..abb1d2b6b9 100644
--- a/packages/db/src/schema/company_skills.ts
+++ b/packages/db/src/schema/company_skills.ts
@@ -1,12 +1,16 @@
import {
+ type AnyPgColumn,
pgTable,
uuid,
text,
timestamp,
jsonb,
index,
+ integer,
uniqueIndex,
} from "drizzle-orm/pg-core";
+import type { CompanySkillFileInventoryEntry, CompanySkillSharingScope } from "@paperclipai/shared";
+import { agents } from "./agents.js";
import { companies } from "./companies.js";
export const companySkills = pgTable(
@@ -25,6 +29,20 @@ export const companySkills = pgTable(
trustLevel: text("trust_level").notNull().default("markdown_only"),
compatibility: text("compatibility").notNull().default("compatible"),
fileInventory: jsonb("file_inventory").$type<Array<Record<string, unknown>>>().notNull().default([]),
+ iconUrl: text("icon_url"),
+ color: text("color"),
+ tagline: text("tagline"),
+ authorName: text("author_name"),
+ homepageUrl: text("homepage_url"),
+ categories: text("categories").array().notNull().default([]),
+ sharingScope: text("sharing_scope").$type<CompanySkillSharingScope>().notNull().default("company"),
+ publicShareToken: text("public_share_token"),
+ forkedFromSkillId: uuid("forked_from_skill_id").references((): AnyPgColumn => companySkills.id, { onDelete: "set null" }),
+ forkedFromCompanyId: uuid("forked_from_company_id").references(() => companies.id, { onDelete: "set null" }),
+ starCount: integer("star_count").notNull().default(0),
+ installCount: integer("install_count").notNull().default(0),
+ forkCount: integer("fork_count").notNull().default(0),
+ currentVersionId: uuid("current_version_id").references((): AnyPgColumn => companySkillVersions.id, { onDelete: "set null" }),
metadata: jsonb("metadata").$type<Record<string, unknown>>(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
@@ -32,5 +50,84 @@ export const companySkills = pgTable(
(table) => ({
companyKeyUniqueIdx: uniqueIndex("company_skills_company_key_idx").on(table.companyId, table.key),
companyNameIdx: index("company_skills_company_name_idx").on(table.companyId, table.name),
+ companyCategoriesIdx: index("company_skills_company_categories_idx").using("gin", table.categories),
+ companySharingScopeIdx: index("company_skills_company_sharing_scope_idx").on(table.companyId, table.sharingScope),
+ companyCurrentVersionIdx: index("company_skills_company_current_version_idx").on(table.companyId, table.currentVersionId),
+ companyForkedFromIdx: index("company_skills_company_forked_from_idx").on(table.companyId, table.forkedFromSkillId),
+ }),
+);
+
+export type CompanySkillVersionFileInventoryEntry = CompanySkillFileInventoryEntry & {
+ content: string;
+};
+
+export const companySkillVersions = pgTable(
+ "company_skill_versions",
+ {
+ id: uuid("id").primaryKey().defaultRandom(),
+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
+ companySkillId: uuid("company_skill_id").notNull().references(() => companySkills.id, { onDelete: "cascade" }),
+ revisionNumber: integer("revision_number").notNull(),
+ label: text("label"),
+ fileInventory: jsonb("file_inventory").$type<CompanySkillVersionFileInventoryEntry[]>().notNull().default([]),
+ authorAgentId: uuid("author_agent_id").references(() => agents.id, { onDelete: "set null" }),
+ authorUserId: text("author_user_id"),
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
+ },
+ (table) => ({
+ companySkillRevisionUniqueIdx: uniqueIndex("company_skill_versions_skill_revision_idx").on(
+ table.companySkillId,
+ table.revisionNumber,
+ ),
+ companySkillCreatedIdx: index("company_skill_versions_company_skill_created_idx").on(
+ table.companyId,
+ table.companySkillId,
+ table.createdAt,
+ ),
+ }),
+);
+
+export const companySkillStars = pgTable(
+ "company_skill_stars",
+ {
+ id: uuid("id").primaryKey().defaultRandom(),
+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
+ companySkillId: uuid("company_skill_id").notNull().references(() => companySkills.id, { onDelete: "cascade" }),
+ agentId: uuid("agent_id").references(() => agents.id, { onDelete: "cascade" }),
+ userId: text("user_id"),
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
+ },
+ (table) => ({
+ companySkillAgentUniqueIdx: uniqueIndex("company_skill_stars_skill_agent_idx").on(table.companySkillId, table.agentId),
+ companySkillUserUniqueIdx: uniqueIndex("company_skill_stars_skill_user_idx").on(table.companySkillId, table.userId),
+ companySkillCreatedIdx: index("company_skill_stars_company_skill_created_idx").on(
+ table.companyId,
+ table.companySkillId,
+ table.createdAt,
+ ),
+ }),
+);
+
+export const companySkillComments = pgTable(
+ "company_skill_comments",
+ {
+ id: uuid("id").primaryKey().defaultRandom(),
+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
+ companySkillId: uuid("company_skill_id").notNull().references(() => companySkills.id, { onDelete: "cascade" }),
+ parentCommentId: uuid("parent_comment_id").references((): AnyPgColumn => companySkillComments.id, { onDelete: "set null" }),
+ authorAgentId: uuid("author_agent_id").references(() => agents.id, { onDelete: "set null" }),
+ authorUserId: text("author_user_id"),
+ body: text("body").notNull(),
+ deletedAt: timestamp("deleted_at", { withTimezone: true }),
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
+ },
+ (table) => ({
+ companySkillCreatedIdx: index("company_skill_comments_company_skill_created_idx").on(
+ table.companyId,
+ table.companySkillId,
+ table.createdAt,
+ ),
+ parentIdx: index("company_skill_comments_parent_idx").on(table.parentCommentId),
}),
);
diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts
index 9d78a33cbd..2dfc4f7d86 100644
--- a/packages/db/src/schema/index.ts
+++ b/packages/db/src/schema/index.ts
@@ -72,7 +72,7 @@ export { companySecrets } from "./company_secrets.js";
export { companySecretVersions } from "./company_secret_versions.js";
export { companySecretBindings } from "./company_secret_bindings.js";
export { secretAccessEvents } from "./secret_access_events.js";
-export { companySkills } from "./company_skills.js";
+export { companySkills, companySkillVersions, companySkillStars, companySkillComments } from "./company_skills.js";
export { plugins } from "./plugins.js";
export { pluginConfig } from "./plugin_config.js";
export { pluginCompanySettings } from "./plugin_company_settings.js";
diff --git a/packages/plugins/sdk/src/testing.ts b/packages/plugins/sdk/src/testing.ts
index b3189bf7ec..aaacebbcb8 100644
--- a/packages/plugins/sdk/src/testing.ts
+++ b/packages/plugins/sdk/src/testing.ts
@@ -1347,6 +1347,20 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {
trustLevel: "markdown_only",
compatibility: "compatible",
fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ iconUrl: null,
+ color: null,
+ tagline: declaration.description?.slice(0, 120) ?? null,
+ authorName: null,
+ homepageUrl: null,
+ categories: [],
+ sharingScope: "company",
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 0,
+ installCount: 1,
+ forkCount: 0,
+ currentVersionId: null,
metadata: {
sourceKind: "catalog",
pluginManagedResource: {
@@ -1403,6 +1417,20 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {
trustLevel: "markdown_only",
compatibility: "compatible",
fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ iconUrl: null,
+ color: null,
+ tagline: declaration.description?.slice(0, 120) ?? null,
+ authorName: null,
+ homepageUrl: null,
+ categories: [],
+ sharingScope: "company",
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: existing.skill?.starCount ?? 0,
+ installCount: existing.skill?.installCount ?? 1,
+ forkCount: existing.skill?.forkCount ?? 0,
+ currentVersionId: existing.skill?.currentVersionId ?? null,
metadata: {
sourceKind: "catalog",
pluginManagedResource: {
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 0a1d3f7925..60f66917e9 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -334,11 +334,24 @@ export type {
CompanySkillTrustLevel,
CompanySkillCompatibility,
CompanySkillSourceBadge,
+ CompanySkillSharingScope,
+ CompanySkillListSort,
CompanySkillFileInventoryEntry,
+ CompanySkillVersionFileInventoryEntry,
CompanySkill,
CompanySkillListItem,
CompanySkillUsageAgent,
CompanySkillDetail,
+ CompanySkillListQuery,
+ CompanySkillCategoryCount,
+ CompanySkillVersion,
+ CompanySkillVersionCreateRequest,
+ CompanySkillStarResult,
+ CompanySkillComment,
+ CompanySkillCommentCreateRequest,
+ CompanySkillCommentUpdateRequest,
+ CompanySkillForkRequest,
+ CompanySkillUpdateRequest,
CompanySkillUpdateStatus,
CompanySkillAuditSeverity,
CompanySkillAuditVerdict,
@@ -390,6 +403,7 @@ export type {
AgentSkillSyncMode,
AgentSkillState,
AgentSkillOrigin,
+ AgentDesiredSkillEntry,
AgentSkillEntry,
AgentSkillSnapshot,
AgentSkillSyncRequest,
@@ -918,6 +932,8 @@ export {
type ProbeEnvironmentConfig,
agentSkillStateSchema,
agentSkillSyncModeSchema,
+ agentDesiredSkillEntrySchema,
+ agentDesiredSkillSelectionSchema,
agentSkillEntrySchema,
agentSkillSnapshotSchema,
agentSkillSyncSchema,
@@ -1212,11 +1228,24 @@ export {
companySkillTrustLevelSchema,
companySkillCompatibilitySchema,
companySkillSourceBadgeSchema,
+ companySkillSharingScopeSchema,
+ companySkillListSortSchema,
companySkillFileInventoryEntrySchema,
+ companySkillVersionFileInventoryEntrySchema,
companySkillSchema,
companySkillListItemSchema,
companySkillUsageAgentSchema,
+ companySkillListQuerySchema,
+ companySkillCategoryCountSchema,
+ companySkillVersionSchema,
companySkillDetailSchema,
+ companySkillVersionCreateSchema,
+ companySkillStarResultSchema,
+ companySkillCommentSchema,
+ companySkillCommentCreateSchema,
+ companySkillCommentUpdateSchema,
+ companySkillForkSchema,
+ companySkillUpdateSchema,
companySkillUpdateStatusSchema,
companySkillAuditFindingSchema,
companySkillAuditResultSchema,
diff --git a/packages/shared/src/types/adapter-skills.ts b/packages/shared/src/types/adapter-skills.ts
index 2699bef0a3..36d6d4fda1 100644
--- a/packages/shared/src/types/adapter-skills.ts
+++ b/packages/shared/src/types/adapter-skills.ts
@@ -14,9 +14,16 @@ export type AgentSkillOrigin =
| "user_installed"
| "external_unknown";
+export interface AgentDesiredSkillEntry {
+ key: string;
+ versionId: string | null;
+}
+
export interface AgentSkillEntry {
key: string;
runtimeName: string | null;
+ versionId?: string | null;
+ currentVersionId?: string | null;
desired: boolean;
managed: boolean;
required?: boolean;
@@ -36,10 +43,11 @@ export interface AgentSkillSnapshot {
supported: boolean;
mode: AgentSkillSyncMode;
desiredSkills: string[];
+ desiredSkillEntries?: AgentDesiredSkillEntry[];
entries: AgentSkillEntry[];
warnings: string[];
}
export interface AgentSkillSyncRequest {
- desiredSkills: string[];
+ desiredSkills: Array<string | AgentDesiredSkillEntry>;
}
diff --git a/packages/shared/src/types/company-skill.ts b/packages/shared/src/types/company-skill.ts
index 356e3d421d..a2d3e6b9f2 100644
--- a/packages/shared/src/types/company-skill.ts
+++ b/packages/shared/src/types/company-skill.ts
@@ -6,11 +6,19 @@ export type CompanySkillCompatibility = "compatible" | "unknown" | "invalid";
export type CompanySkillSourceBadge = "paperclip" | "github" | "local" | "url" | "catalog" | "skills_sh";
+export type CompanySkillSharingScope = "private" | "company" | "public_link";
+
+export type CompanySkillListSort = "alphabetical" | "recent" | "installs" | "stars" | "agents" | "forks";
+
export interface CompanySkillFileInventoryEntry {
path: string;
kind: "skill" | "markdown" | "reference" | "script" | "asset" | "other";
}
+export interface CompanySkillVersionFileInventoryEntry extends CompanySkillFileInventoryEntry {
+ content: string;
+}
+
export interface CompanySkill {
id: string;
companyId: string;
@@ -25,6 +33,20 @@ export interface CompanySkill {
trustLevel: CompanySkillTrustLevel;
compatibility: CompanySkillCompatibility;
fileInventory: CompanySkillFileInventoryEntry[];
+ iconUrl: string | null;
+ color: string | null;
+ tagline: string | null;
+ authorName: string | null;
+ homepageUrl: string | null;
+ categories: string[];
+ sharingScope: CompanySkillSharingScope;
+ publicShareToken: string | null;
+ forkedFromSkillId: string | null;
+ forkedFromCompanyId: string | null;
+ starCount: number;
+ installCount: number;
+ forkCount: number;
+ currentVersionId: string | null;
metadata: Record<string, unknown> | null;
createdAt: Date;
updatedAt: Date;
@@ -43,6 +65,20 @@ export interface CompanySkillListItem {
trustLevel: CompanySkillTrustLevel;
compatibility: CompanySkillCompatibility;
fileInventory: CompanySkillFileInventoryEntry[];
+ iconUrl: string | null;
+ color: string | null;
+ tagline: string | null;
+ authorName: string | null;
+ homepageUrl: string | null;
+ categories: string[];
+ sharingScope: CompanySkillSharingScope;
+ publicShareToken: string | null;
+ forkedFromSkillId: string | null;
+ forkedFromCompanyId: string | null;
+ starCount: number;
+ installCount: number;
+ forkCount: number;
+ currentVersionId: string | null;
createdAt: Date;
updatedAt: Date;
attachedAgentCount: number;
@@ -69,6 +105,7 @@ export interface CompanySkillUsageAgent {
* agent runtimes while loading operator-facing skill metadata.
*/
actualState: string | null;
+ versionId: string | null;
}
export interface CompanySkillDetail extends CompanySkill {
@@ -79,6 +116,81 @@ export interface CompanySkillDetail extends CompanySkill {
sourceLabel: string | null;
sourceBadge: CompanySkillSourceBadge;
sourcePath: string | null;
+ currentVersion: CompanySkillVersion | null;
+ starredByCurrentActor: boolean;
+}
+
+export interface CompanySkillListQuery {
+ q?: string;
+ sort?: CompanySkillListSort;
+ categories?: string[];
+ scope?: CompanySkillSharingScope;
+}
+
+export interface CompanySkillCategoryCount {
+ slug: string;
+ count: number;
+}
+
+export interface CompanySkillVersion {
+ id: string;
+ companyId: string;
+ companySkillId: string;
+ revisionNumber: number;
+ label: string | null;
+ fileInventory: CompanySkillVersionFileInventoryEntry[];
+ authorAgentId: string | null;
+ authorUserId: string | null;
+ createdAt: Date;
+}
+
+export interface CompanySkillVersionCreateRequest {
+ label?: string | null;
+}
+
+export interface CompanySkillStarResult {
+ skillId: string;
+ starred: boolean;
+ starCount: number;
+}
+
+export interface CompanySkillComment {
+ id: string;
+ companyId: string;
+ companySkillId: string;
+ parentCommentId: string | null;
+ authorAgentId: string | null;
+ authorUserId: string | null;
+ body: string;
+ deletedAt: Date | null;
+ createdAt: Date;
+ updatedAt: Date;
+}
+
+export interface CompanySkillCommentCreateRequest {
+ body: string;
+ parentCommentId?: string | null;
+}
+
+export interface CompanySkillCommentUpdateRequest {
+ body: string;
+}
+
+export interface CompanySkillForkRequest {
+ name?: string | null;
+ slug?: string | null;
+ sharingScope?: CompanySkillSharingScope;
+}
+
+export interface CompanySkillUpdateRequest {
+ description?: string | null;
+ iconUrl?: string | null;
+ color?: string | null;
+ tagline?: string | null;
+ authorName?: string | null;
+ homepageUrl?: string | null;
+ categories?: string[];
+ sharingScope?: CompanySkillSharingScope;
}
export interface CompanySkillUpdateStatus {
@@ -186,6 +298,14 @@ export interface CompanySkillCreateRequest {
slug?: string | null;
description?: string | null;
markdown?: string | null;
+ iconUrl?: string | null;
+ color?: string | null;
+ tagline?: string | null;
+ authorName?: string | null;
+ homepageUrl?: string | null;
+ categories?: string[];
+ sharingScope?: CompanySkillSharingScope;
+ forkedFromSkillId?: string | null;
}
export interface CompanySkillFileDetail {
diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts
index 5fc8b5f8df..ffc265520c 100644
--- a/packages/shared/src/types/index.ts
+++ b/packages/shared/src/types/index.ts
@@ -60,11 +60,24 @@ export type {
CompanySkillTrustLevel,
CompanySkillCompatibility,
CompanySkillSourceBadge,
+ CompanySkillSharingScope,
+ CompanySkillListSort,
CompanySkillFileInventoryEntry,
+ CompanySkillVersionFileInventoryEntry,
CompanySkill,
CompanySkillListItem,
CompanySkillUsageAgent,
CompanySkillDetail,
+ CompanySkillListQuery,
+ CompanySkillCategoryCount,
+ CompanySkillVersion,
+ CompanySkillVersionCreateRequest,
+ CompanySkillStarResult,
+ CompanySkillComment,
+ CompanySkillCommentCreateRequest,
+ CompanySkillCommentUpdateRequest,
+ CompanySkillForkRequest,
+ CompanySkillUpdateRequest,
CompanySkillUpdateStatus,
CompanySkillAuditSeverity,
CompanySkillAuditVerdict,
@@ -120,6 +133,7 @@ export type {
AgentSkillSyncMode,
AgentSkillState,
AgentSkillOrigin,
+ AgentDesiredSkillEntry,
AgentSkillEntry,
AgentSkillSnapshot,
AgentSkillSyncRequest,
diff --git a/packages/shared/src/validators/adapter-skills.ts b/packages/shared/src/validators/adapter-skills.ts
index 84fa0f72cc..95c25c2585 100644
--- a/packages/shared/src/validators/adapter-skills.ts
+++ b/packages/shared/src/validators/adapter-skills.ts
@@ -22,9 +22,21 @@ export const agentSkillSyncModeSchema = z.enum([
"ephemeral",
]);
+export const agentDesiredSkillEntrySchema = z.object({
+ key: z.string().min(1),
+ versionId: z.string().uuid().nullable(),
+});
+
+export const agentDesiredSkillSelectionSchema = z.union([
+ z.string().min(1),
+ agentDesiredSkillEntrySchema,
+]);
+
export const agentSkillEntrySchema = z.object({
key: z.string().min(1),
runtimeName: z.string().min(1).nullable(),
+ versionId: z.string().uuid().nullable().optional(),
+ currentVersionId: z.string().uuid().nullable().optional(),
desired: z.boolean(),
managed: z.boolean(),
required: z.boolean().optional(),
@@ -44,12 +56,13 @@ export const agentSkillSnapshotSchema = z.object({
supported: z.boolean(),
mode: agentSkillSyncModeSchema,
desiredSkills: z.array(z.string().min(1)),
+ desiredSkillEntries: z.array(agentDesiredSkillEntrySchema).optional(),
entries: z.array(agentSkillEntrySchema),
warnings: z.array(z.string()),
});
export const agentSkillSyncSchema = z.object({
- desiredSkills: z.array(z.string().min(1)),
+ desiredSkills: z.array(agentDesiredSkillSelectionSchema),
});
export type AgentSkillSync = z.infer<typeof agentSkillSyncSchema>;
diff --git a/packages/shared/src/validators/agent.ts b/packages/shared/src/validators/agent.ts
index 4aa64c2aa0..e7eff192ce 100644
--- a/packages/shared/src/validators/agent.ts
+++ b/packages/shared/src/validators/agent.ts
@@ -8,6 +8,7 @@ import {
import { agentAdapterTypeSchema } from "../adapter-type.js";
import { envConfigSchema } from "./secret.js";
import { trustAuthorizationPolicySchema, trustPresetSchema } from "./trust-policy.js";
+import { agentDesiredSkillSelectionSchema } from "./adapter-skills.js";
export const agentPermissionsSchema = z.object({
canCreateAgents: z.boolean().optional().default(false),
@@ -73,7 +74,7 @@ export const createAgentSchema = z.object({
icon: z.enum(AGENT_ICON_NAMES).optional().nullable(),
reportsTo: z.string().uuid().optional().nullable(),
capabilities: z.string().optional().nullable(),
- desiredSkills: z.array(z.string().min(1)).optional(),
+ desiredSkills: z.array(agentDesiredSkillSelectionSchema).optional(),
adapterType: agentAdapterTypeSchema,
adapterConfig: adapterConfigSchema.optional().default({}),
instructionsBundle: createAgentInstructionsBundleSchema.optional(),
diff --git a/packages/shared/src/validators/company-skill.test.ts b/packages/shared/src/validators/company-skill.test.ts
index 20965e63b0..ec28e5f933 100644
--- a/packages/shared/src/validators/company-skill.test.ts
+++ b/packages/shared/src/validators/company-skill.test.ts
@@ -54,6 +54,20 @@ const companySkill = {
trustLevel: "markdown_only",
compatibility: "compatible",
fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ iconUrl: null,
+ color: null,
+ tagline: null,
+ authorName: null,
+ homepageUrl: null,
+ categories: [],
+ sharingScope: "private",
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 0,
+ installCount: 1,
+ forkCount: 0,
+ currentVersionId: null,
metadata: {
sourceKind: "catalog",
catalogId: catalogSkill.id,
diff --git a/packages/shared/src/validators/company-skill.ts b/packages/shared/src/validators/company-skill.ts
index a0bbb7325c..ff223dd60f 100644
--- a/packages/shared/src/validators/company-skill.ts
+++ b/packages/shared/src/validators/company-skill.ts
@@ -4,12 +4,18 @@ export const companySkillSourceTypeSchema = z.enum(["local_path", "github", "url
export const companySkillTrustLevelSchema = z.enum(["markdown_only", "assets", "scripts_executables"]);
export const companySkillCompatibilitySchema = z.enum(["compatible", "unknown", "invalid"]);
export const companySkillSourceBadgeSchema = z.enum(["paperclip", "github", "local", "url", "catalog", "skills_sh"]);
+export const companySkillSharingScopeSchema = z.enum(["private", "company", "public_link"]);
+export const companySkillListSortSchema = z.enum(["alphabetical", "recent", "installs", "stars", "agents", "forks"]);
export const companySkillFileInventoryEntrySchema = z.object({
path: z.string().min(1),
kind: z.enum(["skill", "markdown", "reference", "script", "asset", "other"]),
});
+export const companySkillVersionFileInventoryEntrySchema = companySkillFileInventoryEntrySchema.extend({
+ content: z.string(),
+});
+
export const companySkillSchema = z.object({
id: z.string().uuid(),
companyId: z.string().uuid(),
@@ -24,6 +30,20 @@ export const companySkillSchema = z.object({
trustLevel: companySkillTrustLevelSchema,
compatibility: companySkillCompatibilitySchema,
fileInventory: z.array(companySkillFileInventoryEntrySchema).default([]),
+ iconUrl: z.string().nullable(),
+ color: z.string().nullable(),
+ tagline: z.string().nullable(),
+ authorName: z.string().nullable(),
+ homepageUrl: z.string().nullable(),
+ categories: z.array(z.string().min(1)).default([]),
+ sharingScope: companySkillSharingScopeSchema,
+ publicShareToken: z.string().nullable(),
+ forkedFromSkillId: z.string().uuid().nullable(),
+ forkedFromCompanyId: z.string().uuid().nullable(),
+ starCount: z.number().int().nonnegative(),
+ installCount: z.number().int().nonnegative(),
+ forkCount: z.number().int().nonnegative(),
+ currentVersionId: z.string().uuid().nullable(),
metadata: z.record(z.string(), z.unknown()).nullable(),
createdAt: z.coerce.date(),
updatedAt: z.coerce.date(),
@@ -50,6 +70,31 @@ export const companySkillUsageAgentSchema = z.object({
actualState: z.string().nullable().describe(
"Runtime adapter skill state when explicitly fetched; company skill detail reads return null without probing agent runtimes.",
),
+ versionId: z.string().uuid().nullable(),
+});
+
+export const companySkillListQuerySchema = z.object({
+ q: z.string().min(1).optional(),
+ sort: companySkillListSortSchema.optional(),
+ categories: z.array(z.string().min(1)).optional(),
+ scope: companySkillSharingScopeSchema.optional(),
+});
+
+export const companySkillCategoryCountSchema = z.object({
+ slug: z.string().min(1),
+ count: z.number().int().nonnegative(),
+});
+
+export const companySkillVersionSchema = z.object({
+ id: z.string().uuid(),
+ companyId: z.string().uuid(),
+ companySkillId: z.string().uuid(),
+ revisionNumber: z.number().int().positive(),
+ label: z.string().nullable(),
+ fileInventory: z.array(companySkillVersionFileInventoryEntrySchema).default([]),
+ authorAgentId: z.string().uuid().nullable(),
+ authorUserId: z.string().nullable(),
+ createdAt: z.coerce.date(),
});
export const companySkillDetailSchema = companySkillSchema.extend({
@@ -59,8 +104,59 @@ export const companySkillDetailSchema = companySkillSchema.extend({
editableReason: z.string().nullable(),
sourceLabel: z.string().nullable(),
sourceBadge: companySkillSourceBadgeSchema,
+ currentVersion: companySkillVersionSchema.nullable(),
+ starredByCurrentActor: z.boolean(),
});
+export const companySkillVersionCreateSchema = z.object({
+ label: z.string().trim().min(1).nullable().optional(),
+}).default({});
+
+export const companySkillStarResultSchema = z.object({
+ skillId: z.string().uuid(),
+ starred: z.boolean(),
+ starCount: z.number().int().nonnegative(),
+});
+
+export const companySkillCommentSchema = z.object({
+ id: z.string().uuid(),
+ companyId: z.string().uuid(),
+ companySkillId: z.string().uuid(),
+ parentCommentId: z.string().uuid().nullable(),
+ authorAgentId: z.string().uuid().nullable(),
+ authorUserId: z.string().nullable(),
+ body: z.string(),
+ deletedAt: z.coerce.date().nullable(),
+ createdAt: z.coerce.date(),
+ updatedAt: z.coerce.date(),
+});
+
+export const companySkillCommentCreateSchema = z.object({
+ body: z.string().min(1),
+ parentCommentId: z.string().uuid().nullable().optional(),
+});
+
+export const companySkillCommentUpdateSchema = z.object({
+ body: z.string().min(1),
+});
+
+export const companySkillForkSchema = z.object({
+ name: z.string().min(1).nullable().optional(),
+ slug: z.string().min(1).nullable().optional(),
+ sharingScope: companySkillSharingScopeSchema.optional(),
+}).default({});
+
+export const companySkillUpdateSchema = z.object({
+ description: z.string().nullable().optional(),
+ iconUrl: z.string().nullable().optional(),
+ color: z.string().nullable().optional(),
+ tagline: z.string().max(120).nullable().optional(),
+ authorName: z.string().nullable().optional(),
+ homepageUrl: z.string().nullable().optional(),
+ categories: z.array(z.string().min(1)).optional(),
+ sharingScope: companySkillSharingScopeSchema.optional(),
+}).default({});
+
export const companySkillUpdateStatusSchema = z.object({
supported: z.boolean(),
reason: z.string().nullable(),
@@ -156,6 +252,14 @@ export const companySkillCreateSchema = z.object({
slug: z.string().min(1).nullable().optional(),
description: z.string().nullable().optional(),
markdown: z.string().nullable().optional(),
+ iconUrl: z.string().nullable().optional(),
+ color: z.string().nullable().optional(),
+ tagline: z.string().max(120).nullable().optional(),
+ authorName: z.string().nullable().optional(),
+ homepageUrl: z.string().nullable().optional(),
+ categories: z.array(z.string().min(1)).optional(),
+ sharingScope: companySkillSharingScopeSchema.optional(),
+ forkedFromSkillId: z.string().uuid().nullable().optional(),
});
export const companySkillFileDetailSchema = z.object({
@@ -247,9 +351,15 @@ export const companySkillInstallCatalogResultSchema = z.object({
});
export type CompanySkillImport = z.infer<typeof companySkillImportSchema>;
+export type CompanySkillListQuery = z.infer<typeof companySkillListQuerySchema>;
export type CompanySkillProjectScan = z.infer<typeof companySkillProjectScanRequestSchema>;
export type CompanySkillCreate = z.infer<typeof companySkillCreateSchema>;
export type CompanySkillFileUpdate = z.infer<typeof companySkillFileUpdateSchema>;
+export type CompanySkillVersionCreate = z.infer<typeof companySkillVersionCreateSchema>;
+export type CompanySkillCommentCreate = z.infer<typeof companySkillCommentCreateSchema>;
+export type CompanySkillCommentUpdate = z.infer<typeof companySkillCommentUpdateSchema>;
+export type CompanySkillFork = z.infer<typeof companySkillForkSchema>;
+export type CompanySkillUpdate = z.infer<typeof companySkillUpdateSchema>;
export type CatalogSkillListQuery = z.infer<typeof catalogSkillListQuerySchema>;
export type CompanySkillInstallCatalog = z.infer<typeof companySkillInstallCatalogSchema>;
export type CompanySkillInstallUpdate = z.infer<typeof companySkillInstallUpdateSchema>;
diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts
index 683950de77..9b170e8114 100644
--- a/packages/shared/src/validators/index.ts
+++ b/packages/shared/src/validators/index.ts
@@ -61,11 +61,24 @@ export {
companySkillTrustLevelSchema,
companySkillCompatibilitySchema,
companySkillSourceBadgeSchema,
+ companySkillSharingScopeSchema,
+ companySkillListSortSchema,
companySkillFileInventoryEntrySchema,
+ companySkillVersionFileInventoryEntrySchema,
companySkillSchema,
companySkillListItemSchema,
companySkillUsageAgentSchema,
+ companySkillListQuerySchema,
+ companySkillCategoryCountSchema,
+ companySkillVersionSchema,
companySkillDetailSchema,
+ companySkillVersionCreateSchema,
+ companySkillStarResultSchema,
+ companySkillCommentSchema,
+ companySkillCommentCreateSchema,
+ companySkillCommentUpdateSchema,
+ companySkillForkSchema,
+ companySkillUpdateSchema,
companySkillUpdateStatusSchema,
companySkillAuditFindingSchema,
companySkillAuditResultSchema,
@@ -89,9 +102,14 @@ export {
companySkillInstallUpdateSchema,
companySkillResetSchema,
type CompanySkillImport,
+ type CompanySkillListQuery,
type CompanySkillProjectScan,
type CompanySkillCreate,
type CompanySkillFileUpdate,
+ type CompanySkillVersionCreate,
+ type CompanySkillCommentCreate,
+ type CompanySkillCommentUpdate,
+ type CompanySkillFork,
type CatalogSkillListQuery,
type CompanySkillInstallCatalog,
type CompanySkillInstallUpdate,
@@ -121,6 +139,8 @@ export {
export {
agentSkillStateSchema,
agentSkillSyncModeSchema,
+ agentDesiredSkillEntrySchema,
+ agentDesiredSkillSelectionSchema,
agentSkillEntrySchema,
agentSkillSnapshotSchema,
agentSkillSyncSchema,
diff --git a/server/src/__tests__/agent-skills-routes.test.ts b/server/src/__tests__/agent-skills-routes.test.ts
index 07c40f7cf3..1ba32715fa 100644
--- a/server/src/__tests__/agent-skills-routes.test.ts
+++ b/server/src/__tests__/agent-skills-routes.test.ts
@@ -44,6 +44,7 @@ const mockAgentInstructionsService = vi.hoisted(() => ({
const mockCompanySkillService = vi.hoisted(() => ({
listRuntimeSkillEntries: vi.fn(),
+ resolveRequestedSkillEntries: vi.fn(),
resolveRequestedSkillKeys: vi.fn(),
}));
@@ -258,6 +259,13 @@ describe.sequential("agent skill routes", () => {
: value,
),
);
+ mockCompanySkillService.resolveRequestedSkillEntries.mockImplementation(
+ async (_companyId: string, requested: Array<{ key: string; versionId?: string | null }>) =>
+ requested.map((entry) => ({
+ key: entry.key === "paperclip" ? "paperclipai/paperclip/paperclip" : entry.key,
+ versionId: entry.versionId ?? null,
+ })),
+ );
mockAdapter.listSkills.mockResolvedValue({
adapterType: "claude_local",
supported: true,
@@ -338,9 +346,10 @@ describe.sequential("agent skill routes", () => {
);
expect(res.status, JSON.stringify(res.body)).toBe(200);
- expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", {
+ expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", expect.objectContaining({
materializeMissing: false,
- });
+ versionSelections: expect.any(Map),
+ }));
expect(mockAdapter.listSkills).toHaveBeenCalledWith(
expect.objectContaining({
adapterType: "claude_local",
@@ -369,9 +378,10 @@ describe.sequential("agent skill routes", () => {
);
expect(res.status, JSON.stringify(res.body)).toBe(200);
- expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", {
+ expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", expect.objectContaining({
materializeMissing: false,
- });
+ versionSelections: expect.any(Map),
+ }));
});
it("passes ACPX Claude config through the agent skill listing route", async () => {
@@ -398,9 +408,10 @@ describe.sequential("agent skill routes", () => {
);
expect(res.status, JSON.stringify(res.body)).toBe(200);
- expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", {
+ expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", expect.objectContaining({
materializeMissing: false,
- });
+ versionSelections: expect.any(Map),
+ }));
expect(mockAdapter.listSkills).toHaveBeenCalledWith(
expect.objectContaining({
adapterType: "acpx_local",
@@ -485,9 +496,10 @@ describe.sequential("agent skill routes", () => {
);
expect(res.status, JSON.stringify(res.body)).toBe(200);
- expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", {
+ expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", expect.objectContaining({
materializeMissing: false,
- });
+ versionSelections: expect.any(Map),
+ }));
});
it("skips runtime materialization when syncing Claude skills", async () => {
diff --git a/server/src/__tests__/company-skills-routes.test.ts b/server/src/__tests__/company-skills-routes.test.ts
index 1545ef637e..acd567a074 100644
--- a/server/src/__tests__/company-skills-routes.test.ts
+++ b/server/src/__tests__/company-skills-routes.test.ts
@@ -12,6 +12,19 @@ const mockAccessService = vi.hoisted(() => ({
}));
const mockCompanySkillService = vi.hoisted(() => ({
+ list: vi.fn(),
+ categoryCounts: vi.fn(),
+ detail: vi.fn(),
+ listVersions: vi.fn(),
+ getVersion: vi.fn(),
+ createVersion: vi.fn(),
+ starSkill: vi.fn(),
+ unstarSkill: vi.fn(),
+ forkSkill: vi.fn(),
+ listComments: vi.fn(),
+ createComment: vi.fn(),
+ updateComment: vi.fn(),
+ deleteComment: vi.fn(),
importFromSource: vi.fn(),
installFromCatalog: vi.fn(),
deleteSkill: vi.fn(),
@@ -102,6 +115,101 @@ describe("company skill mutation permissions", () => {
imported: [],
warnings: [],
});
+ mockCompanySkillService.list.mockResolvedValue([]);
+ mockCompanySkillService.categoryCounts.mockResolvedValue([]);
+ mockCompanySkillService.detail.mockResolvedValue(null);
+ mockCompanySkillService.listVersions.mockResolvedValue([]);
+ mockCompanySkillService.getVersion.mockResolvedValue(null);
+ mockCompanySkillService.createVersion.mockResolvedValue({
+ id: "version-1",
+ companyId: "company-1",
+ companySkillId: "skill-1",
+ revisionNumber: 1,
+ label: "v1",
+ fileInventory: [{ path: "SKILL.md", kind: "skill", content: "# Skill" }],
+ authorAgentId: null,
+ authorUserId: "board",
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ });
+ mockCompanySkillService.starSkill.mockResolvedValue({
+ skillId: "skill-1",
+ starred: true,
+ starCount: 1,
+ });
+ mockCompanySkillService.unstarSkill.mockResolvedValue({
+ skillId: "skill-1",
+ starred: false,
+ starCount: 0,
+ });
+ mockCompanySkillService.forkSkill.mockResolvedValue({
+ id: "skill-fork",
+ companyId: "company-1",
+ key: "company/company-1/review-fork",
+ slug: "review-fork",
+ name: "Review Fork",
+ description: null,
+ markdown: "# Review",
+ sourceType: "local_path",
+ sourceLocator: "/tmp/review-fork",
+ sourceRef: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ iconUrl: null,
+ color: null,
+ tagline: null,
+ authorName: null,
+ homepageUrl: null,
+ categories: [],
+ sharingScope: "company",
+ publicShareToken: null,
+ forkedFromSkillId: "skill-1",
+ forkedFromCompanyId: "company-1",
+ starCount: 0,
+ installCount: 1,
+ forkCount: 0,
+ currentVersionId: null,
+ metadata: null,
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:00:00.000Z"),
+ });
+ mockCompanySkillService.listComments.mockResolvedValue([]);
+ mockCompanySkillService.createComment.mockResolvedValue({
+ id: "comment-1",
+ companyId: "company-1",
+ companySkillId: "skill-1",
+ parentCommentId: null,
+ authorAgentId: null,
+ authorUserId: "board",
+ body: "Looks good",
+ deletedAt: null,
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:00:00.000Z"),
+ });
+ mockCompanySkillService.updateComment.mockResolvedValue({
+ id: "comment-1",
+ companyId: "company-1",
+ companySkillId: "skill-1",
+ parentCommentId: null,
+ authorAgentId: null,
+ authorUserId: "board",
+ body: "Updated",
+ deletedAt: null,
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:00:00.000Z"),
+ });
+ mockCompanySkillService.deleteComment.mockResolvedValue({
+ id: "comment-1",
+ companyId: "company-1",
+ companySkillId: "skill-1",
+ parentCommentId: null,
+ authorAgentId: null,
+ authorUserId: "board",
+ body: "Updated",
+ deletedAt: new Date("2026-05-26T00:01:00.000Z"),
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:01:00.000Z"),
+ });
mockCompanySkillService.installFromCatalog.mockResolvedValue({
action: "created",
skill: {
@@ -484,6 +592,88 @@ describe("company skill mutation permissions", () => {
expect(mockCompanySkillService.installFromCatalog).not.toHaveBeenCalled();
});
+ it("passes store list filters and category count requests to the service", async () => {
+ const app = await createApp({ type: "board", source: "local_implicit" });
+
+ await request(app)
+ .get("/api/companies/company-1/skills?sort=stars&categories[]=memory&category=git&scope=company&q=review")
+ .expect(200);
+ expect(mockCompanySkillService.list).toHaveBeenCalledWith("company-1", {
+ q: "review",
+ sort: "stars",
+ categories: ["git", "memory"],
+ scope: "company",
+ });
+
+ await request(app).get("/api/companies/company-1/skills/categories").expect(200);
+ expect(mockCompanySkillService.categoryCounts).toHaveBeenCalledWith("company-1");
+ });
+
+ it("creates skill versions and logs the mutation", async () => {
+ const app = await createApp({ type: "board", source: "local_implicit", userId: "user-1" });
+
+ await request(app)
+ .post("/api/companies/company-1/skills/skill-1/versions")
+ .send({ label: "v1" })
+ .expect(201);
+
+ expect(mockCompanySkillService.createVersion).toHaveBeenCalledWith("company-1", "skill-1", { label: "v1" }, {
+ type: "user",
+ userId: "user-1",
+ });
+ expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ action: "company.skill_version_created",
+ entityType: "company_skill_version",
+ entityId: "version-1",
+ }));
+ });
+
+ it("stars, forks, and comments on skills through company-scoped endpoints", async () => {
+ const app = await createApp({ type: "board", source: "local_implicit", userId: "user-1" });
+
+ await request(app).post("/api/companies/company-1/skills/skill-1/star").send({}).expect(200);
+ expect(mockCompanySkillService.starSkill).toHaveBeenCalledWith("company-1", "skill-1", {
+ type: "user",
+ userId: "user-1",
+ });
+
+ await request(app).post("/api/companies/company-1/skills/skill-1/fork").send({ slug: "review-fork" }).expect(201);
+ expect(mockCompanySkillService.forkSkill).toHaveBeenCalledWith("company-1", "skill-1", { slug: "review-fork" }, {
+ type: "user",
+ userId: "user-1",
+ });
+
+ await request(app).post("/api/companies/company-1/skills/skill-1/comments").send({ body: "Looks good" }).expect(201);
+ expect(mockCompanySkillService.createComment).toHaveBeenCalledWith("company-1", "skill-1", { body: "Looks good" }, {
+ type: "user",
+ userId: "user-1",
+ });
+
+ expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ action: "company.skill_starred",
+ entityId: "skill-1",
+ }));
+ expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ action: "company.skill_forked",
+ entityId: "skill-fork",
+ }));
+ expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ action: "company.skill_comment_created",
+ entityId: "comment-1",
+ }));
+ });
+
+ it("does not synthesize a shared board user id for board actors without user ids", async () => {
+ const app = await createApp({ type: "board", source: "local_implicit" });
+
+ await request(app).post("/api/companies/company-1/skills/skill-1/star").send({}).expect(200);
+
+ expect(mockCompanySkillService.starSkill).toHaveBeenCalledWith("company-1", "skill-1", {
+ type: "user",
+ userId: null,
+ });
+ });
+
it("allows agents with canCreateAgents to mutate company skills", async () => {
mockAgentService.getById.mockResolvedValue({
id: "agent-1",
diff --git a/server/src/__tests__/company-skills-service.test.ts b/server/src/__tests__/company-skills-service.test.ts
index 88be5f595b..52d098e275 100644
--- a/server/src/__tests__/company-skills-service.test.ts
+++ b/server/src/__tests__/company-skills-service.test.ts
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
import os from "node:os";
import path from "node:path";
import { promises as fs } from "node:fs";
-import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, companies, companySkills, createDb } from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
@@ -143,6 +143,339 @@ describeEmbeddedPostgres("companySkillService.list", () => {
});
});
+ it("filters store list results by category and creates version snapshots", async () => {
+ const companyId = randomUUID();
+ const skillId = randomUUID();
+ const skillDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-versioned-skill-"));
+ cleanupDirs.add(skillDir);
+ await fs.writeFile(path.join(skillDir, "SKILL.md"), "---\nname: Versioned Skill\ncategories:\n - Memory\n---\n\n# Versioned Skill\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(companySkills).values({
+ id: skillId,
+ companyId,
+ key: `company/${companyId}/versioned-skill`,
+ slug: "versioned-skill",
+ name: "Versioned Skill",
+ description: "Tracks revisions.",
+ markdown: "# Versioned Skill",
+ sourceType: "local_path",
+ sourceLocator: skillDir,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ categories: ["memory"],
+ tagline: "Tracks revisions",
+ });
+
+ const filtered = await svc.list(companyId, { categories: ["memory"], sort: "recent" });
+ expect(filtered.some((skill) => skill.id === skillId)).toBe(true);
+ expect(filtered.find((skill) => skill.id === skillId)).toMatchObject({
+ categories: ["memory"],
+ tagline: "Tracks revisions",
+ });
+
+ const version = await svc.createVersion(companyId, skillId, { label: "v1" }, { type: "user", userId: "board" });
+ expect(version).toMatchObject({
+ companySkillId: skillId,
+ revisionNumber: 1,
+ label: "v1",
+ authorUserId: "board",
+ });
+ expect(version.fileInventory).toEqual([
+ expect.objectContaining({
+ path: "SKILL.md",
+ kind: "skill",
+ content: expect.stringContaining("# Versioned Skill"),
+ }),
+ ]);
+ await expect(svc.getVersion(companyId, skillId, version.id)).resolves.toMatchObject({ id: version.id });
+ });
+
+ it("tracks stars and skill comments with actor ownership", async () => {
+ const companyId = randomUUID();
+ const skillId = randomUUID();
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(companySkills).values({
+ id: skillId,
+ companyId,
+ key: `company/${companyId}/discussion-skill`,
+ slug: "discussion-skill",
+ name: "Discussion Skill",
+ description: null,
+ markdown: "# Discussion Skill",
+ sourceType: "local_path",
+ sourceLocator: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ });
+
+ await expect(svc.starSkill(companyId, skillId, { type: "user", userId: "board" })).resolves.toMatchObject({
+ starred: true,
+ starCount: 1,
+ });
+ await expect(svc.starSkill(companyId, skillId, { type: "user", userId: "board" })).resolves.toMatchObject({
+ starred: true,
+ starCount: 1,
+ });
+ await expect(svc.starSkill(companyId, skillId, { type: "user", userId: null })).rejects.toMatchObject({
+ status: 422,
+ });
+ const comment = await svc.createComment(
+ companyId,
+ skillId,
+ { body: "Looks useful." },
+ { type: "user", userId: "board" },
+ );
+ expect(comment).toMatchObject({ body: "Looks useful.", authorUserId: "board" });
+ await expect(svc.updateComment(
+ companyId,
+ skillId,
+ comment.id,
+ { body: "Looks very useful." },
+ { type: "agent", agentId: randomUUID() },
+ )).rejects.toMatchObject({ status: 422 });
+ await expect(svc.deleteComment(companyId, skillId, comment.id, { type: "user", userId: "board" }))
+ .resolves.toMatchObject({ id: comment.id, deletedAt: expect.any(Date) });
+ await expect(svc.listComments(companyId, skillId)).resolves.toEqual([]);
+ await expect(svc.updateComment(
+ companyId,
+ skillId,
+ comment.id,
+ { body: "Resurrected." },
+ { type: "user", userId: "board" },
+ )).rejects.toMatchObject({ status: 404 });
+ await expect(svc.deleteComment(companyId, skillId, comment.id, { type: "user", userId: "board" }))
+ .rejects.toMatchObject({ status: 404 });
+ await expect(svc.createComment(
+ companyId,
+ skillId,
+ { body: "Reply after delete.", parentCommentId: comment.id },
+ { type: "user", userId: "board" },
+ )).rejects.toMatchObject({ status: 404 });
+ await expect(svc.unstarSkill(companyId, skillId, { type: "user", userId: "board" })).resolves.toMatchObject({
+ starred: false,
+ starCount: 0,
+ });
+ });
+
+ it("updates private/company sharing scope and rejects public link publishing", 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 skill = await svc.createLocalSkill(companyId, {
+ name: "Sharing Skill",
+ tagline: "A scoped skill",
+ sharingScope: "company",
+ });
+
+ await expect(svc.updateSkill(companyId, skill.id, { sharingScope: "private" })).resolves.toMatchObject({
+ id: skill.id,
+ sharingScope: "private",
+ publicShareToken: null,
+ });
+ await expect(svc.updateSkill(companyId, skill.id, { sharingScope: "public_link" })).rejects.toMatchObject({
+ status: 422,
+ message: "Public skill sharing is not available in this version.",
+ });
+ await expect(svc.createLocalSkill(companyId, {
+ name: "Public Skill",
+ sharingScope: "public_link",
+ })).rejects.toMatchObject({
+ status: 422,
+ message: "Public skill sharing is not available in this version.",
+ });
+ });
+
+ it("creates a fork from the creation flow with copied files and lineage", async () => {
+ const companyId = randomUUID();
+ const sourceSkillId = randomUUID();
+ const sourceSkillDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-source-fork-skill-"));
+ cleanupDirs.add(sourceSkillDir);
+ await fs.mkdir(path.join(sourceSkillDir, "references"), { recursive: true });
+ await fs.writeFile(
+ path.join(sourceSkillDir, "SKILL.md"),
+ "---\nname: Source Skill\ndescription: Source description\n---\n\n# Source Skill\n",
+ "utf8",
+ );
+ await fs.writeFile(path.join(sourceSkillDir, "references", "guide.md"), "# Guide\n\nOriginal notes.\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(companySkills).values({
+ id: sourceSkillId,
+ companyId,
+ key: `company/${companyId}/source-skill`,
+ slug: "source-skill",
+ name: "Source Skill",
+ description: "Source description",
+ markdown: "---\nname: Source Skill\ndescription: Source description\n---\n\n# Source Skill\n",
+ sourceType: "local_path",
+ sourceLocator: sourceSkillDir,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [
+ { path: "SKILL.md", kind: "skill" },
+ { path: "references/guide.md", kind: "reference" },
+ ],
+ color: "#0ea5e9",
+ categories: ["engineering"],
+ sharingScope: "company",
+ metadata: { sourceKind: "managed_local" },
+ });
+
+ const forked = await svc.createLocalSkill(companyId, {
+ name: "Source Skill Fork",
+ slug: "source-skill-fork",
+ markdown: "---\nname: Source Skill Fork\ndescription: Fork description\n---\n\n# Forked Skill\n",
+ tagline: "Forked for the team",
+ color: "#ef4444",
+ categories: ["review"],
+ sharingScope: "private",
+ forkedFromSkillId: sourceSkillId,
+ }, { type: "user", userId: "board" });
+
+ expect(forked).toMatchObject({
+ name: "Source Skill Fork",
+ slug: "source-skill-fork",
+ sharingScope: "private",
+ forkedFromSkillId: sourceSkillId,
+ forkedFromCompanyId: companyId,
+ color: "#ef4444",
+ tagline: "Forked for the team",
+ categories: ["review"],
+ });
+ expect(forked.fileInventory.map((entry) => entry.path).sort()).toEqual(["SKILL.md", "references/guide.md"]);
+ await expect(svc.readFile(companyId, forked.id, "references/guide.md")).resolves.toMatchObject({
+ content: expect.stringContaining("Original notes."),
+ });
+ await expect(svc.getById(companyId, sourceSkillId)).resolves.toMatchObject({
+ forkCount: 1,
+ installCount: 1,
+ });
+ await expect(svc.getById(companyId, forked.id)).resolves.toMatchObject({
+ metadata: expect.objectContaining({
+ forkedFromSkillId: sourceSkillId,
+ forkedFromCompanyId: companyId,
+ forkedByUserId: "board",
+ }),
+ });
+ const versions = await svc.listVersions(companyId, forked.id);
+ expect(versions).toHaveLength(1);
+ expect(versions[0]).toMatchObject({
+ revisionNumber: 1,
+ label: "Initial version",
+ authorUserId: "board",
+ });
+
+ const dedicatedFork = await svc.forkSkill(
+ companyId,
+ sourceSkillId,
+ { name: "Dedicated Fork", slug: "dedicated-fork", sharingScope: "private" },
+ { type: "user", userId: "board" },
+ );
+ expect(dedicatedFork).toMatchObject({
+ name: "Source Skill",
+ slug: "dedicated-fork",
+ sharingScope: "private",
+ forkedFromSkillId: sourceSkillId,
+ forkedFromCompanyId: companyId,
+ currentVersionId: expect.any(String),
+ });
+ const dedicatedVersions = await svc.listVersions(companyId, dedicatedFork.id);
+ expect(dedicatedVersions).toHaveLength(1);
+ expect(dedicatedVersions[0]).toMatchObject({
+ revisionNumber: 1,
+ label: "Initial version",
+ authorUserId: "board",
+ });
+ });
+
+ it("validates version-aware desired skill selections", async () => {
+ const companyId = randomUUID();
+ const skillId = randomUUID();
+ const otherSkillId = randomUUID();
+ const skillDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-pinned-skill-"));
+ cleanupDirs.add(skillDir);
+ await fs.writeFile(path.join(skillDir, "SKILL.md"), "# Pinned Skill\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(companySkills).values([
+ {
+ id: skillId,
+ companyId,
+ key: `company/${companyId}/pinned-skill`,
+ slug: "pinned-skill",
+ name: "Pinned Skill",
+ description: null,
+ markdown: "# Pinned Skill",
+ sourceType: "local_path",
+ sourceLocator: skillDir,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ },
+ {
+ id: otherSkillId,
+ companyId,
+ key: `company/${companyId}/other-skill`,
+ slug: "other-skill",
+ name: "Other Skill",
+ description: null,
+ markdown: "# Other Skill",
+ sourceType: "local_path",
+ sourceLocator: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ },
+ ]);
+ const version = await svc.createVersion(companyId, skillId, {}, { type: "user", userId: "board" });
+
+ await expect(svc.resolveRequestedSkillEntries(companyId, [
+ "pinned-skill",
+ ])).resolves.toEqual([
+ { key: `company/${companyId}/pinned-skill`, versionId: null },
+ ]);
+ await expect(svc.resolveRequestedSkillEntries(companyId, [
+ { key: "pinned-skill", versionId: null },
+ ])).resolves.toEqual([
+ { key: `company/${companyId}/pinned-skill`, versionId: null },
+ ]);
+ await expect(svc.resolveRequestedSkillEntries(companyId, [
+ { key: "pinned-skill", versionId: version.id },
+ ])).resolves.toEqual([
+ { key: `company/${companyId}/pinned-skill`, versionId: version.id },
+ ]);
+ await expect(svc.resolveRequestedSkillEntries(companyId, [
+ { key: "other-skill", versionId: version.id },
+ ])).rejects.toMatchObject({ status: 422 });
+ });
+
it("preserves missing local-path skills that active agents still desire", async () => {
const companyId = randomUUID();
const skillId = randomUUID();
@@ -279,6 +612,61 @@ describeEmbeddedPostgres("companySkillService.list", () => {
expect(rows.some((row) => row.companyId === companyId && row.slug === "evil")).toBe(false);
});
+ it("rejects unbundled package imports that claim reserved Paperclip skill keys", async () => {
+ const companyId = randomUUID();
+ const skillId = randomUUID();
+ const bundledSkillDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-bundled-skill-"));
+ cleanupDirs.add(bundledSkillDir);
+ await fs.writeFile(path.join(bundledSkillDir, "SKILL.md"), "---\nname: Paperclip\n---\n\n# Official Paperclip\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(companySkills).values({
+ id: skillId,
+ companyId,
+ key: "paperclipai/paperclip/paperclip",
+ slug: "paperclip",
+ name: "Paperclip",
+ description: "Official coordination skill.",
+ markdown: "---\nname: Paperclip\n---\n\n# Official Paperclip\n",
+ sourceType: "local_path",
+ sourceLocator: bundledSkillDir,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ metadata: { sourceKind: "paperclip_bundled" },
+ });
+
+ await expect(svc.importPackageFiles(companyId, {
+ "skills/trojan/SKILL.md": [
+ "---",
+ "name: Trojan Paperclip",
+ "metadata:",
+ " skillKey: paperclipai/paperclip/paperclip",
+ "---",
+ "",
+ "# Trojan Paperclip",
+ "",
+ ].join("\n"),
+ })).rejects.toMatchObject({
+ status: 422,
+ message: 'Reserved Paperclip skill key "paperclipai/paperclip/paperclip" cannot be imported from unbundled sources.',
+ });
+
+ const stored = await svc.getById(companyId, skillId);
+ expect(stored).toMatchObject({
+ id: skillId,
+ key: "paperclipai/paperclip/paperclip",
+ metadata: { sourceKind: "paperclip_bundled" },
+ });
+ expect(stored?.name).not.toBe("Trojan Paperclip");
+ expect(stored?.markdown).not.toContain("Trojan Paperclip");
+ });
+
it("clears the missing-source marker when a local-path skill source returns", async () => {
const companyId = randomUUID();
const skillId = randomUUID();
@@ -429,4 +817,216 @@ describeEmbeddedPostgres("companySkillService.list", () => {
"# Runtime Coach\n\nRecovered from DB.\n",
);
});
+
+ it("falls back to stored markdown when reading SKILL.md from a missing local source", async () => {
+ const companyId = randomUUID();
+ const skillId = randomUUID();
+ const skillKey = `company/${companyId}/missing-reader`;
+ const missingSkillDir = path.join(await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-missing-read-skill-")), "gone");
+ cleanupDirs.add(path.dirname(missingSkillDir));
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(companySkills).values({
+ id: skillId,
+ companyId,
+ key: skillKey,
+ slug: "missing-reader",
+ name: "Missing Reader",
+ description: null,
+ markdown: "# Missing Reader\n\nRecovered from DB.\n",
+ sourceType: "local_path",
+ sourceLocator: missingSkillDir,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [
+ { path: "SKILL.md", kind: "skill" },
+ { path: "references/guide.md", kind: "reference" },
+ ],
+ metadata: { sourceKind: "local_path" },
+ });
+ await db.insert(agents).values({
+ id: randomUUID(),
+ companyId,
+ name: "Reader",
+ role: "engineer",
+ status: "active",
+ adapterType: "codex_local",
+ adapterConfig: {
+ paperclipSkillSync: {
+ desiredSkills: [skillKey],
+ },
+ },
+ });
+
+ await expect(svc.readFile(companyId, skillId, "SKILL.md")).resolves.toMatchObject({
+ path: "SKILL.md",
+ content: "# Missing Reader\n\nRecovered from DB.\n",
+ });
+ await expect(svc.readFile(companyId, skillId, "references/guide.md")).rejects.toMatchObject({
+ status: 404,
+ });
+ });
+
+ it("reads root-level SKILL.md for github skills with a '.' repoSkillDir", async () => {
+ const companyId = randomUUID();
+ const skillId = randomUUID();
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(companySkills).values({
+ id: skillId,
+ companyId,
+ key: `company/${companyId}/root-skill`,
+ slug: "root-skill",
+ name: "Root Skill",
+ description: null,
+ markdown: "# Root Skill (stored)\n",
+ sourceType: "github",
+ sourceLocator: "https://github.com/acme/root-skill",
+ sourceRef: "main",
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ metadata: { owner: "acme", repo: "root-skill", ref: "main", repoSkillDir: "." },
+ });
+
+ const requestedUrls: string[] = [];
+ vi.stubGlobal("fetch", async (url: string | URL) => {
+ requestedUrls.push(String(url));
+ return new Response("# Root Skill (remote)\n", { status: 200 });
+ });
+ try {
+ await expect(svc.readFile(companyId, skillId, "SKILL.md")).resolves.toMatchObject({
+ content: "# Root Skill (remote)\n",
+ });
+ expect(requestedUrls).toEqual([
+ "https://raw.githubusercontent.com/acme/root-skill/main/SKILL.md",
+ ]);
+
+ vi.stubGlobal("fetch", async () => {
+ throw new Error("network down");
+ });
+ await expect(svc.readFile(companyId, skillId, "SKILL.md")).resolves.toMatchObject({
+ content: "# Root Skill (stored)\n",
+ });
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("falls back to slug paths for github skills only when repoSkillDir is absent", async () => {
+ const companyId = randomUUID();
+ const rootSkillId = randomUUID();
+ const slugSkillId = randomUUID();
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(companySkills).values([
+ {
+ id: rootSkillId,
+ companyId,
+ key: `company/${companyId}/empty-root-skill`,
+ slug: "empty-root-skill",
+ name: "Empty Root Skill",
+ description: null,
+ markdown: "# Empty Root Skill\n",
+ sourceType: "github",
+ sourceLocator: "https://github.com/acme/skills",
+ sourceRef: "main",
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ metadata: { owner: "acme", repo: "skills", ref: "main", repoSkillDir: "" },
+ },
+ {
+ id: slugSkillId,
+ companyId,
+ key: `company/${companyId}/slug-skill`,
+ slug: "slug-skill",
+ name: "Slug Skill",
+ description: null,
+ markdown: "# Slug Skill\n",
+ sourceType: "github",
+ sourceLocator: "https://github.com/acme/skills",
+ sourceRef: "main",
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ metadata: { owner: "acme", repo: "skills", ref: "main" },
+ },
+ ]);
+
+ const requestedUrls: string[] = [];
+ vi.stubGlobal("fetch", async (url: string | URL) => {
+ requestedUrls.push(String(url));
+ return new Response("# Remote Skill\n", { status: 200 });
+ });
+ try {
+ await expect(svc.readFile(companyId, rootSkillId, "SKILL.md")).resolves.toMatchObject({
+ content: "# Remote Skill\n",
+ });
+ await expect(svc.readFile(companyId, slugSkillId, "SKILL.md")).resolves.toMatchObject({
+ content: "# Remote Skill\n",
+ });
+ expect(requestedUrls).toEqual([
+ "https://raw.githubusercontent.com/acme/skills/main/SKILL.md",
+ "https://raw.githubusercontent.com/acme/skills/main/slug-skill/SKILL.md",
+ ]);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("seeds an initial version on create and snapshots a version on each changed save", 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 skill = await svc.createLocalSkill(
+ companyId,
+ { name: "Versioned Editor", description: "Edits with history" },
+ { type: "user", userId: "board" },
+ );
+ expect(skill.currentVersionId).not.toBeNull();
+ let versions = await svc.listVersions(companyId, skill.id);
+ expect(versions).toHaveLength(1);
+ expect(versions[0]).toMatchObject({
+ revisionNumber: 1,
+ label: "Initial version",
+ authorUserId: "board",
+ });
+ expect(skill.currentVersionId).toBe(versions[0]!.id);
+
+ const editedMarkdown = "---\nname: Versioned Editor\n---\n\n# Versioned Editor\n\nEdited body.\n";
+ await expect(svc.updateFile(companyId, skill.id, "SKILL.md", editedMarkdown, { type: "user", userId: "board" }))
+ .resolves.toMatchObject({ path: "SKILL.md", content: editedMarkdown });
+ versions = await svc.listVersions(companyId, skill.id);
+ expect(versions).toHaveLength(2);
+ expect(versions[0]).toMatchObject({ revisionNumber: 2, authorUserId: "board" });
+ expect(versions[0]!.fileInventory).toEqual([
+ expect.objectContaining({ path: "SKILL.md", content: editedMarkdown }),
+ ]);
+ await expect(svc.getById(companyId, skill.id)).resolves.toMatchObject({
+ currentVersionId: versions[0]!.id,
+ });
+
+ await svc.updateFile(companyId, skill.id, "SKILL.md", editedMarkdown, { type: "user", userId: "board" });
+ versions = await svc.listVersions(companyId, skill.id);
+ expect(versions).toHaveLength(2);
+ });
});
diff --git a/server/src/__tests__/heartbeat-project-env.test.ts b/server/src/__tests__/heartbeat-project-env.test.ts
index 1f62aa7619..2fde8594c6 100644
--- a/server/src/__tests__/heartbeat-project-env.test.ts
+++ b/server/src/__tests__/heartbeat-project-env.test.ts
@@ -333,4 +333,29 @@ describe("applyRunScopedMentionedSkillKeys", () => {
},
});
});
+
+ it("preserves existing version pins when adding mentioned skills", () => {
+ const originalConfig = {
+ command: "codex",
+ paperclipSkillSync: {
+ desiredSkills: [
+ { key: "company/company-1/release-changelog", versionId: "version-1" },
+ ],
+ },
+ };
+
+ const updatedConfig = applyRunScopedMentionedSkillKeys(originalConfig, [
+ "company/company-1/security-review",
+ ]);
+
+ expect(updatedConfig).toEqual({
+ command: "codex",
+ paperclipSkillSync: {
+ desiredSkills: [
+ { key: "company/company-1/release-changelog", versionId: "version-1" },
+ { key: "company/company-1/security-review", versionId: null },
+ ],
+ },
+ });
+ });
});
diff --git a/server/src/__tests__/heartbeat-runtime-skills.test.ts b/server/src/__tests__/heartbeat-runtime-skills.test.ts
new file mode 100644
index 0000000000..e5a5492846
--- /dev/null
+++ b/server/src/__tests__/heartbeat-runtime-skills.test.ts
@@ -0,0 +1,243 @@
+import { randomUUID } from "node:crypto";
+import os from "node:os";
+import path from "node:path";
+import { promises as fs } from "node:fs";
+import { eq, sql } from "drizzle-orm";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import { agents, companies, companySkills, createDb } from "@paperclipai/db";
+import type { PaperclipSkillEntry } from "@paperclipai/adapter-utils/server-utils";
+import {
+ getEmbeddedPostgresTestSupport,
+ startEmbeddedPostgresTestDatabase,
+} from "./helpers/embedded-postgres.js";
+import { companySkillService } from "../services/company-skills.ts";
+import { heartbeatService } from "../services/heartbeat.ts";
+import { registerServerAdapter, unregisterServerAdapter } from "../adapters/index.ts";
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
+const TEST_ADAPTER_TYPE = "runtime_skill_capture";
+
+if (!embeddedPostgresSupport.supported) {
+ console.warn(
+ `Skipping embedded Postgres heartbeat runtime skill tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
+ );
+}
+
+async function waitForRunToFinish(
+ heartbeat: ReturnType<typeof heartbeatService>,
+ runId: string,
+ timeoutMs = 5_000,
+) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const run = await heartbeat.getRun(runId);
+ if (run && !["queued", "running"].includes(run.status)) return run;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ return await heartbeat.getRun(runId);
+}
+
+describeEmbeddedPostgres("heartbeat runtime skill version pins", () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+ let oldPaperclipHome: string | undefined;
+ let paperclipHome: string | null = null;
+ const capturedRuns: Array<{ agentId: string; skills: PaperclipSkillEntry[] }> = [];
+ const cleanupDirs = new Set<string>();
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("heartbeat-runtime-skills-");
+ db = createDb(tempDb.connectionString);
+ oldPaperclipHome = process.env.PAPERCLIP_HOME;
+ paperclipHome = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-runtime-skills-home-"));
+ process.env.PAPERCLIP_HOME = paperclipHome;
+ registerServerAdapter({
+ type: TEST_ADAPTER_TYPE,
+ execute: async (ctx) => {
+ capturedRuns.push({
+ agentId: ctx.agent.id,
+ skills: (ctx.config.paperclipRuntimeSkills ?? []) as PaperclipSkillEntry[],
+ });
+ return {
+ exitCode: 0,
+ signal: null,
+ timedOut: false,
+ label: "Captured runtime skills",
+ };
+ },
+ testEnvironment: async () => ({
+ adapterType: TEST_ADAPTER_TYPE,
+ status: "pass",
+ checks: [],
+ testedAt: new Date().toISOString(),
+ }),
+ });
+ }, 20_000);
+
+ afterEach(async () => {
+ capturedRuns.length = 0;
+ await db.execute(sql.raw(`
+ TRUNCATE TABLE
+ "activity_log",
+ "environment_leases",
+ "environments",
+ "heartbeat_run_events",
+ "heartbeat_runs",
+ "agent_wakeup_requests",
+ "agent_runtime_state",
+ "company_skill_versions",
+ "company_skills",
+ "agents",
+ "companies"
+ RESTART IDENTITY CASCADE
+ `));
+ await Promise.all(Array.from(cleanupDirs, (dir) => fs.rm(dir, { recursive: true, force: true })));
+ cleanupDirs.clear();
+ });
+
+ afterAll(async () => {
+ unregisterServerAdapter(TEST_ADAPTER_TYPE);
+ if (oldPaperclipHome === undefined) delete process.env.PAPERCLIP_HOME;
+ else process.env.PAPERCLIP_HOME = oldPaperclipHome;
+ if (paperclipHome) {
+ await fs.rm(paperclipHome, { recursive: true, force: true });
+ }
+ await tempDb?.cleanup();
+ });
+
+ it("materializes different pinned skill versions for different agents at runtime", async () => {
+ const companyId = randomUUID();
+ const skillId = randomUUID();
+ const firstAgentId = randomUUID();
+ const secondAgentId = randomUUID();
+ const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
+ const skillKey = `company/${companyId}/runtime-coach`;
+ const skillDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-versioned-runtime-skill-"));
+ cleanupDirs.add(skillDir);
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix,
+ requireBoardApprovalForNewAgents: false,
+ });
+ await fs.writeFile(path.join(skillDir, "SKILL.md"), "# Runtime Coach\n\nVersion one.\n", "utf8");
+ await db.insert(companySkills).values({
+ id: skillId,
+ companyId,
+ key: skillKey,
+ slug: "runtime-coach",
+ name: "Runtime Coach",
+ description: null,
+ markdown: "# Runtime Coach\n\nVersion one.\n",
+ sourceType: "local_path",
+ sourceLocator: skillDir,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ metadata: { sourceKind: "local_path" },
+ });
+
+ const skills = companySkillService(db);
+ const versionOne = await skills.createVersion(
+ companyId,
+ skillId,
+ { label: "v1" },
+ { type: "user", userId: "board" },
+ );
+ await fs.writeFile(path.join(skillDir, "SKILL.md"), "# Runtime Coach\n\nVersion two.\n", "utf8");
+ await db
+ .update(companySkills)
+ .set({ markdown: "# Runtime Coach\n\nVersion two.\n", updatedAt: new Date() })
+ .where(eq(companySkills.id, skillId));
+ const versionTwo = await skills.createVersion(
+ companyId,
+ skillId,
+ { label: "v2" },
+ { type: "user", userId: "board" },
+ );
+
+ await db.insert(agents).values([
+ {
+ id: firstAgentId,
+ companyId,
+ name: "Pinned V1",
+ role: "engineer",
+ status: "idle",
+ adapterType: TEST_ADAPTER_TYPE,
+ adapterConfig: {
+ paperclipSkillSync: {
+ desiredSkills: [{ key: skillKey, versionId: versionOne.id }],
+ },
+ },
+ runtimeConfig: {},
+ permissions: {},
+ },
+ {
+ id: secondAgentId,
+ companyId,
+ name: "Pinned V2",
+ role: "engineer",
+ status: "idle",
+ adapterType: TEST_ADAPTER_TYPE,
+ adapterConfig: {
+ paperclipSkillSync: {
+ desiredSkills: [{ key: skillKey, versionId: versionTwo.id }],
+ },
+ },
+ runtimeConfig: {},
+ permissions: {},
+ },
+ ]);
+
+ const heartbeat = heartbeatService(db);
+ const firstRun = await heartbeat.invoke(firstAgentId, "on_demand", {}, "manual");
+ expect(firstRun).not.toBeNull();
+ expect((await waitForRunToFinish(heartbeat, firstRun!.id))?.status).toBe("succeeded");
+
+ const secondRun = await heartbeat.invoke(secondAgentId, "on_demand", {}, "manual");
+ expect(secondRun).not.toBeNull();
+ expect((await waitForRunToFinish(heartbeat, secondRun!.id))?.status).toBe("succeeded");
+
+ const firstSkill = capturedRuns.find((run) => run.agentId === firstAgentId)?.skills
+ .find((entry) => entry.key === skillKey);
+ const secondSkill = capturedRuns.find((run) => run.agentId === secondAgentId)?.skills
+ .find((entry) => entry.key === skillKey);
+
+ expect(firstSkill).toMatchObject({
+ key: skillKey,
+ versionId: versionOne.id,
+ currentVersionId: versionTwo.id,
+ sourceStatus: "available",
+ });
+ expect(secondSkill).toMatchObject({
+ key: skillKey,
+ versionId: versionTwo.id,
+ currentVersionId: versionTwo.id,
+ sourceStatus: "available",
+ });
+ await expect(fs.readFile(path.join(firstSkill!.source, "SKILL.md"), "utf8"))
+ .resolves.toContain("Version one.");
+ await expect(fs.readFile(path.join(secondSkill!.source, "SKILL.md"), "utf8"))
+ .resolves.toContain("Version two.");
+
+ const firstSkillFile = path.join(firstSkill!.source, "SKILL.md");
+ const oldMtime = new Date("2024-01-01T00:00:00.000Z");
+ await fs.utimes(firstSkillFile, oldMtime, oldMtime);
+
+ const repeatRun = await heartbeat.invoke(firstAgentId, "on_demand", {}, "manual");
+ expect(repeatRun).not.toBeNull();
+ expect((await waitForRunToFinish(heartbeat, repeatRun!.id))?.status).toBe("succeeded");
+ const repeatedSkill = capturedRuns
+ .filter((run) => run.agentId === firstAgentId)
+ .at(-1)
+ ?.skills.find((entry) => entry.key === skillKey);
+ expect(repeatedSkill).toMatchObject({
+ source: firstSkill!.source,
+ versionId: versionOne.id,
+ sourceStatus: "available",
+ });
+ expect((await fs.stat(firstSkillFile)).mtime.toISOString()).toBe(oldMtime.toISOString());
+ });
+});
diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts
index 3182c2bf0a..fb52036d41 100644
--- a/server/src/routes/agents.ts
+++ b/server/src/routes/agents.ts
@@ -16,6 +16,7 @@ import {
normalizeIssueIdentifier,
resetAgentSessionSchema,
testAdapterEnvironmentSchema,
+ type AgentDesiredSkillEntry,
type AgentSkillSnapshot,
type InstanceSchedulerHeartbeatAgent,
upsertAgentInstructionsFileSchema,
@@ -64,6 +65,7 @@ import type {
AdapterEnvironmentCheck,
AdapterEnvironmentTestResult,
} from "@paperclipai/adapter-utils";
+import { skillVersionSelectionMap } from "../services/runtime-skill-selections.js";
import { secretService } from "../services/secrets.js";
import {
detectAdapterModel,
@@ -1282,18 +1284,35 @@ export function agentRoutes(
function buildUnsupportedSkillSnapshot(
adapterType: string,
- desiredSkills: string[] = [],
+ desiredSkillEntries: AgentDesiredSkillEntry[] = [],
): AgentSkillSnapshot {
+ const desiredSkills = desiredSkillEntries.map((entry) => entry.key);
return {
adapterType,
supported: false,
mode: "unsupported",
desiredSkills,
+ desiredSkillEntries,
entries: [],
warnings: ["This adapter does not implement skill sync yet."],
};
}
+ function normalizeDesiredSkillSelections(
+ requestedDesiredSkills: Array<string | AgentDesiredSkillEntry> | undefined,
+ ): AgentDesiredSkillEntry[] | undefined {
+ if (!requestedDesiredSkills) return undefined;
+ const out = new Map<string, AgentDesiredSkillEntry>();
+ for (const value of requestedDesiredSkills) {
+ const entry = typeof value === "string"
+ ? { key: value.trim(), versionId: null }
+ : { key: value.key.trim(), versionId: value.versionId ?? null };
+ if (!entry.key || out.has(entry.key)) continue;
+ out.set(entry.key, entry);
+ }
+ return Array.from(out.values());
+ }
+
// Legacy hardcoded set — used as fallback when adapter module does not
// declare requiresMaterializedRuntimeSkills explicitly.
const LEGACY_MATERIALIZED_SKILLS_SET = new Set([
@@ -1319,9 +1338,11 @@ export function agentRoutes(
materializeMissing?: boolean;
} = {},
) {
+ const preference = readPaperclipSkillSyncPreference(config);
const runtimeSkillEntries = await companySkills.listRuntimeSkillEntries(companyId, {
materializeMissing: options.materializeMissing
?? shouldMaterializeRuntimeSkillsForAdapter(adapterType),
+ versionSelections: skillVersionSelectionMap(preference.desiredSkillEntries),
});
return {
...config,
@@ -1333,31 +1354,39 @@ export function agentRoutes(
companyId: string,
adapterType: string,
adapterConfig: Record<string, unknown>,
- requestedDesiredSkills: string[] | undefined,
+ requestedDesiredSkills: AgentDesiredSkillEntry[] | undefined,
) {
if (!requestedDesiredSkills) {
return {
adapterConfig,
desiredSkills: null as string[] | null,
+ desiredSkillEntries: null as AgentDesiredSkillEntry[] | null,
runtimeSkillEntries: null as Awaited<ReturnType<typeof companySkills.listRuntimeSkillEntries>> | null,
};
}
- const resolvedRequestedSkills = await companySkills.resolveRequestedSkillKeys(
+ const resolvedRequestedSkillEntries = await companySkills.resolveRequestedSkillEntries(
companyId,
requestedDesiredSkills,
);
+ const resolvedRequestedSkills = resolvedRequestedSkillEntries.map((entry) => entry.key);
const runtimeSkillEntries = await companySkills.listRuntimeSkillEntries(companyId, {
materializeMissing: shouldMaterializeRuntimeSkillsForAdapter(adapterType),
+ versionSelections: skillVersionSelectionMap(resolvedRequestedSkillEntries),
});
const requiredSkills = runtimeSkillEntries
.filter((entry) => entry.required)
.map((entry) => entry.key);
- const desiredSkills = Array.from(new Set([...requiredSkills, ...resolvedRequestedSkills]));
+ const desiredSkillEntries = [
+ ...requiredSkills.map((key) => ({ key, versionId: null })),
+ ...resolvedRequestedSkillEntries,
+ ].filter((entry, index, entries) => entries.findIndex((candidate) => candidate.key === entry.key) === index);
+ const desiredSkills = desiredSkillEntries.map((entry) => entry.key);
return {
- adapterConfig: writePaperclipSkillSyncPreference(adapterConfig, desiredSkills),
+ adapterConfig: writePaperclipSkillSyncPreference(adapterConfig, desiredSkillEntries),
desiredSkills,
+ desiredSkillEntries,
runtimeSkillEntries,
};
}
@@ -1574,9 +1603,14 @@ export function agentRoutes(
);
const runtimeSkillEntries = await companySkills.listRuntimeSkillEntries(agent.companyId, {
materializeMissing: false,
+ versionSelections: skillVersionSelectionMap(preference.desiredSkillEntries),
});
const requiredSkills = runtimeSkillEntries.filter((entry) => entry.required).map((entry) => entry.key);
- res.json(buildUnsupportedSkillSnapshot(agent.adapterType, Array.from(new Set([...requiredSkills, ...preference.desiredSkills]))));
+ const desiredSkillEntries = [
+ ...requiredSkills.map((key) => ({ key, versionId: null })),
+ ...preference.desiredSkillEntries,
+ ].filter((entry, index, entries) => entries.findIndex((candidate) => candidate.key === entry.key) === index);
+ res.json(buildUnsupportedSkillSnapshot(agent.adapterType, desiredSkillEntries));
return;
}
@@ -1611,16 +1645,11 @@ export function agentRoutes(
}
await assertCanUpdateAgent(req, agent);
- const requestedSkills = Array.from(
- new Set(
- (req.body.desiredSkills as string[])
- .map((value) => value.trim())
- .filter(Boolean),
- ),
- );
+ const requestedSkills = normalizeDesiredSkillSelections(req.body.desiredSkills);
const {
adapterConfig: nextAdapterConfig,
desiredSkills,
+ desiredSkillEntries,
runtimeSkillEntries,
} = await resolveDesiredSkillAssignment(
agent.companyId,
@@ -1628,7 +1657,7 @@ export function agentRoutes(
agent.adapterConfig as Record<string, unknown>,
requestedSkills,
);
- if (!desiredSkills || !runtimeSkillEntries) {
+ if (!desiredSkills || !desiredSkillEntries || !runtimeSkillEntries) {
throw unprocessable("Skill sync requires desiredSkills.");
}
const actor = getActorInfo(req);
@@ -1669,7 +1698,7 @@ export function agentRoutes(
adapterType: updated.adapterType,
config: runtimeSkillConfig,
})
- : buildUnsupportedSkillSnapshot(updated.adapterType, desiredSkills);
+ : buildUnsupportedSkillSnapshot(updated.adapterType, desiredSkillEntries);
await logActivity(db, {
companyId: updated.companyId,
@@ -1683,6 +1712,7 @@ export function agentRoutes(
details: {
adapterType: updated.adapterType,
desiredSkills,
+ desiredSkillEntries,
mode: snapshot.mode,
supported: snapshot.supported,
entryCount: snapshot.entries.length,
@@ -2093,7 +2123,7 @@ export function agentRoutes(
companyId,
hireInput.adapterType,
requestedAdapterConfig,
- Array.isArray(requestedDesiredSkills) ? requestedDesiredSkills : undefined,
+ normalizeDesiredSkillSelections(Array.isArray(requestedDesiredSkills) ? requestedDesiredSkills : undefined),
);
const normalizedAdapterConfig = await normalizeMediatedAdapterConfigForPersistence({
companyId,
@@ -2279,7 +2309,7 @@ export function agentRoutes(
companyId,
createInput.adapterType,
requestedAdapterConfig,
- Array.isArray(requestedDesiredSkills) ? requestedDesiredSkills : undefined,
+ normalizeDesiredSkillSelections(Array.isArray(requestedDesiredSkills) ? requestedDesiredSkills : undefined),
);
const normalizedAdapterConfig = await normalizeMediatedAdapterConfigForPersistence({
companyId,
diff --git a/server/src/routes/company-skills.ts b/server/src/routes/company-skills.ts
index 1fb82298ad..c6bec7a687 100644
--- a/server/src/routes/company-skills.ts
+++ b/server/src/routes/company-skills.ts
@@ -2,13 +2,19 @@ import { Router, type Request } from "express";
import type { Db } from "@paperclipai/db";
import {
catalogSkillListQuerySchema,
+ companySkillCommentCreateSchema,
+ companySkillCommentUpdateSchema,
companySkillCreateSchema,
companySkillFileUpdateSchema,
+ companySkillForkSchema,
companySkillImportSchema,
companySkillInstallCatalogSchema,
companySkillInstallUpdateSchema,
+ companySkillListQuerySchema,
companySkillProjectScanRequestSchema,
companySkillResetSchema,
+ companySkillUpdateSchema,
+ companySkillVersionCreateSchema,
} from "@paperclipai/shared";
import { trackSkillImported } from "@paperclipai/shared/telemetry";
import { validate } from "../middleware/validate.js";
@@ -63,6 +69,22 @@ export function companySkillRoutes(db: Db) {
return undefined;
}
+ 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");
+ return [];
+ }
+
+ function skillActor(req: Request) {
+ if (req.actor.type === "agent") {
+ return { type: "agent" as const, agentId: req.actor.agentId ?? null };
+ }
+ if (req.actor.type === "board") {
+ return { type: "user" as const, userId: req.actor.userId ?? null };
+ }
+ return { type: "system" as const };
+ }
+
async function assertCanMutateCompanySkills(req: Request, companyId: string) {
assertCompanyAccess(req, companyId);
@@ -118,15 +140,30 @@ export function companySkillRoutes(db: Db) {
router.get("/companies/:companyId/skills", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
- const result = await svc.list(companyId);
+ const result = await svc.list(companyId, companySkillListQuerySchema.parse({
+ q: firstQueryString(req.query.q),
+ sort: firstQueryString(req.query.sort),
+ categories: [
+ ...queryStringArray(req.query.category),
+ ...queryStringArray(req.query.categories),
+ ...queryStringArray(req.query["categories[]"]),
+ ],
+ scope: firstQueryString(req.query.scope),
+ }));
res.json(result);
});
+ router.get("/companies/:companyId/skills/categories", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ assertCompanyAccess(req, companyId);
+ res.json(await svc.categoryCounts(companyId));
+ });
+
router.get("/companies/:companyId/skills/:skillId", async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
assertCompanyAccess(req, companyId);
- const result = await svc.detail(companyId, skillId);
+ const result = await svc.detail(companyId, skillId, skillActor(req));
if (!result) {
res.status(404).json({ error: "Skill not found" });
return;
@@ -134,6 +171,199 @@ export function companySkillRoutes(db: Db) {
res.json(result);
});
+ router.get("/companies/:companyId/skills/:skillId/versions", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ assertCompanyAccess(req, companyId);
+ res.json(await svc.listVersions(companyId, skillId));
+ });
+
+ router.get("/companies/:companyId/skills/:skillId/versions/:versionId", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ const versionId = req.params.versionId as string;
+ assertCompanyAccess(req, companyId);
+ const result = await svc.getVersion(companyId, skillId, versionId);
+ if (!result) {
+ res.status(404).json({ error: "Skill version not found" });
+ return;
+ }
+ res.json(result);
+ });
+
+ router.post(
+ "/companies/:companyId/skills/:skillId/versions",
+ validate(companySkillVersionCreateSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ await assertCanMutateCompanySkills(req, companyId);
+ const result = await svc.createVersion(companyId, skillId, req.body, skillActor(req));
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_version_created",
+ entityType: "company_skill_version",
+ entityId: result.id,
+ details: {
+ skillId,
+ revisionNumber: result.revisionNumber,
+ label: result.label,
+ },
+ });
+ res.status(201).json(result);
+ },
+ );
+
+ router.post("/companies/:companyId/skills/:skillId/star", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ assertCompanyAccess(req, companyId);
+ const result = await svc.starSkill(companyId, skillId, skillActor(req));
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_starred",
+ entityType: "company_skill",
+ entityId: skillId,
+ details: { starCount: result.starCount },
+ });
+ res.json(result);
+ });
+
+ router.delete("/companies/:companyId/skills/:skillId/star", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ assertCompanyAccess(req, companyId);
+ const result = await svc.unstarSkill(companyId, skillId, skillActor(req));
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_unstarred",
+ entityType: "company_skill",
+ entityId: skillId,
+ details: { starCount: result.starCount },
+ });
+ res.json(result);
+ });
+
+ router.post(
+ "/companies/:companyId/skills/:skillId/fork",
+ validate(companySkillForkSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ await assertCanMutateCompanySkills(req, companyId);
+ const result = await svc.forkSkill(companyId, skillId, req.body, skillActor(req));
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_forked",
+ entityType: "company_skill",
+ entityId: result.id,
+ details: {
+ sourceSkillId: skillId,
+ slug: result.slug,
+ name: result.name,
+ },
+ });
+ res.status(201).json(result);
+ },
+ );
+
+ router.get("/companies/:companyId/skills/:skillId/comments", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ assertCompanyAccess(req, companyId);
+ res.json(await svc.listComments(companyId, skillId));
+ });
+
+ router.post(
+ "/companies/:companyId/skills/:skillId/comments",
+ validate(companySkillCommentCreateSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ assertCompanyAccess(req, companyId);
+ const result = await svc.createComment(companyId, skillId, req.body, skillActor(req));
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_comment_created",
+ entityType: "company_skill_comment",
+ entityId: result.id,
+ details: { skillId, parentCommentId: result.parentCommentId },
+ });
+ res.status(201).json(result);
+ },
+ );
+
+ router.patch(
+ "/companies/:companyId/skills/:skillId/comments/:commentId",
+ validate(companySkillCommentUpdateSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ const commentId = req.params.commentId as string;
+ assertCompanyAccess(req, companyId);
+ const result = await svc.updateComment(companyId, skillId, commentId, req.body, skillActor(req));
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_comment_updated",
+ entityType: "company_skill_comment",
+ entityId: result.id,
+ details: { skillId },
+ });
+ res.json(result);
+ },
+ );
+
+ router.delete("/companies/:companyId/skills/:skillId/comments/:commentId", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ const commentId = req.params.commentId as string;
+ assertCompanyAccess(req, companyId);
+ const result = await svc.deleteComment(companyId, skillId, commentId, skillActor(req));
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_comment_deleted",
+ entityType: "company_skill_comment",
+ entityId: result.id,
+ details: { skillId },
+ });
+ res.json(result);
+ });
+
router.get("/companies/:companyId/skills/:skillId/update-status", async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
@@ -165,7 +395,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
await assertCanMutateCompanySkills(req, companyId);
- const result = await svc.createLocalSkill(companyId, req.body);
+ const result = await svc.createLocalSkill(companyId, req.body, skillActor(req));
const actor = getActorInfo(req);
await logActivity(db, {
@@ -187,6 +417,35 @@ export function companySkillRoutes(db: Db) {
},
);
+ router.patch(
+ "/companies/:companyId/skills/:skillId",
+ validate(companySkillUpdateSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ await assertCanMutateCompanySkills(req, companyId);
+ const result = await svc.updateSkill(companyId, skillId, req.body);
+
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_updated",
+ entityType: "company_skill",
+ entityId: result.id,
+ details: {
+ slug: result.slug,
+ sharingScope: result.sharingScope,
+ },
+ });
+
+ res.json(result);
+ },
+ );
+
router.patch(
"/companies/:companyId/skills/:skillId/files",
validate(companySkillFileUpdateSchema),
@@ -199,6 +458,7 @@ export function companySkillRoutes(db: Db) {
skillId,
String(req.body.path ?? ""),
String(req.body.content ?? ""),
+ skillActor(req),
);
const actor = getActorInfo(req);
diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts
index 81b900610f..ab1cc85bb1 100644
--- a/server/src/routes/openapi.ts
+++ b/server/src/routes/openapi.ts
@@ -4268,7 +4268,19 @@ for (const route of [
["get", "/api/skills/catalog/{catalogId}", "Get a catalog skill"],
["get", "/api/skills/catalog/{catalogId}/files", "List catalog skill files"],
["post", "/api/companies/{companyId}/skills/install-catalog", "Install a catalog skill"],
+ ["get", "/api/companies/{companyId}/skills/categories", "List company skill categories"],
["post", "/api/companies/{companyId}/skills/{skillId}/audit", "Audit a company skill"],
+ ["patch", "/api/companies/{companyId}/skills/{skillId}", "Update a company skill"],
+ ["get", "/api/companies/{companyId}/skills/{skillId}/versions", "List skill versions"],
+ ["post", "/api/companies/{companyId}/skills/{skillId}/versions", "Create a skill version"],
+ ["get", "/api/companies/{companyId}/skills/{skillId}/versions/{versionId}", "Get a skill version"],
+ ["post", "/api/companies/{companyId}/skills/{skillId}/star", "Star a company skill"],
+ ["delete", "/api/companies/{companyId}/skills/{skillId}/star", "Unstar a company skill"],
+ ["post", "/api/companies/{companyId}/skills/{skillId}/fork", "Fork a company skill"],
+ ["get", "/api/companies/{companyId}/skills/{skillId}/comments", "List skill comments"],
+ ["post", "/api/companies/{companyId}/skills/{skillId}/comments", "Create a skill comment"],
+ ["patch", "/api/companies/{companyId}/skills/{skillId}/comments/{commentId}", "Update a skill comment"],
+ ["delete", "/api/companies/{companyId}/skills/{skillId}/comments/{commentId}", "Delete a skill comment"],
["post", "/api/companies/{companyId}/skills/{skillId}/reset", "Reset a company skill"],
] as const) {
registerCurrentRoute({
diff --git a/server/src/services/company-portability.ts b/server/src/services/company-portability.ts
index e696063445..1024a871b7 100644
--- a/server/src/services/company-portability.ts
+++ b/server/src/services/company-portability.ts
@@ -2770,13 +2770,19 @@ function buildManifestFromPackageFiles(
const trackingRef = asString(primarySource?.trackingRef);
const sourceHostname = asString(primarySource?.hostname) || "github.com";
const [owner, repoName] = (repo ?? "").split("/");
+ const canonicalKey = readSkillKey(frontmatter);
+ const normalizedSourceKind = owner === "paperclipai"
+ && repoName === "paperclip"
+ && canonicalKey?.startsWith("paperclipai/paperclip/")
+ ? "paperclip_bundled"
+ : "github";
sourceType = "github";
sourceLocator = asString(primarySource?.url)
?? (repo ? `https://${sourceHostname}/${repo}${repoPath ? `/tree/${trackingRef ?? commit ?? "main"}/${repoPath}` : ""}` : null);
sourceRef = commit;
normalizedMetadata = owner && repoName
? {
- sourceKind: "github",
+ sourceKind: normalizedSourceKind,
...(sourceHostname !== "github.com" ? { hostname: sourceHostname } : {}),
owner,
repo: repoName,
diff --git a/server/src/services/company-skills.ts b/server/src/services/company-skills.ts
index 58bfb3ce94..17c39f50e9 100644
--- a/server/src/services/company-skills.ts
+++ b/server/src/services/company-skills.ts
@@ -2,36 +2,48 @@ import { createHash, randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
-import { and, asc, eq } from "drizzle-orm";
+import { and, asc, desc, eq, isNull, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
-import { companies, companySkills } from "@paperclipai/db";
+import { companies, companySkillComments, companySkillStars, companySkillVersions, companySkills } from "@paperclipai/db";
import { readPaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils";
-import type { PaperclipSkillEntry } from "@paperclipai/adapter-utils/server-utils";
+import type { PaperclipDesiredSkillEntry, PaperclipSkillEntry } from "@paperclipai/adapter-utils/server-utils";
import type {
+ AgentDesiredSkillEntry,
CatalogSkill,
CompanySkill,
CompanySkillAuditFinding,
CompanySkillAuditResult,
CompanySkillAuditVerdict,
+ CompanySkillCategoryCount,
+ CompanySkillComment,
+ CompanySkillCommentCreateRequest,
+ CompanySkillCommentUpdateRequest,
CompanySkillCreateRequest,
CompanySkillCompatibility,
CompanySkillDetail,
CompanySkillFileDetail,
CompanySkillFileInventoryEntry,
+ CompanySkillForkRequest,
CompanySkillImportResult,
CompanySkillInstallCatalogRequest,
CompanySkillInstallCatalogResult,
+ CompanySkillListQuery,
CompanySkillListItem,
CompanySkillProjectScanConflict,
CompanySkillProjectScanRequest,
CompanySkillProjectScanResult,
CompanySkillProjectScanSkipped,
+ CompanySkillSharingScope,
CompanySkillSourceBadge,
CompanySkillSourceType,
CompanySkillTrustLevel,
+ CompanySkillUpdateRequest,
CompanySkillUpdateStatus,
CompanySkillUpdateHoldReason,
CompanySkillUsageAgent,
+ CompanySkillVersion,
+ CompanySkillVersionCreateRequest,
+ CompanySkillVersionFileInventoryEntry,
} from "@paperclipai/shared";
import { normalizeAgentUrlKey } from "@paperclipai/shared";
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
@@ -53,6 +65,8 @@ import {
} from "./catalog-provenance.js";
type CompanySkillRow = typeof companySkills.$inferSelect;
+type CompanySkillVersionRow = typeof companySkillVersions.$inferSelect;
+type CompanySkillCommentRow = typeof companySkillComments.$inferSelect;
type CompanySkillListDbRow = Pick<
CompanySkillRow,
| "id"
@@ -67,6 +81,20 @@ type CompanySkillListDbRow = Pick<
| "trustLevel"
| "compatibility"
| "fileInventory"
+ | "iconUrl"
+ | "color"
+ | "tagline"
+ | "authorName"
+ | "homepageUrl"
+ | "categories"
+ | "sharingScope"
+ | "publicShareToken"
+ | "forkedFromSkillId"
+ | "forkedFromCompanyId"
+ | "starCount"
+ | "installCount"
+ | "forkCount"
+ | "currentVersionId"
| "metadata"
| "createdAt"
| "updatedAt"
@@ -85,6 +113,20 @@ type CompanySkillListRow = Pick<
| "trustLevel"
| "compatibility"
| "fileInventory"
+ | "iconUrl"
+ | "color"
+ | "tagline"
+ | "authorName"
+ | "homepageUrl"
+ | "categories"
+ | "sharingScope"
+ | "publicShareToken"
+ | "forkedFromSkillId"
+ | "forkedFromCompanyId"
+ | "starCount"
+ | "installCount"
+ | "forkCount"
+ | "currentVersionId"
| "metadata"
| "createdAt"
| "updatedAt"
@@ -168,6 +210,20 @@ function assertImportedSkillSourceAllowed(skill: ImportedSkill) {
}
}
+function assertImportedSkillKeyAllowed(skill: ImportedSkill) {
+ if (!skill.key.startsWith("paperclipai/paperclip/")) return;
+ const metadata = isPlainRecord(skill.metadata) ? skill.metadata : null;
+ const sourceKind = asString(metadata?.sourceKind);
+ if (sourceKind === "paperclip_bundled") return;
+ throw unprocessable(
+ `Reserved Paperclip skill key "${skill.key}" cannot be imported from unbundled sources.`,
+ {
+ skillKey: skill.key,
+ sourceKind: sourceKind ?? skill.sourceType,
+ },
+ );
+}
+
type SkillSourceMeta = {
skillKey?: string;
sourceKind?: string;
@@ -219,6 +275,13 @@ export type ProjectSkillScanTarget = {
type RuntimeSkillEntryOptions = {
materializeMissing?: boolean;
+ versionSelections?: Map<string, string | null>;
+};
+
+type SkillActor = {
+ type: "agent" | "user" | "system";
+ agentId?: string | null;
+ userId?: string | null;
};
type RuntimeSkillSourceResolution =
@@ -242,6 +305,20 @@ function selectCompanySkillColumns() {
trustLevel: companySkills.trustLevel,
compatibility: companySkills.compatibility,
fileInventory: companySkills.fileInventory,
+ iconUrl: companySkills.iconUrl,
+ color: companySkills.color,
+ tagline: companySkills.tagline,
+ authorName: companySkills.authorName,
+ homepageUrl: companySkills.homepageUrl,
+ categories: companySkills.categories,
+ sharingScope: companySkills.sharingScope,
+ publicShareToken: companySkills.publicShareToken,
+ forkedFromSkillId: companySkills.forkedFromSkillId,
+ forkedFromCompanyId: companySkills.forkedFromCompanyId,
+ starCount: companySkills.starCount,
+ installCount: companySkills.installCount,
+ forkCount: companySkills.forkCount,
+ currentVersionId: companySkills.currentVersionId,
metadata: companySkills.metadata,
createdAt: companySkills.createdAt,
updatedAt: companySkills.updatedAt,
@@ -833,13 +910,18 @@ function deriveImportedSkillSource(
: null);
const [owner, repoName] = (repo ?? "").split("/");
if (repo && owner && repoName) {
+ const sourceKind = owner === "paperclipai"
+ && repoName === "paperclip"
+ && canonicalKey?.startsWith("paperclipai/paperclip/")
+ ? "paperclip_bundled"
+ : "github";
return {
sourceType: "github",
sourceLocator: url,
sourceRef: commit,
metadata: {
...(canonicalKey ? { skillKey: canonicalKey } : {}),
- sourceKind: "github",
+ sourceKind,
...(sourceHostname !== "github.com" ? { hostname: sourceHostname } : {}),
owner,
repo: repoName,
@@ -1306,6 +1388,20 @@ function toCompanySkill(row: CompanySkillRow): CompanySkill {
}];
})
: [],
+ iconUrl: row.iconUrl ?? null,
+ color: row.color ?? null,
+ tagline: row.tagline ?? null,
+ authorName: row.authorName ?? null,
+ homepageUrl: row.homepageUrl ?? null,
+ categories: normalizeCategoryList(row.categories),
+ sharingScope: normalizeSharingScope(row.sharingScope),
+ publicShareToken: row.publicShareToken ?? null,
+ forkedFromSkillId: row.forkedFromSkillId ?? null,
+ forkedFromCompanyId: row.forkedFromCompanyId ?? null,
+ starCount: Math.max(0, row.starCount ?? 0),
+ installCount: Math.max(0, row.installCount ?? 0),
+ forkCount: Math.max(0, row.forkCount ?? 0),
+ currentVersionId: row.currentVersionId ?? null,
metadata: isPlainRecord(row.metadata) ? row.metadata : null,
};
}
@@ -1328,10 +1424,75 @@ function toCompanySkillListRow(row: CompanySkillListDbRow): CompanySkillListRow
}];
})
: [],
+ iconUrl: row.iconUrl ?? null,
+ color: row.color ?? null,
+ tagline: row.tagline ?? null,
+ authorName: row.authorName ?? null,
+ homepageUrl: row.homepageUrl ?? null,
+ categories: normalizeCategoryList(row.categories),
+ sharingScope: normalizeSharingScope(row.sharingScope),
+ publicShareToken: row.publicShareToken ?? null,
+ forkedFromSkillId: row.forkedFromSkillId ?? null,
+ forkedFromCompanyId: row.forkedFromCompanyId ?? null,
+ starCount: Math.max(0, row.starCount ?? 0),
+ installCount: Math.max(0, row.installCount ?? 0),
+ forkCount: Math.max(0, row.forkCount ?? 0),
+ currentVersionId: row.currentVersionId ?? null,
metadata: isPlainRecord(row.metadata) ? row.metadata : null,
};
}
+function normalizeSharingScope(value: unknown): CompanySkillSharingScope {
+ return value === "private" || value === "public_link" || value === "company" ? value : "company";
+}
+
+function normalizeMutableSharingScope(value: unknown): CompanySkillSharingScope | null {
+ if (value === undefined || value === null) return null;
+ if (value === "private" || value === "company") return value;
+ if (value === "public_link") {
+ throw unprocessable("Public skill sharing is not available in this version.");
+ }
+ throw unprocessable("Invalid skill sharing scope.");
+}
+
+function normalizeCategorySlug(value: unknown) {
+ if (typeof value !== "string") return null;
+ return normalizeSkillSlug(value);
+}
+
+function normalizeCategoryList(values: unknown): string[] {
+ if (!Array.isArray(values)) return [];
+ return Array.from(new Set(values.map(normalizeCategorySlug).filter((value): value is string => Boolean(value))));
+}
+
+function normalizeStoreText(value: unknown, maxLength = 500) {
+ const text = asString(value);
+ return text ? text.slice(0, maxLength) : null;
+}
+
+function readStringList(value: unknown): string[] {
+ return Array.isArray(value)
+ ? value.map(asString).filter((entry): entry is string => Boolean(entry))
+ : [];
+}
+
+function readSkillStoreMetadata(frontmatter: Record<string, unknown>, metadata: Record<string, unknown> | null) {
+ const categories = normalizeCategoryList([
+ ...readStringList(frontmatter.categories),
+ ...readStringList(frontmatter.tags),
+ ...readStringList(metadata?.categories),
+ ...readStringList(metadata?.tags),
+ ]);
+ return {
+ iconUrl: normalizeStoreText(frontmatter.iconUrl ?? frontmatter.icon ?? metadata?.iconUrl ?? metadata?.icon, 2000),
+ color: normalizeStoreText(frontmatter.color ?? metadata?.color, 64),
+ tagline: normalizeStoreText(frontmatter.tagline ?? frontmatter.summary ?? metadata?.tagline, 120),
+ authorName: normalizeStoreText(frontmatter.author ?? frontmatter.authorName ?? metadata?.authorName, 200),
+ homepageUrl: normalizeStoreText(frontmatter.homepage ?? frontmatter.homepageUrl ?? metadata?.homepageUrl, 2000),
+ categories,
+ };
+}
+
function serializeFileInventory(
fileInventory: CompanySkillFileInventoryEntry[],
): Array<Record<string, unknown>> {
@@ -1341,6 +1502,45 @@ function serializeFileInventory(
}));
}
+function serializeVersionFileInventory(
+ fileInventory: CompanySkillVersionFileInventoryEntry[],
+): CompanySkillVersionFileInventoryEntry[] {
+ return fileInventory.map((entry) => ({
+ path: entry.path,
+ kind: entry.kind,
+ content: entry.content,
+ }));
+}
+
+function toCompanySkillVersion(row: CompanySkillVersionRow): CompanySkillVersion {
+ return {
+ ...row,
+ label: row.label ?? null,
+ fileInventory: Array.isArray(row.fileInventory)
+ ? row.fileInventory.flatMap((entry) => {
+ if (!isPlainRecord(entry)) return [];
+ return [{
+ path: String(entry.path ?? ""),
+ kind: (String(entry.kind ?? "other") as CompanySkillFileInventoryEntry["kind"]),
+ content: String(entry.content ?? ""),
+ }];
+ })
+ : [],
+ authorAgentId: row.authorAgentId ?? null,
+ authorUserId: row.authorUserId ?? null,
+ };
+}
+
+function toCompanySkillComment(row: CompanySkillCommentRow): CompanySkillComment {
+ return {
+ ...row,
+ parentCommentId: row.parentCommentId ?? null,
+ authorAgentId: row.authorAgentId ?? null,
+ authorUserId: row.authorUserId ?? null,
+ deletedAt: row.deletedAt ?? null,
+ };
+}
+
function getSkillMeta(skill: Pick<CompanySkill, "metadata">): SkillSourceMeta {
return isPlainRecord(skill.metadata) ? skill.metadata as SkillSourceMeta : {};
}
@@ -1466,6 +1666,91 @@ function resolveRequestedSkillKeysOrThrow(
return Array.from(resolved);
}
+function normalizeRequestedDesiredSkillSelection(value: string | AgentDesiredSkillEntry): PaperclipDesiredSkillEntry {
+ if (typeof value === "string") {
+ return { key: value.trim(), versionId: null };
+ }
+ return {
+ key: value.key.trim(),
+ versionId: value.versionId ?? null,
+ };
+}
+
+async function assertVersionMatchesSkill(
+ db: Db,
+ companyId: string,
+ skillId: string,
+ versionId: string | null,
+) {
+ if (!versionId) return;
+ const row = await db
+ .select({ id: companySkillVersions.id })
+ .from(companySkillVersions)
+ .where(and(
+ eq(companySkillVersions.companyId, companyId),
+ eq(companySkillVersions.companySkillId, skillId),
+ eq(companySkillVersions.id, versionId),
+ ))
+ .then((rows) => rows[0] ?? null);
+ if (!row) {
+ throw unprocessable("Selected skill version does not belong to the requested company skill.", {
+ versionId,
+ skillId,
+ });
+ }
+}
+
+async function resolveRequestedSkillEntriesOrThrow(
+ db: Db,
+ companyId: string,
+ skills: CompanySkill[],
+ requestedSelections: Array<string | AgentDesiredSkillEntry>,
+) {
+ const missing = new Set<string>();
+ const ambiguous = new Set<string>();
+ const resolved = new Map<string, PaperclipDesiredSkillEntry>();
+
+ for (const rawSelection of requestedSelections) {
+ const selection = normalizeRequestedDesiredSkillSelection(rawSelection);
+ if (!selection.key) continue;
+
+ const match = resolveSkillReference(skills, selection.key);
+ if (match.skill) {
+ const skill = skills.find((candidate) => candidate.id === match.skill?.id);
+ if (!skill) {
+ missing.add(selection.key);
+ continue;
+ }
+ const selectedVersionId = selection.versionId ?? null;
+ await assertVersionMatchesSkill(db, companyId, skill.id, selectedVersionId);
+ if (!resolved.has(skill.key)) {
+ resolved.set(skill.key, { key: skill.key, versionId: selectedVersionId });
+ }
+ continue;
+ }
+
+ if (match.ambiguous) {
+ ambiguous.add(selection.key);
+ continue;
+ }
+
+ missing.add(selection.key);
+ }
+
+ if (ambiguous.size > 0 || missing.size > 0) {
+ const problems: string[] = [];
+ if (ambiguous.size > 0) {
+ problems.push(`ambiguous references: ${Array.from(ambiguous).sort().join(", ")}`);
+ }
+ if (missing.size > 0) {
+ problems.push(`unknown references: ${Array.from(missing).sort().join(", ")}`);
+ }
+ throw unprocessable(`Invalid company skill selection (${problems.join("; ")}).`);
+ }
+
+ return Array.from(resolved.values());
+}
+
function resolveDesiredSkillKeys(
skills: SkillReferenceTarget[],
config: Record<string, unknown>,
@@ -1478,6 +1763,20 @@ function resolveDesiredSkillKeys(
));
}
+function resolveDesiredSkillEntries(
+ skills: SkillReferenceTarget[],
+ config: Record<string, unknown>,
+) {
+ const preference = readPaperclipSkillSyncPreference(config);
+ const out = new Map<string, PaperclipDesiredSkillEntry>();
+ for (const entry of preference.desiredSkillEntries) {
+ const key = resolveSkillReference(skills, entry.key).skill?.key ?? normalizeSkillKey(entry.key);
+ if (!key || out.has(key)) continue;
+ out.set(key, { key, versionId: entry.versionId ?? null });
+ }
+ return Array.from(out.values());
+}
+
function normalizeSkillDirectory(skill: SkillSourceInfoTarget) {
if ((skill.sourceType !== "local_path" && skill.sourceType !== "catalog") || !skill.sourceLocator) return null;
const resolved = path.resolve(skill.sourceLocator);
@@ -1864,12 +2163,20 @@ function deriveSkillSourceInfo(skill: SkillSourceInfoTarget): {
};
}
-function enrichSkill(skill: CompanySkill, attachedAgentCount: number, usedByAgents: CompanySkillUsageAgent[] = []) {
+function enrichSkill(
+ skill: CompanySkill,
+ attachedAgentCount: number,
+ usedByAgents: CompanySkillUsageAgent[] = [],
+ currentVersion: CompanySkillVersion | null = null,
+ starredByCurrentActor = false,
+) {
const source = deriveSkillSourceInfo(skill);
return {
...skill,
attachedAgentCount,
usedByAgents,
+ currentVersion,
+ starredByCurrentActor,
...source,
};
}
@@ -1896,6 +2203,20 @@ function toCompanySkillListItem(skill: CompanySkillListRow, attachedAgentCount:
trustLevel: skill.trustLevel,
compatibility: skill.compatibility,
fileInventory: skill.fileInventory,
+ iconUrl: skill.iconUrl,
+ color: skill.color,
+ tagline: skill.tagline,
+ authorName: skill.authorName,
+ homepageUrl: skill.homepageUrl,
+ categories: skill.categories,
+ sharingScope: skill.sharingScope,
+ publicShareToken: skill.publicShareToken,
+ forkedFromSkillId: skill.forkedFromSkillId,
+ forkedFromCompanyId: skill.forkedFromCompanyId,
+ starCount: skill.starCount,
+ installCount: skill.installCount,
+ forkCount: skill.forkCount,
+ currentVersionId: skill.currentVersionId,
createdAt: skill.createdAt,
updatedAt: skill.updatedAt,
attachedAgentCount,
@@ -2028,7 +2349,7 @@ export function companySkillService(db: Db) {
}
}
- async function list(companyId: string): Promise<CompanySkillListItem[]> {
+ async function list(companyId: string, query: CompanySkillListQuery = {}): Promise<CompanySkillListItem[]> {
await ensureSkillInventoryCurrent(companyId);
const rows = await db
.select({
@@ -2044,6 +2365,20 @@ export function companySkillService(db: Db) {
trustLevel: companySkills.trustLevel,
compatibility: companySkills.compatibility,
fileInventory: companySkills.fileInventory,
+ iconUrl: companySkills.iconUrl,
+ color: companySkills.color,
+ tagline: companySkills.tagline,
+ authorName: companySkills.authorName,
+ homepageUrl: companySkills.homepageUrl,
+ categories: companySkills.categories,
+ sharingScope: companySkills.sharingScope,
+ publicShareToken: companySkills.publicShareToken,
+ forkedFromSkillId: companySkills.forkedFromSkillId,
+ forkedFromCompanyId: companySkills.forkedFromCompanyId,
+ starCount: companySkills.starCount,
+ installCount: companySkills.installCount,
+ forkCount: companySkills.forkCount,
+ currentVersionId: companySkills.currentVersionId,
metadata: companySkills.metadata,
createdAt: companySkills.createdAt,
updatedAt: companySkills.updatedAt,
@@ -2053,13 +2388,42 @@ export function companySkillService(db: Db) {
.orderBy(asc(companySkills.name), asc(companySkills.key))
.then((entries) => entries.map((entry) => toCompanySkillListRow(entry as CompanySkillListDbRow)));
const agentRows = await agents.list(companyId);
- return rows.map((skill) => {
+ const q = query.q?.trim().toLowerCase() ?? "";
+ const categories = new Set((query.categories ?? []).map(normalizeCategorySlug).filter((value): value is string => Boolean(value)));
+ const filtered = rows.filter((skill) => {
+ if (query.scope && skill.sharingScope !== query.scope) return false;
+ if (categories.size > 0 && !skill.categories.some((category) => categories.has(category))) return false;
+ if (q) {
+ const haystack = [
+ skill.name,
+ skill.slug,
+ skill.key,
+ skill.description,
+ skill.tagline,
+ skill.authorName,
+ ...skill.categories,
+ ].filter(Boolean).join("\n").toLowerCase();
+ if (!haystack.includes(q)) return false;
+ }
+ return true;
+ });
+ const items = filtered.map((skill) => {
const attachedAgentCount = agentRows.filter((agent) => {
const desiredSkills = resolveDesiredSkillKeys(rows, agent.adapterConfig as Record<string, unknown>);
return desiredSkills.includes(skill.key);
}).length;
return toCompanySkillListItem(skill, attachedAgentCount);
});
+ const sort = query.sort ?? "alphabetical";
+ items.sort((left, right) => {
+ if (sort === "recent") return right.updatedAt.getTime() - left.updatedAt.getTime() || left.name.localeCompare(right.name);
+ if (sort === "installs") return right.installCount - left.installCount || left.name.localeCompare(right.name);
+ if (sort === "stars") return right.starCount - left.starCount || left.name.localeCompare(right.name);
+ if (sort === "agents") return right.attachedAgentCount - left.attachedAgentCount || left.name.localeCompare(right.name);
+ if (sort === "forks") return right.forkCount - left.forkCount || left.name.localeCompare(right.name);
+ return left.name.localeCompare(right.name) || left.key.localeCompare(right.key);
+ });
+ return items;
}
async function listFull(companyId: string): Promise<CompanySkill[]> {
@@ -2072,6 +2436,19 @@ export function companySkillService(db: Db) {
return rows.map((row) => toCompanySkill(row));
}
+ async function categoryCounts(companyId: string): Promise<CompanySkillCategoryCount[]> {
+ const rows = await listFull(companyId);
+ const counts = new Map<string, number>();
+ for (const skill of rows) {
+ for (const category of skill.categories) {
+ counts.set(category, (counts.get(category) ?? 0) + 1);
+ }
+ }
+ return Array.from(counts.entries())
+ .map(([slug, count]) => ({ slug, count }))
+ .sort((left, right) => right.count - left.count || left.slug.localeCompare(right.slug));
+ }
+
async function listReferenceTargets(companyId: string): Promise<SkillReferenceTarget[]> {
const rows = await db
.select({
@@ -2102,6 +2479,43 @@ export function companySkillService(db: Db) {
return row ? toCompanySkill(row) : null;
}
+ async function getVersion(companyId: string, skillId: string, versionId: string): Promise<CompanySkillVersion | null> {
+ const row = await db
+ .select()
+ .from(companySkillVersions)
+ .where(and(
+ eq(companySkillVersions.companyId, companyId),
+ eq(companySkillVersions.companySkillId, skillId),
+ eq(companySkillVersions.id, versionId),
+ ))
+ .then((rows) => rows[0] ?? null);
+ return row ? toCompanySkillVersion(row) : null;
+ }
+
+ async function getCurrentVersion(skill: CompanySkill): Promise<CompanySkillVersion | null> {
+ return skill.currentVersionId ? getVersion(skill.companyId, skill.id, skill.currentVersionId) : null;
+ }
+
+ async function isStarredByActor(companyId: string, skillId: string, actor: SkillActor | null | undefined) {
+ if (!actor || actor.type === "system") return false;
+ const clause = actor.type === "agent" && actor.agentId
+ ? eq(companySkillStars.agentId, actor.agentId)
+ : actor.type === "user" && actor.userId
+ ? eq(companySkillStars.userId, actor.userId)
+ : null;
+ if (!clause) return false;
+ const row = await db
+ .select({ id: companySkillStars.id })
+ .from(companySkillStars)
+ .where(and(
+ eq(companySkillStars.companyId, companyId),
+ eq(companySkillStars.companySkillId, skillId),
+ clause,
+ ))
+ .then((rows) => rows[0] ?? null);
+ return Boolean(row);
+ }
+
async function updateSkillMetadata(
skill: CompanySkill,
metadataPatch: Record<string, unknown>,
@@ -2153,12 +2567,13 @@ export function companySkillService(db: Db) {
async function usage(companyId: string, key: string): Promise<CompanySkillUsageAgent[]> {
const skills = await listReferenceTargets(companyId);
const agentRows = await agents.list(companyId);
- const desiredAgents = agentRows.filter((agent) => {
- const desiredSkills = resolveDesiredSkillKeys(skills, agent.adapterConfig as Record<string, unknown>);
- return desiredSkills.includes(key);
+ const desiredAgents = agentRows.flatMap((agent) => {
+ const desiredEntries = resolveDesiredSkillEntries(skills, agent.adapterConfig as Record<string, unknown>);
+ const desiredEntry = desiredEntries.find((entry) => entry.key === key);
+ return desiredEntry ? [{ agent, desiredEntry }] : [];
});
- return desiredAgents.map((agent) => ({
+ return desiredAgents.map(({ agent, desiredEntry }) => ({
id: agent.id,
name: agent.name,
urlKey: agent.urlKey,
@@ -2166,15 +2581,355 @@ export function companySkillService(db: Db) {
desired: true,
// Runtime adapter state is intentionally omitted from this bounded metadata read.
actualState: null,
+ versionId: desiredEntry.versionId ?? null,
}));
}
- async function detail(companyId: string, id: string): Promise<CompanySkillDetail | null> {
+ async function detail(companyId: string, id: string, actor?: SkillActor | null): Promise<CompanySkillDetail | null> {
await ensureSkillInventoryCurrent(companyId);
const skill = await getById(companyId, id);
if (!skill) return null;
const usedByAgents = await usage(companyId, skill.key);
- return enrichSkill(skill, usedByAgents.length, usedByAgents);
+ return enrichSkill(
+ skill,
+ usedByAgents.length,
+ usedByAgents,
+ await getCurrentVersion(skill),
+ await isStarredByActor(companyId, id, actor),
+ );
+ }
+
+ async function collectVersionFileInventory(
+ companyId: string,
+ skill: CompanySkill,
+ ): Promise<CompanySkillVersionFileInventoryEntry[]> {
+ const out: CompanySkillVersionFileInventoryEntry[] = [];
+ for (const entry of skill.fileInventory) {
+ const detail = await readFile(companyId, skill.id, entry.path);
+ if (!detail) continue;
+ out.push({
+ path: detail.path,
+ kind: detail.kind,
+ content: detail.content,
+ });
+ }
+ return out;
+ }
+
+ async function listVersions(companyId: string, skillId: string): Promise<CompanySkillVersion[]> {
+ const skill = await getById(companyId, skillId);
+ if (!skill) throw notFound("Skill not found");
+ const rows = await db
+ .select()
+ .from(companySkillVersions)
+ .where(and(eq(companySkillVersions.companyId, companyId), eq(companySkillVersions.companySkillId, skillId)))
+ .orderBy(desc(companySkillVersions.revisionNumber));
+ return rows.map((row) => toCompanySkillVersion(row));
+ }
+
+ async function createVersion(
+ companyId: string,
+ skillId: string,
+ input: CompanySkillVersionCreateRequest = {},
+ actor: SkillActor | null = null,
+ ): Promise<CompanySkillVersion> {
+ await ensureSkillInventoryCurrent(companyId);
+ const skill = await getById(companyId, skillId);
+ if (!skill) throw notFound("Skill not found");
+ const fileInventory = serializeVersionFileInventory(await collectVersionFileInventory(companyId, skill));
+ const versionRow = await db.transaction(async (tx) => {
+ await tx.execute(sql`
+ select ${companySkills.id}
+ from ${companySkills}
+ where ${companySkills.id} = ${skillId}
+ and ${companySkills.companyId} = ${companyId}
+ for update
+ `);
+ const [{ nextRevision }] = await tx
+ .select({
+ nextRevision: sql<number>`coalesce(max(${companySkillVersions.revisionNumber}), 0) + 1`,
+ })
+ .from(companySkillVersions)
+ .where(and(eq(companySkillVersions.companyId, companyId), eq(companySkillVersions.companySkillId, skillId)));
+ const row = await tx
+ .insert(companySkillVersions)
+ .values({
+ companyId,
+ companySkillId: skillId,
+ revisionNumber: Number(nextRevision ?? 1),
+ label: input.label?.trim() || null,
+ fileInventory,
+ authorAgentId: actor?.type === "agent" ? actor.agentId ?? null : null,
+ authorUserId: actor?.type === "user" ? actor.userId ?? null : null,
+ })
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ if (!row) return null;
+ await tx
+ .update(companySkills)
+ .set({ currentVersionId: row.id, updatedAt: new Date() })
+ .where(and(eq(companySkills.id, skillId), eq(companySkills.companyId, companyId)));
+ return row;
+ });
+ if (!versionRow) throw notFound("Failed to persist skill version");
+ return toCompanySkillVersion(versionRow);
+ }
+
+ async function refreshStarCount(companyId: string, skillId: string) {
+ const [{ value }] = await db
+ .select({ value: sql<number>`count(*)::int` })
+ .from(companySkillStars)
+ .where(and(eq(companySkillStars.companyId, companyId), eq(companySkillStars.companySkillId, skillId)));
+ const starCount = Number(value ?? 0);
+ await db
+ .update(companySkills)
+ .set({ starCount, updatedAt: new Date() })
+ .where(and(eq(companySkills.id, skillId), eq(companySkills.companyId, companyId)));
+ return starCount;
+ }
+
+ function actorStarClause(actor: SkillActor) {
+ if (actor.type === "agent" && actor.agentId) return eq(companySkillStars.agentId, actor.agentId);
+ if (actor.type === "user" && actor.userId) return eq(companySkillStars.userId, actor.userId);
+ throw unprocessable("Skill stars require an agent or board user actor.");
+ }
+
+ async function starSkill(companyId: string, skillId: string, actor: SkillActor) {
+ const skill = await getById(companyId, skillId);
+ if (!skill) throw notFound("Skill not found");
+ const existing = await db
+ .select({ id: companySkillStars.id })
+ .from(companySkillStars)
+ .where(and(eq(companySkillStars.companyId, companyId), eq(companySkillStars.companySkillId, skillId), actorStarClause(actor)))
+ .then((rows) => rows[0] ?? null);
+ if (!existing) {
+ await db.insert(companySkillStars).values({
+ companyId,
+ companySkillId: skillId,
+ agentId: actor.type === "agent" ? actor.agentId ?? null : null,
+ userId: actor.type === "user" ? actor.userId ?? null : null,
+ });
+ }
+ return { skillId, starred: true, starCount: await refreshStarCount(companyId, skillId) };
+ }
+
+ async function unstarSkill(companyId: string, skillId: string, actor: SkillActor) {
+ const skill = await getById(companyId, skillId);
+ if (!skill) throw notFound("Skill not found");
+ await db
+ .delete(companySkillStars)
+ .where(and(eq(companySkillStars.companyId, companyId), eq(companySkillStars.companySkillId, skillId), actorStarClause(actor)));
+ return { skillId, starred: false, starCount: await refreshStarCount(companyId, skillId) };
+ }
+
+ async function listComments(companyId: string, skillId: string): Promise<CompanySkillComment[]> {
+ const skill = await getById(companyId, skillId);
+ if (!skill) throw notFound("Skill not found");
+ const rows = await db
+ .select()
+ .from(companySkillComments)
+ .where(and(
+ eq(companySkillComments.companyId, companyId),
+ eq(companySkillComments.companySkillId, skillId),
+ isNull(companySkillComments.deletedAt),
+ ))
+ .orderBy(asc(companySkillComments.createdAt));
+ return rows.map((row) => toCompanySkillComment(row));
+ }
+
+ async function createComment(
+ companyId: string,
+ skillId: string,
+ input: CompanySkillCommentCreateRequest,
+ actor: SkillActor,
+ ): Promise<CompanySkillComment> {
+ const skill = await getById(companyId, skillId);
+ if (!skill) throw notFound("Skill not found");
+ if (input.parentCommentId) {
+ const parent = await db
+ .select({ id: companySkillComments.id })
+ .from(companySkillComments)
+ .where(and(
+ eq(companySkillComments.companyId, companyId),
+ eq(companySkillComments.companySkillId, skillId),
+ eq(companySkillComments.id, input.parentCommentId),
+ isNull(companySkillComments.deletedAt),
+ ))
+ .then((rows) => rows[0] ?? null);
+ if (!parent) throw notFound("Parent comment not found");
+ }
+ const row = await db
+ .insert(companySkillComments)
+ .values({
+ companyId,
+ companySkillId: skillId,
+ parentCommentId: input.parentCommentId ?? null,
+ authorAgentId: actor.type === "agent" ? actor.agentId ?? null : null,
+ authorUserId: actor.type === "user" ? actor.userId ?? null : null,
+ body: input.body,
+ })
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ if (!row) throw notFound("Failed to persist skill comment");
+ return toCompanySkillComment(row);
+ }
+
+ function assertCanMutateComment(comment: CompanySkillComment, actor: SkillActor) {
+ if (actor.type === "user") return;
+ if (actor.type === "agent" && actor.agentId && comment.authorAgentId === actor.agentId) return;
+ throw unprocessable("Only the comment author or a board user can modify this skill comment.");
+ }
+
+ async function updateComment(
+ companyId: string,
+ skillId: string,
+ commentId: string,
+ input: CompanySkillCommentUpdateRequest,
+ actor: SkillActor,
+ ): Promise<CompanySkillComment> {
+ const existing = await db
+ .select()
+ .from(companySkillComments)
+ .where(and(
+ eq(companySkillComments.companyId, companyId),
+ eq(companySkillComments.companySkillId, skillId),
+ eq(companySkillComments.id, commentId),
+ isNull(companySkillComments.deletedAt),
+ ))
+ .then((rows) => rows[0] ?? null);
+ if (!existing) throw notFound("Skill comment not found");
+ const comment = toCompanySkillComment(existing);
+ assertCanMutateComment(comment, actor);
+ const row = await db
+ .update(companySkillComments)
+ .set({ body: input.body, updatedAt: new Date() })
+ .where(and(
+ eq(companySkillComments.companyId, companyId),
+ eq(companySkillComments.companySkillId, skillId),
+ eq(companySkillComments.id, commentId),
+ isNull(companySkillComments.deletedAt),
+ ))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ if (!row) throw notFound("Skill comment not found");
+ return toCompanySkillComment(row);
+ }
+
+ async function deleteComment(
+ companyId: string,
+ skillId: string,
+ commentId: string,
+ actor: SkillActor,
+ ): Promise<CompanySkillComment> {
+ const existing = await db
+ .select()
+ .from(companySkillComments)
+ .where(and(
+ eq(companySkillComments.companyId, companyId),
+ eq(companySkillComments.companySkillId, skillId),
+ eq(companySkillComments.id, commentId),
+ isNull(companySkillComments.deletedAt),
+ ))
+ .then((rows) => rows[0] ?? null);
+ if (!existing) throw notFound("Skill comment not found");
+ const comment = toCompanySkillComment(existing);
+ assertCanMutateComment(comment, actor);
+ const row = await db
+ .update(companySkillComments)
+ .set({ deletedAt: new Date(), updatedAt: new Date() })
+ .where(and(
+ eq(companySkillComments.companyId, companyId),
+ eq(companySkillComments.companySkillId, skillId),
+ eq(companySkillComments.id, commentId),
+ isNull(companySkillComments.deletedAt),
+ ))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ if (!row) throw notFound("Skill comment not found");
+ return toCompanySkillComment(row);
+ }
+
+ async function forkSkill(
+ companyId: string,
+ skillId: string,
+ input: CompanySkillForkRequest = {},
+ actor: SkillActor | null = null,
+ ): Promise<CompanySkill> {
+ await ensureSkillInventoryCurrent(companyId);
+ const source = await getById(companyId, skillId);
+ if (!source) throw notFound("Skill not found");
+ const existing = await listFull(companyId);
+ const usedSlugs = new Set(existing.map((skill) => normalizeSkillSlug(skill.slug) ?? skill.slug));
+ const forkSlug = uniqueSkillSlug(normalizeSkillSlug(input.slug ?? `${source.slug}-fork`) ?? `${source.slug}-fork`, usedSlugs);
+ const forkName = input.name?.trim() || `${source.name} Fork`;
+ const managedRoot = resolveManagedSkillsRoot(companyId);
+ const forkDir = path.resolve(managedRoot, forkSlug);
+ await fs.rm(forkDir, { recursive: true, force: true });
+ await fs.mkdir(forkDir, { recursive: true });
+ for (const entry of source.fileInventory) {
+ const detail = await readFile(companyId, source.id, entry.path);
+ if (!detail) continue;
+ const targetPath = path.resolve(forkDir, detail.path);
+ await fs.mkdir(path.dirname(targetPath), { recursive: true });
+ await fs.writeFile(targetPath, detail.content, "utf8");
+ }
+ const skillFilePath = path.join(forkDir, "SKILL.md");
+ const markdown = await fs.readFile(skillFilePath, "utf8").catch(() => source.markdown);
+ if (!(await statPath(skillFilePath))?.isFile()) {
+ await fs.writeFile(skillFilePath, markdown, "utf8");
+ }
+ const inventory = await collectLocalSkillInventory(forkDir);
+ const parsed = parseFrontmatterMarkdown(markdown);
+ const metadata = {
+ sourceKind: "managed_local",
+ forkedFromSkillId: source.id,
+ forkedFromCompanyId: source.companyId,
+ forkedByAgentId: actor?.type === "agent" ? actor.agentId ?? null : null,
+ forkedByUserId: actor?.type === "user" ? actor.userId ?? null : null,
+ };
+ const imported = await upsertImportedSkills(companyId, [{
+ key: `company/${companyId}/${forkSlug}`,
+ slug: forkSlug,
+ name: asString(parsed.frontmatter.name) ?? forkName,
+ description: asString(parsed.frontmatter.description) ?? source.description,
+ markdown,
+ sourceType: "local_path",
+ sourceLocator: forkDir,
+ sourceRef: null,
+ trustLevel: deriveTrustLevel(inventory),
+ compatibility: source.compatibility,
+ fileInventory: inventory,
+ metadata,
+ }]);
+ const forked = imported[0]!;
+ await db
+ .update(companySkills)
+ .set({
+ iconUrl: source.iconUrl,
+ color: source.color,
+ tagline: source.tagline,
+ authorName: source.authorName,
+ homepageUrl: source.homepageUrl,
+ categories: source.categories,
+ sharingScope: input.sharingScope ?? "company",
+ forkedFromSkillId: source.id,
+ forkedFromCompanyId: source.companyId,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(companySkills.id, forked.id), eq(companySkills.companyId, companyId)));
+ await db
+ .update(companySkills)
+ .set({
+ forkCount: sql`${companySkills.forkCount} + 1`,
+ installCount: sql`${companySkills.installCount} + 1`,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(companySkills.id, source.id), eq(companySkills.companyId, companyId)));
+ await createVersion(companyId, forked.id, { label: "Initial version" }, actor);
+ return getById(companyId, forked.id).then((skill) => {
+ if (!skill) throw notFound("Forked skill not found");
+ return skill;
+ });
}
async function updateStatus(companyId: string, skillId: string): Promise<CompanySkillUpdateStatus | null> {
@@ -2297,12 +3052,15 @@ export function companySkillService(db: Db) {
if (skill.sourceType === "local_path" || skill.sourceType === "catalog") {
const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath);
- if (absolutePath) {
- content = await fs.readFile(absolutePath, "utf8");
+ const diskContent = absolutePath
+ ? await fs.readFile(absolutePath, "utf8").catch(() => null)
+ : null;
+ if (diskContent !== null) {
+ content = diskContent;
} else if (normalizedPath === "SKILL.md") {
content = skill.markdown;
} else {
- throw notFound("Skill file not found");
+ throw notFound("Skill file is unavailable: the skill source directory is missing.");
}
} else if (skill.sourceType === "github" || skill.sourceType === "skills_sh") {
const metadata = getSkillMeta(skill);
@@ -2310,12 +3068,25 @@ export function companySkillService(db: Db) {
const repo = asString(metadata.repo);
const hostname = asString(metadata.hostname) || "github.com";
const ref = skill.sourceRef ?? asString(metadata.ref) ?? "main";
- const repoSkillDir = normalizeGitHubSkillDirectory(asString(metadata.repoSkillDir), skill.slug);
+ const rawRepoSkillDir = typeof metadata.repoSkillDir === "string" ? metadata.repoSkillDir.trim() : null;
+ // An explicit "."/"" repoSkillDir means SKILL.md lives at the repo root;
+ // only fall back to the slug subdirectory when metadata is absent.
+ const repoSkillDir = typeof metadata.repoSkillDir === "string"
+ ? normalizeGitHubSkillDirectory(rawRepoSkillDir, "")
+ : normalizeGitHubSkillDirectory(rawRepoSkillDir, skill.slug);
if (!owner || !repo) {
throw unprocessable("Skill source metadata is incomplete.");
}
const repoPath = normalizePortablePath(path.posix.join(repoSkillDir, normalizedPath));
- content = await fetchText(resolveRawGitHubUrl(hostname, owner, repo, ref, repoPath));
+ try {
+ content = await fetchText(resolveRawGitHubUrl(hostname, owner, repo, ref, repoPath));
+ } catch (error) {
+ if (normalizedPath === "SKILL.md" && skill.markdown) {
+ content = skill.markdown;
+ } else {
+ throw error;
+ }
+ }
} else if (skill.sourceType === "url") {
if (normalizedPath !== "SKILL.md") {
throw notFound("This skill source only exposes SKILL.md");
@@ -2336,17 +3107,95 @@ export function companySkillService(db: Db) {
};
}
- async function createLocalSkill(companyId: string, input: CompanySkillCreateRequest): Promise<CompanySkill> {
+ async function updateSkill(
+ companyId: string,
+ skillId: string,
+ input: CompanySkillUpdateRequest = {},
+ ): Promise<CompanySkill> {
+ await ensureSkillInventoryCurrent(companyId);
+ const skill = await getById(companyId, skillId);
+ if (!skill) throw notFound("Skill not found");
+
+ const sharingScope = Object.prototype.hasOwnProperty.call(input, "sharingScope")
+ ? normalizeMutableSharingScope(input.sharingScope)
+ : null;
+ const values: Partial<typeof companySkills.$inferInsert> = {
+ updatedAt: new Date(),
+ };
+
+ if (Object.prototype.hasOwnProperty.call(input, "description")) {
+ values.description = normalizeStoreText(input.description, 2000);
+ }
+ if (Object.prototype.hasOwnProperty.call(input, "iconUrl")) {
+ values.iconUrl = normalizeStoreText(input.iconUrl, 2000);
+ }
+ if (Object.prototype.hasOwnProperty.call(input, "color")) {
+ values.color = normalizeStoreText(input.color, 64);
+ }
+ if (Object.prototype.hasOwnProperty.call(input, "tagline")) {
+ values.tagline = normalizeStoreText(input.tagline, 120);
+ }
+ if (Object.prototype.hasOwnProperty.call(input, "authorName")) {
+ values.authorName = normalizeStoreText(input.authorName, 200);
+ }
+ if (Object.prototype.hasOwnProperty.call(input, "homepageUrl")) {
+ values.homepageUrl = normalizeStoreText(input.homepageUrl, 2000);
+ }
+ if (Object.prototype.hasOwnProperty.call(input, "categories")) {
+ values.categories = normalizeCategoryList(input.categories);
+ }
+ if (sharingScope) {
+ values.sharingScope = sharingScope;
+ values.publicShareToken = null;
+ }
+
+ const row = await db
+ .update(companySkills)
+ .set(values)
+ .where(and(eq(companySkills.id, skillId), eq(companySkills.companyId, companyId)))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ if (!row) throw notFound("Skill not found");
+ return toCompanySkill(row);
+ }
+
+ async function createLocalSkill(
+ companyId: string,
+ input: CompanySkillCreateRequest,
+ actor: SkillActor | null = null,
+ ): Promise<CompanySkill> {
const slug = normalizeSkillSlug(input.slug ?? input.name) ?? "skill";
+ const key = `company/${companyId}/${slug}`;
+ const existing = await getByKey(companyId, key);
+ if (existing) {
+ throw conflict(`A company skill with slug "${slug}" already exists.`);
+ }
+
+ const forkSource = input.forkedFromSkillId
+ ? await getById(companyId, input.forkedFromSkillId)
+ : null;
+ if (input.forkedFromSkillId && !forkSource) {
+ throw notFound("Fork source skill not found");
+ }
+ const sharingScope = normalizeMutableSharingScope(input.sharingScope) ?? "company";
const managedRoot = resolveManagedSkillsRoot(companyId);
const skillDir = path.resolve(managedRoot, slug);
const skillFilePath = path.resolve(skillDir, "SKILL.md");
+ await fs.rm(skillDir, { recursive: true, force: true });
await fs.mkdir(skillDir, { recursive: true });
- const markdown = (input.markdown?.trim().length
- ? input.markdown
- : [
+ if (forkSource) {
+ for (const entry of forkSource.fileInventory) {
+ const detail = await readFile(companyId, forkSource.id, entry.path);
+ if (!detail) continue;
+ const targetPath = path.resolve(skillDir, detail.path);
+ await fs.mkdir(path.dirname(targetPath), { recursive: true });
+ await fs.writeFile(targetPath, detail.content, "utf8");
+ }
+ }
+
+ const fallbackMarkdown = [
"---",
`name: ${input.name}`,
...(input.description?.trim() ? [`description: ${input.description.trim()}`] : []),
@@ -2356,30 +3205,80 @@ export function companySkillService(db: Db) {
"",
input.description?.trim() ? input.description.trim() : "Describe what this skill does.",
"",
- ].join("\n"));
+ ].join("\n");
+ const markdown = input.markdown?.trim().length
+ ? input.markdown
+ : forkSource?.markdown ?? fallbackMarkdown;
await fs.writeFile(skillFilePath, markdown, "utf8");
+ const inventory = forkSource
+ ? await collectLocalSkillInventory(skillDir)
+ : [{ path: "SKILL.md", kind: "skill" as const }];
const parsed = parseFrontmatterMarkdown(markdown);
+ const metadata = {
+ sourceKind: "managed_local",
+ ...(forkSource ? {
+ forkedFromSkillId: forkSource.id,
+ forkedFromCompanyId: forkSource.companyId,
+ forkedByAgentId: actor?.type === "agent" ? actor.agentId ?? null : null,
+ forkedByUserId: actor?.type === "user" ? actor.userId ?? null : null,
+ } : {}),
+ };
const imported = await upsertImportedSkills(companyId, [{
- key: `company/${companyId}/${slug}`,
+ key,
slug,
name: asString(parsed.frontmatter.name) ?? input.name,
- description: asString(parsed.frontmatter.description) ?? input.description?.trim() ?? null,
+ description: asString(parsed.frontmatter.description) ?? input.description?.trim() ?? forkSource?.description ?? null,
markdown,
sourceType: "local_path",
sourceLocator: skillDir,
sourceRef: null,
- trustLevel: "markdown_only",
- compatibility: "compatible",
- fileInventory: [{ path: "SKILL.md", kind: "skill" }],
- metadata: { sourceKind: "managed_local" },
+ trustLevel: deriveTrustLevel(inventory),
+ compatibility: forkSource?.compatibility ?? "compatible",
+ fileInventory: inventory,
+ metadata,
}]);
- return imported[0]!;
+ const created = imported[0]!;
+ const row = await db
+ .update(companySkills)
+ .set({
+ iconUrl: normalizeStoreText(input.iconUrl, 2000) ?? forkSource?.iconUrl ?? created.iconUrl,
+ color: normalizeStoreText(input.color, 64) ?? forkSource?.color ?? created.color,
+ tagline: normalizeStoreText(input.tagline, 120) ?? forkSource?.tagline ?? created.tagline,
+ 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,
+ sharingScope,
+ forkedFromSkillId: forkSource?.id ?? null,
+ forkedFromCompanyId: forkSource?.companyId ?? null,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(companySkills.id, created.id), eq(companySkills.companyId, companyId)))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ if (forkSource) {
+ await db
+ .update(companySkills)
+ .set({
+ forkCount: sql`${companySkills.forkCount} + 1`,
+ installCount: sql`${companySkills.installCount} + 1`,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(companySkills.id, forkSource.id), eq(companySkills.companyId, companyId)));
+ }
+ await createVersion(companyId, created.id, { label: "Initial version" }, actor);
+ return (await getById(companyId, created.id)) ?? (row ? toCompanySkill(row) : created);
}
- async function updateFile(companyId: string, skillId: string, relativePath: string, content: string): Promise<CompanySkillFileDetail> {
+ async function updateFile(
+ companyId: string,
+ skillId: string,
+ relativePath: string,
+ content: string,
+ actor: SkillActor | null = null,
+ ): Promise<CompanySkillFileDetail> {
await ensureSkillInventoryCurrent(companyId);
const skill = await getById(companyId, skillId);
if (!skill) throw notFound("Skill not found");
@@ -2393,6 +3292,7 @@ export function companySkillService(db: Db) {
const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath);
if (!absolutePath) throw notFound("Skill file not found");
+ const previousContent = await fs.readFile(absolutePath, "utf8").catch(() => null);
await fs.mkdir(path.dirname(absolutePath), { recursive: true });
await fs.writeFile(absolutePath, content, "utf8");
@@ -2404,6 +3304,7 @@ export function companySkillService(db: Db) {
name: asString(parsed.frontmatter.name) ?? skill.name,
description: asString(parsed.frontmatter.description) ?? skill.description,
markdown: content,
+ ...readSkillStoreMetadata(parsed.frontmatter, skill.metadata),
updatedAt: new Date(),
})
.where(eq(companySkills.id, skill.id));
@@ -2414,6 +3315,10 @@ export function companySkillService(db: Db) {
.where(eq(companySkills.id, skill.id));
}
+ if (previousContent !== content) {
+ await createVersion(companyId, skillId, {}, actor);
+ }
+
const detail = await readFile(companyId, skillId, normalizedPath);
if (!detail) throw notFound("Skill file not found");
return detail;
@@ -3008,6 +3913,20 @@ export function companySkillService(db: Db) {
trustLevel: catalogSkill.trustLevel,
compatibility: catalogSkill.compatibility,
fileInventory: catalogSkill.files.map((entry) => ({ path: entry.path, kind: entry.kind })),
+ iconUrl: null,
+ color: null,
+ tagline: null,
+ authorName: null,
+ homepageUrl: null,
+ categories: normalizeCategoryList([catalogSkill.category, ...catalogSkill.tags]),
+ sharingScope: "company",
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 0,
+ installCount: 0,
+ forkCount: 0,
+ currentVersionId: null,
metadata: {
sourceKind: "catalog",
catalogId: catalogSkill.id,
@@ -3102,6 +4021,11 @@ export function companySkillService(db: Db) {
}
const markdown = await fs.readFile(path.join(originSnapshotLocator, catalogSkill.entrypoint), "utf8");
const metadata = buildCatalogSkillMetadata(catalogSkill, existingByKey, originSnapshotLocator);
+ const parsed = parseFrontmatterMarkdown(markdown);
+ const storeMetadata = readSkillStoreMetadata(parsed.frontmatter, {
+ ...metadata,
+ categories: [catalogSkill.category, ...catalogSkill.tags],
+ });
const values = {
companyId,
key: catalogSkill.key,
@@ -3118,6 +4042,14 @@ export function companySkillService(db: Db) {
path: entry.path,
kind: entry.kind,
}))),
+ iconUrl: storeMetadata.iconUrl ?? existingByKey?.iconUrl ?? null,
+ color: storeMetadata.color ?? existingByKey?.color ?? null,
+ tagline: storeMetadata.tagline ?? existingByKey?.tagline ?? catalogSkill.description.slice(0, 120),
+ authorName: storeMetadata.authorName ?? existingByKey?.authorName ?? "Paperclip",
+ homepageUrl: storeMetadata.homepageUrl ?? existingByKey?.homepageUrl ?? catalogSkill.source?.url ?? null,
+ categories: storeMetadata.categories.length > 0 ? storeMetadata.categories : normalizeCategoryList([catalogSkill.category, ...catalogSkill.tags]),
+ sharingScope: existingByKey?.sharingScope ?? "company",
+ installCount: existingByKey?.installCount ?? 1,
metadata,
updatedAt: new Date(),
};
@@ -3180,6 +4112,94 @@ export function companySkillService(db: Db) {
return skillDir;
}
+ function resolveVersionSnapshotPath(skillDir: string, relativePath: string) {
+ const normalizedPath = normalizePortablePath(relativePath);
+ if (!normalizedPath) return null;
+ const targetPath = path.resolve(skillDir, normalizedPath);
+ if (targetPath !== skillDir && !targetPath.startsWith(`${skillDir}${path.sep}`)) {
+ throw unprocessable(`Skill version file path is invalid: ${relativePath}`);
+ }
+ return { normalizedPath, targetPath };
+ }
+
+ async function listMaterializedFiles(root: string): Promise<string[] | null> {
+ async function walk(dir: string, base: string): Promise<string[]> {
+ const entries = await fs.readdir(dir, { withFileTypes: true });
+ const out: string[] = [];
+ for (const entry of entries) {
+ const relativePath = base ? path.posix.join(base, entry.name) : entry.name;
+ const absolutePath = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ out.push(...await walk(absolutePath, relativePath));
+ } else if (entry.isFile()) {
+ out.push(normalizePortablePath(relativePath));
+ } else {
+ out.push(normalizePortablePath(relativePath));
+ }
+ }
+ return out;
+ }
+
+ try {
+ return await walk(root, "");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+ throw error;
+ }
+ }
+
+ async function materializedVersionSnapshotMatches(skillDir: string, version: CompanySkillVersion) {
+ const expected = new Map<string, string>();
+ let sawSkillFile = false;
+ for (const entry of version.fileInventory) {
+ const resolved = resolveVersionSnapshotPath(skillDir, entry.path);
+ if (!resolved) continue;
+ expected.set(resolved.normalizedPath, entry.content);
+ if (resolved.normalizedPath === "SKILL.md") sawSkillFile = true;
+ }
+ if (!sawSkillFile) {
+ throw unprocessable("Company skill version could not be materialized because its SKILL.md snapshot is missing.");
+ }
+
+ const existingFiles = await listMaterializedFiles(skillDir);
+ if (!existingFiles || existingFiles.length !== expected.size) return false;
+ for (const relativePath of existingFiles) {
+ if (!expected.has(relativePath)) return false;
+ }
+ for (const [relativePath, content] of expected.entries()) {
+ const existingContent = await fs.readFile(path.resolve(skillDir, relativePath), "utf8").catch(() => null);
+ if (existingContent !== content) return false;
+ }
+ return true;
+ }
+
+ async function materializeVersionSnapshot(companyId: string, skill: CompanySkill, version: CompanySkillVersion) {
+ const runtimeRoot = path.resolve(resolveManagedSkillsRoot(companyId), "__versions__");
+ const skillDir = path.resolve(runtimeRoot, skill.id, version.id);
+ if (await materializedVersionSnapshotMatches(skillDir, version)) {
+ return skillDir;
+ }
+ await fs.rm(skillDir, { recursive: true, force: true });
+ await fs.mkdir(skillDir, { recursive: true });
+
+ let wroteSkillFile = false;
+ for (const entry of version.fileInventory) {
+ const resolved = resolveVersionSnapshotPath(skillDir, entry.path);
+ if (!resolved) continue;
+ const { normalizedPath, targetPath } = resolved;
+ await fs.mkdir(path.dirname(targetPath), { recursive: true });
+ await fs.writeFile(targetPath, entry.content, "utf8");
+ if (normalizedPath === "SKILL.md") wroteSkillFile = true;
+ }
+
+ if (!wroteSkillFile) {
+ await fs.rm(skillDir, { recursive: true, force: true });
+ throw unprocessable("Company skill version could not be materialized because its SKILL.md snapshot is missing.");
+ }
+
+ return skillDir;
+ }
+
function resolveRuntimeSkillMaterializedPath(companyId: string, skill: Pick<CompanySkill, "key" | "slug">) {
const runtimeRoot = path.resolve(resolveManagedSkillsRoot(companyId), "__runtime__");
return path.resolve(runtimeRoot, buildSkillRuntimeName(skill.key, skill.slug));
@@ -3190,6 +4210,20 @@ export function companySkillService(db: Db) {
skill: CompanySkill,
options: RuntimeSkillEntryOptions,
): Promise<RuntimeSkillSourceResolution | null> {
+ const selectedVersionId = options.versionSelections?.get(skill.key) ?? null;
+ if (selectedVersionId) {
+ const version = await getVersion(companyId, skill.id, selectedVersionId);
+ if (!version) {
+ return {
+ status: "missing",
+ source: path.resolve(resolveManagedSkillsRoot(companyId), "__versions__", skill.id, selectedVersionId),
+ detail: "The selected skill version no longer exists.",
+ };
+ }
+ const versionSource = await materializeVersionSnapshot(companyId, skill, version).catch(() => null);
+ return versionSource ? { status: "available", source: versionSource } : null;
+ }
+
const source = await resolveExistingSkillDirectory(normalizeSkillDirectory(skill));
if (source) return { status: "available", source };
@@ -3225,6 +4259,8 @@ export function companySkillService(db: Db) {
key: skill.key,
runtimeName: buildSkillRuntimeName(skill.key, skill.slug),
source: sourceResolution.source,
+ versionId: options.versionSelections?.get(skill.key) ?? null,
+ currentVersionId: skill.currentVersionId,
sourceStatus: sourceResolution.status,
missingDetail: sourceResolution.status === "missing" ? sourceResolution.detail : null,
required,
@@ -3362,6 +4398,7 @@ export function companySkillService(db: Db) {
async function upsertImportedSkills(companyId: string, imported: ImportedSkill[]): Promise<CompanySkill[]> {
const out: CompanySkill[] = [];
for (const skill of imported) {
+ assertImportedSkillKeyAllowed(skill);
assertImportedSkillSourceAllowed(skill);
const existing = await getByKey(companyId, skill.key);
const existingMeta = existing ? getSkillMeta(existing) : {};
@@ -3384,6 +4421,8 @@ export function companySkillService(db: Db) {
...(skill.metadata ?? {}),
skillKey: skill.key,
};
+ const parsed = parseFrontmatterMarkdown(skill.markdown);
+ const storeMetadata = readSkillStoreMetadata(parsed.frontmatter, metadata);
const values = {
companyId,
key: skill.key,
@@ -3397,6 +4436,14 @@ export function companySkillService(db: Db) {
trustLevel: skill.trustLevel,
compatibility: skill.compatibility,
fileInventory: serializeFileInventory(skill.fileInventory),
+ iconUrl: storeMetadata.iconUrl ?? existing?.iconUrl ?? null,
+ color: storeMetadata.color ?? existing?.color ?? null,
+ tagline: storeMetadata.tagline ?? existing?.tagline ?? null,
+ authorName: storeMetadata.authorName ?? existing?.authorName ?? null,
+ homepageUrl: storeMetadata.homepageUrl ?? existing?.homepageUrl ?? null,
+ categories: storeMetadata.categories.length > 0 ? storeMetadata.categories : existing?.categories ?? [],
+ sharingScope: existing?.sharingScope ?? "company",
+ installCount: existing?.installCount ?? 1,
metadata,
updatedAt: new Date(),
};
@@ -3506,9 +4553,25 @@ export function companySkillService(db: Db) {
const skills = await listFull(companyId);
return resolveRequestedSkillKeysOrThrow(skills, requestedReferences);
},
+ resolveRequestedSkillEntries: async (companyId: string, requestedSelections: Array<string | AgentDesiredSkillEntry>) => {
+ const skills = await listFull(companyId);
+ return resolveRequestedSkillEntriesOrThrow(db, companyId, skills, requestedSelections);
+ },
+ categoryCounts,
detail,
+ listVersions,
+ getVersion,
+ createVersion,
+ starSkill,
+ unstarSkill,
+ listComments,
+ createComment,
+ updateComment,
+ deleteComment,
+ forkSkill,
updateStatus,
readFile,
+ updateSkill,
updateFile,
createLocalSkill,
deleteSkill,
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index deec2ab691..24a38df783 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -188,6 +188,7 @@ import { extractSkillMentionIds, isUuidLike } from "@paperclipai/shared";
import { environmentService } from "./environments.js";
import { parseExecutionPolicyBootstrapEnv } from "./execution-policy-bootstrap.js";
import { environmentRuntimeService } from "./environment-runtime.js";
+import { skillVersionSelectionMap } from "./runtime-skill-selections.js";
import { environmentRunOrchestrator } from "./environment-run-orchestrator.js";
import { isUnsafeSessionWorkspaceCwd } from "./session-workspace-cwd.js";
import {
@@ -555,7 +556,7 @@ export function applyRunScopedMentionedSkillKeys(
const existingPreference = readPaperclipSkillSyncPreference(config);
return writePaperclipSkillSyncPreference(config, [
- ...existingPreference.desiredSkills,
+ ...existingPreference.desiredSkillEntries,
...normalizedSkillKeys,
]);
}
@@ -8264,7 +8265,10 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
resolvedConfig,
runScopedMentionedSkillKeys,
);
- const runtimeSkillEntries = await companySkills.listRuntimeSkillEntries(agent.companyId);
+ const runtimeSkillPreference = readPaperclipSkillSyncPreference(effectiveResolvedConfig);
+ const runtimeSkillEntries = await companySkills.listRuntimeSkillEntries(agent.companyId, {
+ versionSelections: skillVersionSelectionMap(runtimeSkillPreference.desiredSkillEntries),
+ });
let runtimeConfig = {
...effectiveResolvedConfig,
paperclipRuntimeSkills: runtimeSkillEntries,
diff --git a/server/src/services/runtime-skill-selections.ts b/server/src/services/runtime-skill-selections.ts
new file mode 100644
index 0000000000..658a71ba9e
--- /dev/null
+++ b/server/src/services/runtime-skill-selections.ts
@@ -0,0 +1,3 @@
+export function skillVersionSelectionMap(entries: Array<{ key: string; versionId: string | null }>) {
+ return new Map(entries.map((entry) => [entry.key, entry.versionId] as const));
+}
diff --git a/ui/src/api/agents.ts b/ui/src/api/agents.ts
index 3dc1fae75a..e9271831b7 100644
--- a/ui/src/api/agents.ts
+++ b/ui/src/api/agents.ts
@@ -1,5 +1,6 @@
import type {
Agent,
+ AgentDesiredSkillEntry,
AgentPermissions,
AgentDetail,
AgentInstructionsBundle,
@@ -174,7 +175,7 @@ export const agentsApi = {
listKeys: (id: string, companyId?: string) => api.get<AgentKey[]>(agentPath(id, companyId, "/keys")),
skills: (id: string, companyId?: string) =>
api.get<AgentSkillSnapshot>(agentPath(id, companyId, "/skills")),
- syncSkills: (id: string, desiredSkills: string[], companyId?: string) =>
+ syncSkills: (id: string, desiredSkills: Array<string | AgentDesiredSkillEntry>, companyId?: string) =>
api.post<AgentSkillSnapshot>(agentPath(id, companyId, "/skills/sync"), { desiredSkills }),
createKey: (id: string, name: string, companyId?: string) =>
api.post<AgentKeyCreated>(agentPath(id, companyId, "/keys"), { name }),
diff --git a/ui/src/api/companySkills.ts b/ui/src/api/companySkills.ts
index 996fe9aaa7..1e3aeb8f3d 100644
--- a/ui/src/api/companySkills.ts
+++ b/ui/src/api/companySkills.ts
@@ -3,16 +3,26 @@ import type {
CatalogSkillFileDetail,
CatalogSkillKind,
CompanySkill,
+ CompanySkillCategoryCount,
+ CompanySkillComment,
+ CompanySkillCommentCreateRequest,
+ CompanySkillCommentUpdateRequest,
CompanySkillCreateRequest,
CompanySkillDetail,
CompanySkillFileDetail,
+ CompanySkillForkRequest,
CompanySkillImportResult,
CompanySkillInstallCatalogRequest,
CompanySkillInstallCatalogResult,
+ CompanySkillListQuery,
CompanySkillListItem,
CompanySkillProjectScanRequest,
CompanySkillProjectScanResult,
+ CompanySkillStarResult,
+ CompanySkillUpdateRequest,
CompanySkillUpdateStatus,
+ CompanySkillVersion,
+ CompanySkillVersionCreateRequest,
} from "@paperclipai/shared";
import { api } from "./client";
@@ -23,12 +33,66 @@ export interface CatalogListQuery {
}
export const companySkillsApi = {
- list: (companyId: string) =>
- api.get<CompanySkillListItem[]>(`/companies/${encodeURIComponent(companyId)}/skills`),
+ list: (companyId: string, query: CompanySkillListQuery = {}) => {
+ const params = new URLSearchParams();
+ if (query.q) params.set("q", query.q);
+ if (query.sort) params.set("sort", query.sort);
+ if (query.scope) params.set("scope", query.scope);
+ for (const category of query.categories ?? []) params.append("categories[]", category);
+ const search = params.toString();
+ return api.get<CompanySkillListItem[]>(`/companies/${encodeURIComponent(companyId)}/skills${search ? `?${search}` : ""}`);
+ },
+ categories: (companyId: string) =>
+ api.get<CompanySkillCategoryCount[]>(`/companies/${encodeURIComponent(companyId)}/skills/categories`),
detail: (companyId: string, skillId: string) =>
api.get<CompanySkillDetail>(
`/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}`,
),
+ versions: (companyId: string, skillId: string) =>
+ api.get<CompanySkillVersion[]>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/versions`,
+ ),
+ version: (companyId: string, skillId: string, versionId: string) =>
+ api.get<CompanySkillVersion>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/versions/${encodeURIComponent(versionId)}`,
+ ),
+ createVersion: (companyId: string, skillId: string, payload: CompanySkillVersionCreateRequest = {}) =>
+ api.post<CompanySkillVersion>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/versions`,
+ payload,
+ ),
+ star: (companyId: string, skillId: string) =>
+ api.post<CompanySkillStarResult>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/star`,
+ {},
+ ),
+ unstar: (companyId: string, skillId: string) =>
+ api.delete<CompanySkillStarResult>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/star`,
+ ),
+ fork: (companyId: string, skillId: string, payload: CompanySkillForkRequest = {}) =>
+ api.post<CompanySkill>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/fork`,
+ payload,
+ ),
+ comments: (companyId: string, skillId: string) =>
+ api.get<CompanySkillComment[]>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/comments`,
+ ),
+ createComment: (companyId: string, skillId: string, payload: CompanySkillCommentCreateRequest) =>
+ api.post<CompanySkillComment>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/comments`,
+ payload,
+ ),
+ updateComment: (companyId: string, skillId: string, commentId: string, payload: CompanySkillCommentUpdateRequest) =>
+ api.patch<CompanySkillComment>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/comments/${encodeURIComponent(commentId)}`,
+ payload,
+ ),
+ deleteComment: (companyId: string, skillId: string, commentId: string) =>
+ api.delete<CompanySkillComment>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/comments/${encodeURIComponent(commentId)}`,
+ ),
updateStatus: (companyId: string, skillId: string) =>
api.get<CompanySkillUpdateStatus>(
`/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/update-status`,
@@ -47,6 +111,11 @@ export const companySkillsApi = {
`/companies/${encodeURIComponent(companyId)}/skills`,
payload,
),
+ update: (companyId: string, skillId: string, payload: CompanySkillUpdateRequest) =>
+ api.patch<CompanySkill>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}`,
+ payload,
+ ),
importFromSource: (companyId: string, source: string) =>
api.post<CompanySkillImportResult>(
`/companies/${encodeURIComponent(companyId)}/skills/import`,
diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsx
index f6679d11ec..18fe7cc31a 100644
--- a/ui/src/components/Layout.tsx
+++ b/ui/src/components/Layout.tsx
@@ -78,6 +78,9 @@ export function Layout() {
const location = useLocation();
const navigationType = useNavigationType();
const isCompanySettingsRoute = location.pathname.includes("/company/settings");
+ // The Skills Store renders its own secondary (category) sidebar, so the main
+ // app nav collapses to its rail throughout the /skills section (PAP-10879).
+ const isSkillsRoute = /(^|\/)skills(\/|$)/.test(location.pathname);
const onboardingTriggered = useRef(false);
const lastMainScrollTop = useRef(0);
const previousPathname = useRef<string | null>(null);
@@ -148,10 +151,11 @@ export function Layout() {
// is active, but does NOT mutate the persisted preference. Clearing the force
// on cleanup restores the user's expanded/collapsed choice when navigating
// off the takeover route (PAP-10694).
+ const forceRailCollapsed = hasSecondarySidebar || isSkillsRoute;
useLayoutEffect(() => {
- setForceCollapsed(hasSecondarySidebar);
+ setForceCollapsed(forceRailCollapsed);
return () => setForceCollapsed(false);
- }, [hasSecondarySidebar, setForceCollapsed]);
+ }, [forceRailCollapsed, setForceCollapsed]);
useEffect(() => {
if (companiesLoading || onboardingTriggered.current) return;
@@ -536,7 +540,12 @@ export function Layout() {
tabIndex={-1}
className={cn(
"flex-1 p-4 outline-none md:p-6",
- isMobile ? "overflow-visible pb-[calc(5rem+env(safe-area-inset-bottom))]" : "overflow-auto",
+ // Reserve the scrollbar gutter on desktop so pages whose height
+ // changes (e.g. switching skill-detail tabs) don't widen/shift
+ // when the vertical scrollbar appears or disappears (PAP-10907).
+ isMobile
+ ? "overflow-visible pb-[calc(5rem+env(safe-area-inset-bottom))]"
+ : "overflow-auto [scrollbar-gutter:stable]",
)}
>
{hasUnknownCompanyPrefix ? (
diff --git a/ui/src/lib/company-skill-routes.test.ts b/ui/src/lib/company-skill-routes.test.ts
new file mode 100644
index 0000000000..b9040615d4
--- /dev/null
+++ b/ui/src/lib/company-skill-routes.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from "vitest";
+import {
+ canonicalSkillRouteToken,
+ parseSkillRoute,
+ resolveSkillRouteToken,
+ skillRoute,
+ type CompanySkillRouteSubject,
+} from "./company-skill-routes";
+
+function skill(id: string, slug: string, key = slug): CompanySkillRouteSubject {
+ return { id, slug, key };
+}
+
+const deepResearch = skill("11111111-1111-4111-8111-111111111111", "deep-research", "paperclip/deep-research");
+const scopedDeepResearch = skill("22222222-2222-4222-8222-222222222222", "deep-research", "community/deep-research");
+const browser = skill("33333333-3333-4333-8333-333333333333", "browser", "paperclip/browser");
+
+describe("company skill routes", () => {
+ it("builds unique slug detail and file routes", () => {
+ expect(canonicalSkillRouteToken(browser, [deepResearch, scopedDeepResearch, browser])).toBe("browser");
+ expect(skillRoute(browser, [deepResearch, scopedDeepResearch, browser])).toBe("/skills/browser");
+ expect(skillRoute(browser, [browser], "references/setup guide.md")).toBe(
+ "/skills/browser/files/references/setup%20guide.md",
+ );
+ });
+
+ it("uses a unique key to disambiguate colliding slugs", () => {
+ const skills = [deepResearch, scopedDeepResearch, browser];
+
+ expect(canonicalSkillRouteToken(deepResearch, skills)).toBe("paperclip/deep-research");
+ expect(canonicalSkillRouteToken(scopedDeepResearch, skills)).toBe("community/deep-research");
+ expect(skillRoute(deepResearch, skills)).toBe("/skills/paperclip/deep-research");
+ });
+
+ it("falls back to a slug plus short id when the key is not route-safe", () => {
+ const unsafe = skill("44444444-4444-4444-8444-444444444444", "deep-research", "paperclip/files/deep-research");
+ const skills = [deepResearch, unsafe];
+
+ expect(canonicalSkillRouteToken(unsafe, skills)).toBe("deep-research-44444444");
+ expect(skillRoute(unsafe, skills)).toBe("/skills/deep-research-44444444");
+ });
+
+ it("resolves legacy UUID URLs and asks callers to redirect to the canonical token", () => {
+ const resolution = resolveSkillRouteToken(browser.id, [browser]);
+
+ expect(resolution.skill?.id).toBe(browser.id);
+ expect(resolution.canonicalToken).toBe("browser");
+ expect(resolution.shouldRedirect).toBe(true);
+ });
+
+ it("resolves canonical key URLs for colliding slugs", () => {
+ const skills = [deepResearch, scopedDeepResearch];
+ const resolution = resolveSkillRouteToken("community/deep-research", skills);
+
+ expect(resolution.skill?.id).toBe(scopedDeepResearch.id);
+ expect(resolution.shouldRedirect).toBe(false);
+ expect(resolution.ambiguous).toBe(false);
+ });
+
+ it("leaves ambiguous bare slug URLs unresolved", () => {
+ const resolution = resolveSkillRouteToken("deep-research", [deepResearch, scopedDeepResearch]);
+
+ expect(resolution.skill).toBeNull();
+ expect(resolution.ambiguous).toBe(true);
+ });
+
+ it("parses token paths and encoded file paths", () => {
+ expect(parseSkillRoute("paperclip/deep-research/files/references/setup%20guide.md")).toEqual({
+ skillToken: "paperclip/deep-research",
+ filePath: "references/setup guide.md",
+ });
+ expect(parseSkillRoute(undefined)).toEqual({ skillToken: null, filePath: "SKILL.md" });
+ });
+});
diff --git a/ui/src/lib/company-skill-routes.ts b/ui/src/lib/company-skill-routes.ts
new file mode 100644
index 0000000000..f5fc9404aa
--- /dev/null
+++ b/ui/src/lib/company-skill-routes.ts
@@ -0,0 +1,192 @@
+import type { CompanySkill, CompanySkillDetail, CompanySkillListItem } from "@paperclipai/shared";
+
+export type CompanySkillRouteSubject = Pick<CompanySkill | CompanySkillDetail | CompanySkillListItem, "id" | "key" | "slug">;
+
+export type ParsedCompanySkillRoute = {
+ skillToken: string | null;
+ filePath: string;
+};
+
+export type CompanySkillRouteResolution = {
+ skill: CompanySkillRouteSubject | null;
+ canonicalToken: string | null;
+ shouldRedirect: boolean;
+ ambiguous: boolean;
+};
+
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+
+function decodeRouteSegment(segment: string) {
+ try {
+ return decodeURIComponent(segment);
+ } catch {
+ return segment;
+ }
+}
+
+function encodeRoutePath(value: string) {
+ return value.split("/").map((segment) => encodeURIComponent(segment)).join("/");
+}
+
+export function encodeSkillFilePath(filePath: string) {
+ return encodeRoutePath(filePath);
+}
+
+export function decodeSkillFilePath(filePath: string | undefined) {
+ if (!filePath) return "SKILL.md";
+ return filePath
+ .split("/")
+ .filter(Boolean)
+ .map(decodeRouteSegment)
+ .join("/");
+}
+
+function decodeSkillRouteToken(tokenPath: string | undefined) {
+ if (!tokenPath) return null;
+ const token = tokenPath
+ .split("/")
+ .filter(Boolean)
+ .map(decodeRouteSegment)
+ .join("/");
+ return token.length > 0 ? token : null;
+}
+
+export function parseSkillRoute(routePath: string | undefined): ParsedCompanySkillRoute {
+ const segments = (routePath ?? "").split("/").filter(Boolean);
+ if (segments.length === 0) {
+ return { skillToken: null, filePath: "SKILL.md" };
+ }
+
+ const filesIndex = segments.indexOf("files");
+ const tokenSegments = filesIndex >= 0 ? segments.slice(0, filesIndex) : segments;
+ const skillToken = decodeSkillRouteToken(tokenSegments.join("/"));
+ if (!skillToken) {
+ return { skillToken: null, filePath: "SKILL.md" };
+ }
+
+ return {
+ skillToken,
+ filePath: filesIndex >= 0 ? decodeSkillFilePath(segments.slice(filesIndex + 1).join("/")) : "SKILL.md",
+ };
+}
+
+function shortSkillId(skill: CompanySkillRouteSubject) {
+ return skill.id.replace(/-/g, "").slice(0, 8);
+}
+
+function slugShortIdToken(skill: CompanySkillRouteSubject) {
+ const slug = skill.slug.trim();
+ return `${slug || "skill"}-${shortSkillId(skill)}`;
+}
+
+function hasExactlyOneMatch(skills: CompanySkillRouteSubject[], predicate: (skill: CompanySkillRouteSubject) => boolean) {
+ return skills.filter(predicate).length === 1;
+}
+
+function isSafeKeyToken(skill: CompanySkillRouteSubject, skills: CompanySkillRouteSubject[]) {
+ const key = skill.key.trim();
+ if (!key || key.split("/").includes("files")) return false;
+ return !skills.some((candidate) =>
+ candidate.id !== skill.id
+ && (
+ candidate.key === key
+ || candidate.slug === key
+ || slugShortIdToken(candidate) === key
+ )
+ );
+}
+
+export function canonicalSkillRouteToken(
+ skill: CompanySkillRouteSubject,
+ skills: CompanySkillRouteSubject[] = [],
+) {
+ const slug = skill.slug.trim();
+ if (slug && hasExactlyOneMatch(skills.length > 0 ? skills : [skill], (candidate) => candidate.slug === slug)) {
+ return slug;
+ }
+
+ if (isSafeKeyToken(skill, skills)) {
+ return skill.key.trim();
+ }
+
+ return slugShortIdToken(skill);
+}
+
+function uniqueMatch(
+ skills: CompanySkillRouteSubject[],
+ predicate: (skill: CompanySkillRouteSubject) => boolean,
+) {
+ const matches = skills.filter(predicate);
+ if (matches.length !== 1) return { skill: null, ambiguous: matches.length > 1 };
+ return { skill: matches[0], ambiguous: false };
+}
+
+export function resolveSkillRouteToken(
+ token: string | null,
+ skills: CompanySkillRouteSubject[],
+): CompanySkillRouteResolution {
+ if (!token) {
+ return { skill: null, canonicalToken: null, shouldRedirect: false, ambiguous: false };
+ }
+
+ const legacyId = UUID_PATTERN.test(token) ? skills.find((skill) => skill.id === token) ?? null : null;
+ if (legacyId) {
+ return {
+ skill: legacyId,
+ canonicalToken: canonicalSkillRouteToken(legacyId, skills),
+ shouldRedirect: true,
+ ambiguous: false,
+ };
+ }
+
+ const canonical = uniqueMatch(skills, (skill) => canonicalSkillRouteToken(skill, skills) === token);
+ if (canonical.skill) {
+ return { skill: canonical.skill, canonicalToken: token, shouldRedirect: false, ambiguous: false };
+ }
+
+ const bySlug = uniqueMatch(skills, (skill) => skill.slug === token);
+ if (bySlug.skill) {
+ const canonicalToken = canonicalSkillRouteToken(bySlug.skill, skills);
+ return {
+ skill: bySlug.skill,
+ canonicalToken,
+ shouldRedirect: canonicalToken !== token,
+ ambiguous: false,
+ };
+ }
+ if (bySlug.ambiguous) {
+ return { skill: null, canonicalToken: null, shouldRedirect: false, ambiguous: true };
+ }
+
+ const byKey = uniqueMatch(skills, (skill) => skill.key === token);
+ if (byKey.skill) {
+ const canonicalToken = canonicalSkillRouteToken(byKey.skill, skills);
+ return {
+ skill: byKey.skill,
+ canonicalToken,
+ shouldRedirect: canonicalToken !== token,
+ ambiguous: false,
+ };
+ }
+
+ return { skill: null, canonicalToken: null, shouldRedirect: false, ambiguous: byKey.ambiguous };
+}
+
+export function skillRoute(
+ skill: CompanySkillRouteSubject | string,
+ skillsOrFilePath: CompanySkillRouteSubject[] | string | null = [],
+ filePath?: string | null,
+) {
+ const skills = Array.isArray(skillsOrFilePath) ? skillsOrFilePath : [];
+ const effectiveFilePath = Array.isArray(skillsOrFilePath) ? filePath : skillsOrFilePath;
+ const token = typeof skill === "string" ? skill : canonicalSkillRouteToken(skill, skills);
+ const basePath = `/skills/${encodeRoutePath(token)}`;
+ return effectiveFilePath ? `${basePath}/files/${encodeSkillFilePath(effectiveFilePath)}` : basePath;
+}
+
+export function withRouteSkill(
+ skills: CompanySkillRouteSubject[],
+ skill: CompanySkillRouteSubject,
+) {
+ return skills.some((candidate) => candidate.id === skill.id) ? skills : [...skills, skill];
+}
diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts
index 30a8e83774..790b881351 100644
--- a/ui/src/lib/queryKeys.ts
+++ b/ui/src/lib/queryKeys.ts
@@ -7,6 +7,8 @@ export const queryKeys = {
companySkills: {
list: (companyId: string) => ["company-skills", companyId] as const,
detail: (companyId: string, skillId: string) => ["company-skills", companyId, skillId] as const,
+ versions: (companyId: string, skillId: string) => ["company-skills", companyId, skillId, "versions"] as const,
+ comments: (companyId: string, skillId: string) => ["company-skills", companyId, skillId, "comments"] as const,
updateStatus: (companyId: string, skillId: string) =>
["company-skills", companyId, skillId, "update-status"] as const,
file: (companyId: string, skillId: string, relativePath: string) =>
diff --git a/ui/src/pages/CompanySkills.test.tsx b/ui/src/pages/CompanySkills.test.tsx
new file mode 100644
index 0000000000..df199276c4
--- /dev/null
+++ b/ui/src/pages/CompanySkills.test.tsx
@@ -0,0 +1,276 @@
+// @vitest-environment jsdom
+
+import type { ComponentProps, ReactNode } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import type { CompanySkillDetail, CompanySkillVersion } from "@paperclipai/shared";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { SkillDetailPage, getSkillVersionDiffSelection } from "./CompanySkills";
+
+vi.mock("@/lib/router", () => ({
+ Link: ({ children, to, ...props }: { children: ReactNode; to: string }) => (
+ <a href={to} {...props}>{children}</a>
+ ),
+ useNavigate: () => vi.fn(),
+ useParams: () => ({}),
+ useSearchParams: () => [new URLSearchParams(), vi.fn()],
+}));
+
+vi.mock("@/components/ui/button", () => ({
+ Button: ({
+ children,
+ type = "button",
+ variant: _variant,
+ size: _size,
+ asChild: _asChild,
+ ...props
+ }: ComponentProps<"button"> & { asChild?: boolean; variant?: string; size?: string }) => (
+ <button type={type} {...props}>{children}</button>
+ ),
+}));
+
+vi.mock("@/components/ui/dialog", () => ({
+ Dialog: ({ open, children }: { open?: boolean; children: ReactNode }) => (open ? <div>{children}</div> : null),
+ DialogContent: ({ children }: { children: ReactNode }) => <div role="dialog">{children}</div>,
+ DialogDescription: ({ children }: { children: ReactNode }) => <p>{children}</p>,
+ DialogFooter: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DialogHeader: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DialogTitle: ({ children }: { children: ReactNode }) => <h2>{children}</h2>,
+}));
+
+vi.mock("@/components/ui/dropdown-menu", () => ({
+ DropdownMenu: ({ children }: { children: ReactNode }) => <>{children}</>,
+ DropdownMenuContent: () => null,
+ DropdownMenuItem: ({ children, onSelect }: { children: ReactNode; onSelect?: () => void }) => (
+ <button type="button" onClick={onSelect}>{children}</button>
+ ),
+ DropdownMenuLabel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DropdownMenuRadioGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DropdownMenuRadioItem: ({ children, onSelect }: { children: ReactNode; onSelect?: () => void }) => (
+ <button type="button" onClick={onSelect}>{children}</button>
+ ),
+ DropdownMenuSeparator: () => <hr />,
+ DropdownMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/components/ui/popover", () => ({
+ Popover: ({ children }: { children: ReactNode }) => <>{children}</>,
+ PopoverContent: () => null,
+ PopoverTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
+ TooltipContent: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+ TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/components/ui/tabs", () => ({
+ Tabs: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ TabsList: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ TabsTrigger: ({ children }: { children: ReactNode }) => <button type="button">{children}</button>,
+}));
+
+vi.mock("@/components/ui/checkbox", () => ({
+ Checkbox: (props: ComponentProps<"input">) => <input type="checkbox" {...props} />,
+}));
+
+vi.mock("../components/MarkdownBody", () => ({
+ MarkdownBody: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+
+vi.mock("../components/MarkdownEditor", () => ({
+ MarkdownEditor: ({ value }: { value: string }) => <textarea readOnly value={value} />,
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root | null = null;
+let container: HTMLDivElement | null = null;
+
+async function act(callback: () => void | Promise<void>) {
+ let result: void | Promise<void> = undefined;
+ flushSync(() => {
+ result = callback();
+ });
+ await result;
+}
+
+afterEach(() => {
+ root?.unmount();
+ root = null;
+ container?.remove();
+ container = null;
+});
+
+function makeVersion(revisionNumber: number, content: string): CompanySkillVersion {
+ return {
+ id: `version-${revisionNumber}`,
+ companyId: "company-1",
+ companySkillId: "skill-1",
+ revisionNumber,
+ label: null,
+ fileInventory: [
+ {
+ path: "SKILL.md",
+ kind: "skill",
+ content,
+ },
+ ],
+ authorAgentId: null,
+ authorUserId: null,
+ createdAt: new Date(`2026-01-0${revisionNumber}T00:00:00Z`),
+ };
+}
+
+function makeDetail(currentVersion: CompanySkillVersion): CompanySkillDetail {
+ return {
+ id: "skill-1",
+ companyId: "company-1",
+ key: "demo-skill",
+ slug: "demo-skill",
+ name: "Demo Skill",
+ description: "A demo skill.",
+ markdown: "# Demo Skill",
+ sourceType: "local_path",
+ sourceLocator: null,
+ sourceRef: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ iconUrl: null,
+ color: null,
+ tagline: null,
+ authorName: null,
+ homepageUrl: null,
+ categories: [],
+ sharingScope: "private",
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 0,
+ installCount: 0,
+ forkCount: 0,
+ currentVersionId: currentVersion.id,
+ metadata: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ updatedAt: new Date("2026-01-02T00:00:00Z"),
+ attachedAgentCount: 0,
+ usedByAgents: [],
+ editable: true,
+ editableReason: null,
+ sourceLabel: "Local",
+ sourceBadge: "local",
+ sourcePath: null,
+ currentVersion,
+ starredByCurrentActor: false,
+ };
+}
+
+async function renderSkillDetail(versions: CompanySkillVersion[]) {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root?.render(
+ <SkillDetailPage
+ detail={makeDetail(versions[0]!)}
+ loading={false}
+ activeTab="versions"
+ onTabChange={vi.fn()}
+ selectedPath="SKILL.md"
+ file={null}
+ fileLoading={false}
+ viewMode="preview"
+ editMode={false}
+ draft=""
+ setViewMode={vi.fn()}
+ setEditMode={vi.fn()}
+ setDraft={vi.fn()}
+ onSave={vi.fn()}
+ savePending={false}
+ versions={versions}
+ versionsLoading={false}
+ attachAgents={[]}
+ onSubmitAttach={vi.fn()}
+ attachPending={false}
+ expandedDirs={new Set()}
+ onToggleDir={vi.fn()}
+ onSelectPath={vi.fn()}
+ updateStatus={null}
+ updateStatusLoading={false}
+ onCheckUpdates={vi.fn()}
+ checkUpdatesPending={false}
+ onInstallUpdate={vi.fn()}
+ installUpdatePending={false}
+ onToggleStar={vi.fn()}
+ starPending={false}
+ onFork={vi.fn()}
+ onUpdateSharingScope={vi.fn()}
+ updateSharingPending={false}
+ onDelete={vi.fn()}
+ deletePending={false}
+ />,
+ );
+ });
+
+ return container;
+}
+
+function buttonsNamed(node: ParentNode, name: string) {
+ return Array.from(node.querySelectorAll("button")).filter((button) => button.textContent?.trim() === name);
+}
+
+async function click(button: HTMLButtonElement) {
+ await act(async () => {
+ button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+}
+
+describe("getSkillVersionDiffSelection", () => {
+ it("selects the previous saved revision or the initial baseline for row diffs", () => {
+ const v1 = makeVersion(1, "first");
+ const v2 = makeVersion(2, "second");
+
+ expect(getSkillVersionDiffSelection([v2, v1], v2.id)).toEqual({
+ leftVersionId: v1.id,
+ rightVersionId: v2.id,
+ });
+ expect(getSkillVersionDiffSelection([v2, v1], v1.id)).toEqual({
+ leftVersionId: null,
+ rightVersionId: v1.id,
+ });
+ });
+});
+
+describe("SkillDetailPage versions tab", () => {
+ it("opens per-row version diffs for newest and oldest revisions", async () => {
+ const v1 = makeVersion(1, "# Demo Skill\n\nFirst line");
+ const v2 = makeVersion(2, "# Demo Skill\n\nSecond line");
+ const node = await renderSkillDetail([v2, v1]);
+ const viewDiffButtons = buttonsNamed(node, "View diff") as HTMLButtonElement[];
+
+ expect(viewDiffButtons).toHaveLength(2);
+
+ await click(viewDiffButtons[0]!);
+ let dialog = node.querySelector('[role="dialog"]') as HTMLElement;
+ let selects = Array.from(dialog.querySelectorAll("select"));
+
+ expect(dialog.textContent).toContain("Diff");
+ expect(selects[0]?.value).toBe(v1.id);
+ expect(selects[1]?.value).toBe(v2.id);
+ expect(dialog.textContent).toContain("Second line");
+
+ await click(viewDiffButtons[1]!);
+ dialog = node.querySelector('[role="dialog"]') as HTMLElement;
+ selects = Array.from(dialog.querySelectorAll("select"));
+
+ expect(selects[0]?.value).toBe("");
+ expect(selects[1]?.value).toBe(v1.id);
+ expect(dialog.textContent).toContain("Initial");
+ expect(dialog.textContent).toContain("First line");
+ expect(dialog.textContent).not.toContain("Both sides are the same version");
+ });
+});
diff --git a/ui/src/pages/CompanySkills.tsx b/ui/src/pages/CompanySkills.tsx
index ff2d3095dd..95e6e76cd9 100644
--- a/ui/src/pages/CompanySkills.tsx
+++ b/ui/src/pages/CompanySkills.tsx
@@ -1,10 +1,12 @@
-import { useEffect, useMemo, useState, type SVGProps } from "react";
+import { useEffect, useMemo, useRef, useState, type SVGProps } from "react";
import { Link, useNavigate, useParams, useSearchParams } from "@/lib/router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type {
+ AgentDesiredSkillEntry,
Agent,
CatalogSkill,
CatalogSkillFileDetail,
+ CatalogSkillSource,
CompanySkillCompatibility,
CompanySkillCreateRequest,
CompanySkillDetail,
@@ -12,9 +14,11 @@ import type {
CompanySkillFileInventoryEntry,
CompanySkillListItem,
CompanySkillProjectScanResult,
+ CompanySkillSharingScope,
CompanySkillSourceBadge,
CompanySkillTrustLevel,
CompanySkillUpdateStatus,
+ CompanySkillVersion,
} from "@paperclipai/shared";
import { companySkillsApi } from "../api/companySkills";
import { agentsApi } from "../api/agents";
@@ -28,6 +32,7 @@ import { MarkdownEditor } from "../components/MarkdownEditor";
import { PageSkeleton } from "../components/PageSkeleton";
import { CopyText } from "../components/CopyText";
import { Identity } from "../components/Identity";
+import { AgentIcon } from "../components/AgentIconPicker";
import { useAdapterCapabilities } from "../adapters/use-adapter-capabilities";
import {
Dialog,
@@ -55,7 +60,15 @@ import {
} from "@/components/ui/popover";
import { Checkbox } from "@/components/ui/checkbox";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { cn } from "../lib/utils";
+import { buildLineDiff, type DiffRow } from "../lib/line-diff";
+import { cn, relativeTime } from "../lib/utils";
+import {
+ parseSkillRoute,
+ skillRoute,
+ withRouteSkill,
+ resolveSkillRouteToken,
+ type CompanySkillRouteSubject,
+} from "../lib/company-skill-routes";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
@@ -65,6 +78,7 @@ import {
Boxes,
Check,
ChevronDown,
+ ChevronLeft,
ChevronRight,
Code2,
Download,
@@ -74,21 +88,29 @@ import {
FileText,
Folder,
FolderOpen,
+ GitFork,
Github,
Globe,
HelpCircle,
+ LayoutGrid,
Link2,
+ Lock,
ExternalLink,
Paperclip,
+ Pause,
Pencil,
+ Pin,
Plus,
Copy,
RefreshCw,
Save,
Search,
+ Settings,
ShieldCheck,
+ Star,
Trash2,
Users,
+ History,
XOctagon,
} from "lucide-react";
@@ -230,51 +252,6 @@ function fileIcon(kind: CompanySkillFileInventoryEntry["kind"]) {
return FileText;
}
-function encodeSkillFilePath(filePath: string) {
- return filePath.split("/").map((segment) => encodeURIComponent(segment)).join("/");
-}
-
-function decodeSkillFilePath(filePath: string | undefined) {
- if (!filePath) return "SKILL.md";
- return filePath
- .split("/")
- .filter(Boolean)
- .map((segment) => {
- try {
- return decodeURIComponent(segment);
- } catch {
- return segment;
- }
- })
- .join("/");
-}
-
-function parseSkillRoute(routePath: string | undefined) {
- const segments = (routePath ?? "").split("/").filter(Boolean);
- if (segments.length === 0) {
- return { skillId: null, filePath: "SKILL.md" };
- }
-
- const [rawSkillId, rawMode, ...rest] = segments;
- const skillId = rawSkillId ? decodeURIComponent(rawSkillId) : null;
- if (!skillId) {
- return { skillId: null, filePath: "SKILL.md" };
- }
-
- if (rawMode === "files") {
- return {
- skillId,
- filePath: decodeSkillFilePath(rest.join("/")),
- };
- }
-
- return { skillId, filePath: "SKILL.md" };
-}
-
-function skillRoute(skillId: string, filePath?: string | null) {
- return filePath ? `/skills/${skillId}/files/${encodeSkillFilePath(filePath)}` : `/skills/${skillId}`;
-}
-
function catalogSkillRoute(catalogRef: string) {
return `/skills?view=catalog&catalog=${encodeURIComponent(catalogRef)}`;
}
@@ -519,222 +496,1189 @@ function formatBytes(bytes: number) {
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
-function NewSkillForm({
- onCreate,
- isPending,
- onCancel,
-}: {
- onCreate: (payload: CompanySkillCreateRequest) => void;
- isPending: boolean;
- onCancel: () => void;
-}) {
- const [name, setName] = useState("");
- const [slug, setSlug] = useState("");
- const [description, setDescription] = useState("");
+// Some bundled skills ship with a frontmatter-only SKILL.md whose extracted
+// description is just punctuation (e.g. ">"). Strip leading markdown syntax and
+// fall back to a neutral placeholder so cards don't render bare glyphs.
+function cardDescriptionText(raw: string | null | undefined): string {
+ const cleaned = (raw ?? "")
+ .replace(/^[\s>#*_\-`>]+/, "")
+ .trim();
+ // Empty descriptions render as a blank line on cards so spacing stays
+ // consistent across the grid (PAP-10907).
+ return cleaned.length >= 3 ? cleaned : "";
+}
+
+// ---------------------------------------------------------------------------
+// Skills Store discovery grid (PAP-10879)
+// ---------------------------------------------------------------------------
+
+type DiscoveryTab = "all" | "installed" | "catalog" | "bundled";
+
+const DISCOVERY_TABS: DiscoveryTab[] = ["all", "installed", "catalog", "bundled"];
+
+type DiscoverySort = "agents" | "stars" | "forks" | "recent" | "alphabetical";
+
+const DISCOVERY_SORT_LABELS: Record<DiscoverySort, string> = {
+ agents: "Most agents",
+ stars: "Most stars",
+ forks: "Most forks",
+ recent: "Recently updated",
+ alphabetical: "Alphabetical",
+};
+const DISCOVERY_SORTS: DiscoverySort[] = ["agents", "stars", "forks", "recent", "alphabetical"];
+
+export type DiscoveryCard = {
+ key: string;
+ skillId: string | null;
+ catalogRef: string | null;
+ name: string;
+ slug: string;
+ author: string;
+ version: string | null;
+ description: string | null;
+ categories: string[];
+ iconUrl: string | null;
+ color: string | null;
+ starCount: number;
+ agentCount: number;
+ forkCount: number;
+ installed: boolean;
+ required: boolean;
+ forkedFrom: boolean;
+ updatedAt: number;
+ sourceBadge?: CompanySkillSourceBadge | null;
+ sourceLabel?: string | null;
+};
+
+// Stable palette used to auto-assign an accent colour to a skill when the
+// backend has not stored an explicit one. Colour is derived from the skill key
+// so the same skill always lands on the same hue.
+const DISCOVERY_ACCENTS = [
+ "#6366f1", "#0ea5e9", "#10b981", "#f59e0b", "#ef4444",
+ "#8b5cf6", "#ec4899", "#14b8a6", "#f97316", "#22c55e",
+ "#3b82f6", "#a855f7",
+];
+
+function skillAccentColor(key: string, explicit: string | null | undefined): string {
+ const trimmed = explicit?.trim();
+ if (trimmed) return trimmed;
+ let hash = 0;
+ for (let i = 0; i < key.length; i += 1) hash = (hash * 31 + key.charCodeAt(i)) >>> 0;
+ return DISCOVERY_ACCENTS[hash % DISCOVERY_ACCENTS.length];
+}
+
+function SkillCardIcon({ card, size = 36 }: { card: DiscoveryCard; size?: number }) {
+ if (card.iconUrl) {
+ return (
+ <img
+ src={card.iconUrl}
+ alt=""
+ className="shrink-0 rounded-md object-cover"
+ style={{ width: size, height: size }}
+ />
+ );
+ }
+ const accent = skillAccentColor(card.key, card.color);
+ const letter = (card.slug || card.name || "?").trim().charAt(0).toUpperCase();
return (
- <div className="border-b border-border px-4 py-4">
- <div className="space-y-3">
- <Input
- value={name}
- onChange={(event) => setName(event.target.value)}
- placeholder="Skill name"
- className="h-9 rounded-none border-0 border-b border-border px-0 shadow-none focus-visible:ring-0"
- />
- <Input
- value={slug}
- onChange={(event) => setSlug(event.target.value)}
- placeholder="optional-shortname"
- className="h-9 rounded-none border-0 border-b border-border px-0 shadow-none focus-visible:ring-0"
- />
- <Textarea
- value={description}
- onChange={(event) => setDescription(event.target.value)}
- placeholder="Short description"
- className="min-h-20 rounded-none border-0 border-b border-border px-0 shadow-none focus-visible:ring-0"
- />
- <div className="flex items-center justify-end gap-2">
- <Button variant="ghost" size="sm" onClick={onCancel} disabled={isPending}>
- Cancel
- </Button>
- <Button
- size="sm"
- onClick={() => onCreate({ name, slug: slug || null, description: description || null })}
- disabled={isPending || name.trim().length === 0}
- >
- {isPending ? "Creating..." : "Create skill"}
- </Button>
- </div>
- </div>
- </div>
+ <span
+ aria-hidden="true"
+ className="flex shrink-0 items-center justify-center rounded-md font-semibold text-white"
+ style={{ width: size, height: size, backgroundColor: accent, fontSize: Math.round(size * 0.42) }}
+ >
+ {letter}
+ </span>
);
}
-function CatalogList({
- skills,
- kindFilter,
- categoryFilter,
- catalogFilter,
- installedByKey,
- selectedCatalogRef,
- selectedPath,
- expandedSkillId,
- expandedDirs,
- onSelect,
- onSelectPath,
- onToggleSkill,
- onToggleDir,
-}: {
- skills: CatalogSkill[];
- kindFilter: "all" | "bundled" | "optional";
- categoryFilter: string;
- catalogFilter: string;
- installedByKey: Map<string, CompanySkillListItem>;
- selectedCatalogRef: string | null;
- selectedPath: string;
- expandedSkillId: string | null;
- expandedDirs: Record<string, Set<string>>;
- onSelect: (catalogRef: string) => void;
- onSelectPath: (catalogRef: string, path: string) => void;
- onToggleSkill: (catalogRef: string) => void;
- onToggleDir: (catalogRef: string, path: string) => void;
-}) {
- const lowered = catalogFilter.trim().toLowerCase();
- const filtered = skills.filter((skill) => {
- if (kindFilter !== "all" && skill.kind !== kindFilter) return false;
- if (categoryFilter && skill.category !== categoryFilter) return false;
- if (!lowered) return true;
- const haystack = `${skill.name} ${skill.slug} ${skill.key} ${skill.description} ${skill.category} ${skill.tags.join(" ")} ${skill.recommendedForRoles.join(" ")}`.toLowerCase();
- return haystack.includes(lowered);
- });
+function discoveryVersionLabel(skill: {
+ packageVersion: string | null;
+ sourceRef: string | null;
+}, required: boolean): string | null {
+ if (skill.packageVersion) return `v${skill.packageVersion}`;
+ if (required) return "core";
+ if (skill.sourceRef) return shortRef(skill.sourceRef);
+ return null;
+}
- if (filtered.length === 0) {
- return (
- <div className="px-4 py-6 text-sm text-muted-foreground">
- No catalog skills match this filter.
- </div>
- );
+function uniqueCategories(values: (string | null | undefined)[]): string[] {
+ const out: string[] = [];
+ const seen = new Set<string>();
+ for (const value of values) {
+ const slug = value?.trim();
+ if (!slug || seen.has(slug)) continue;
+ seen.add(slug);
+ out.push(slug);
}
+ return out;
+}
- const available = filtered.filter((skill) => !installedByKey.has(skill.key));
- const installed = filtered.filter((skill) => installedByKey.has(skill.key));
- const bundled = available.filter((skill) => skill.kind === "bundled");
- const optional = available.filter((skill) => skill.kind === "optional");
+function normalizeSkillDraftSlug(value: string) {
+ return value
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 80);
+}
- function renderRow(skill: CatalogSkill) {
- const isSelected = selectedCatalogRef === skill.id || selectedCatalogRef === skill.key;
- const expanded = expandedSkillId === skill.id;
- const tree = buildTree(skill.files.map((file) => ({
- path: file.path,
- kind: file.kind,
- })));
- return (
- <div key={skill.id} className="border-b border-border">
- <div
- className={cn(
- "group grid grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-x-1 px-3 py-1.5 hover:bg-accent/30",
- isSelected && "text-foreground",
- )}
- >
- <Link
- to={catalogSkillRoute(skill.id)}
- className="flex min-w-0 items-center self-stretch pr-2 text-left no-underline"
- onClick={() => onSelect(skill.id)}
- >
- <span className="flex min-w-0 items-center gap-2 self-center">
- <span className="flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground opacity-75 transition-opacity group-hover:opacity-100">
- <Boxes className={cn("h-3.5 w-3.5", skill.kind === "optional" && "opacity-70")} aria-hidden="true" />
- </span>
- <span className="min-w-0 overflow-hidden text-[13px] font-medium leading-5 [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:3]">
- {skill.name}
- </span>
- </span>
- </Link>
- <button
- type="button"
- className="flex h-9 w-9 shrink-0 items-center justify-center self-center rounded-sm text-muted-foreground opacity-80 transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground group-hover:opacity-100"
- onClick={() => onToggleSkill(skill.id)}
- aria-label={expanded ? `Collapse ${skill.name}` : `Expand ${skill.name}`}
- >
- {expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
- </button>
- </div>
- <div
- aria-hidden={!expanded}
- className={cn(
- "grid overflow-hidden transition-[grid-template-rows,opacity] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)]",
- expanded ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0",
- )}
- >
- <div className="min-h-0 overflow-hidden">
- <SkillTree
- nodes={tree}
- skillId={skill.id}
- selectedPath={isSelected ? selectedPath : "SKILL.md"}
- expandedDirs={expandedDirs[skill.id] ?? new Set<string>()}
- onToggleDir={(path) => onToggleDir(skill.id, path)}
- onSelectPath={(path) => onSelectPath(skill.id, path)}
- fileHref={(skillId) => catalogSkillRoute(skillId)}
- depth={1}
- />
- </div>
- </div>
- </div>
- );
+function splitCategoryDraft(value: string) {
+ return value
+ .split(",")
+ .map((entry) => normalizeSkillDraftSlug(entry))
+ .filter(Boolean);
+}
+
+function defaultSkillMarkdown(name: string, tagline: string) {
+ const title = name.trim() || "New Skill";
+ const summary = tagline.trim() || "Describe when agents should use this skill.";
+ return [
+ "---",
+ `name: ${title}`,
+ `description: ${summary}`,
+ "---",
+ "",
+ `# ${title}`,
+ "",
+ summary,
+ "",
+ "## When To Use",
+ "",
+ "- Use this skill when the task needs its specialized workflow.",
+ "",
+ "## Workflow",
+ "",
+ "1. Inspect the task context.",
+ "2. Apply the workflow carefully.",
+ "3. Report what changed and how it was verified.",
+ "",
+ ].join("\n");
+}
+
+// Merge installed company skills and the install catalog into one card model.
+// Installed skills win on dedup (they carry the richer social-proof metadata);
+// catalog-only skills fill in the rest of the discoverable surface.
+function buildDiscoveryCards(
+ installed: CompanySkillListItem[],
+ catalog: CatalogSkill[],
+): DiscoveryCard[] {
+ const catalogByKey = new Map(catalog.map((entry) => [entry.key, entry]));
+ const cards: DiscoveryCard[] = [];
+ const installedKeys = new Set<string>();
+
+ for (const skill of installed) {
+ installedKeys.add(skill.key);
+ const catalogMatch = catalogByKey.get(skill.key) ?? null;
+ const required = skill.catalogKind === "bundled" || catalogMatch?.kind === "bundled";
+ cards.push({
+ key: skill.key,
+ skillId: skill.id,
+ catalogRef: catalogMatch ? catalogMatch.id : null,
+ name: skill.name,
+ slug: skill.slug,
+ author: skill.authorName ?? skill.sourceLabel ?? "you",
+ version: discoveryVersionLabel(skill, required),
+ description: skill.tagline ?? skill.description,
+ categories: uniqueCategories([...(skill.categories ?? []), catalogMatch?.category]),
+ iconUrl: skill.iconUrl,
+ color: skill.color,
+ starCount: skill.starCount ?? 0,
+ agentCount: skill.attachedAgentCount ?? 0,
+ forkCount: skill.forkCount ?? 0,
+ installed: true,
+ required,
+ forkedFrom: Boolean(skill.forkedFromSkillId),
+ updatedAt: new Date(skill.updatedAt).getTime() || 0,
+ sourceBadge: skill.sourceBadge,
+ sourceLabel: skill.sourceLabel,
+ });
+ }
+
+ for (const entry of catalog) {
+ if (installedKeys.has(entry.key)) continue;
+ const required = entry.kind === "bundled";
+ cards.push({
+ key: entry.key,
+ skillId: null,
+ catalogRef: entry.id,
+ name: entry.name,
+ slug: entry.slug,
+ author: entry.packageName ?? "Paperclip",
+ version: discoveryVersionLabel({ packageVersion: entry.packageVersion ?? null, sourceRef: null }, required),
+ description: entry.description,
+ categories: uniqueCategories([entry.category, ...(entry.tags ?? [])]),
+ iconUrl: null,
+ color: null,
+ starCount: 0,
+ agentCount: 0,
+ forkCount: 0,
+ installed: false,
+ required,
+ forkedFrom: false,
+ updatedAt: 0,
+ sourceBadge: "catalog",
+ sourceLabel: entry.packageName ?? "Catalog",
+ });
}
+ return cards;
+}
+
+function cardsForTab(cards: DiscoveryCard[], tab: DiscoveryTab): DiscoveryCard[] {
+ switch (tab) {
+ case "installed":
+ return cards.filter((card) => card.installed);
+ case "catalog":
+ return cards.filter((card) => card.catalogRef != null);
+ case "bundled":
+ return cards.filter((card) => card.required);
+ case "all":
+ default:
+ return cards;
+ }
+}
+
+function sortDiscoveryCards(cards: DiscoveryCard[], sort: DiscoverySort, demoteRequired: boolean): DiscoveryCard[] {
+ const byName = (a: DiscoveryCard, b: DiscoveryCard) => a.name.localeCompare(b.name);
+ const sorted = [...cards].sort((a, b) => {
+ // Bundled/required skills are demoted out of discovery rankings (except on
+ // the Bundled tab, where they are the whole point).
+ if (demoteRequired && a.required !== b.required) return a.required ? 1 : -1;
+ switch (sort) {
+ case "stars":
+ return b.starCount - a.starCount || byName(a, b);
+ case "forks":
+ return b.forkCount - a.forkCount || byName(a, b);
+ case "recent":
+ return b.updatedAt - a.updatedAt || byName(a, b);
+ case "alphabetical":
+ return byName(a, b);
+ case "agents":
+ default:
+ return b.agentCount - a.agentCount || byName(a, b);
+ }
+ });
+ return sorted;
+}
+
+function discoveryMatchesSearch(card: DiscoveryCard, query: string): boolean {
+ if (!query) return true;
+ const haystack = [
+ card.name,
+ card.slug,
+ card.author,
+ card.description ?? "",
+ card.categories.join(" "),
+ ].join(" ").toLowerCase();
+ return haystack.includes(query.toLowerCase());
+}
+
+function SkillStat({ icon: Icon, value }: { icon: typeof Star; value: string }) {
return (
- <div>
- {bundled.length > 0 && kindFilter !== "optional" ? (
- <div>
- <div className="border-b border-border bg-background px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
- Bundled · {bundled.length}
+ <span className="inline-flex items-center gap-1">
+ <Icon className="h-3 w-3" aria-hidden="true" />
+ {value}
+ </span>
+ );
+}
+
+function SkillCategoryChip({ label }: { label: string }) {
+ return (
+ <span className="inline-flex items-center rounded-full border border-border bg-muted/40 px-2 py-0.5 text-[10px] capitalize text-muted-foreground">
+ {label}
+ </span>
+ );
+}
+
+function SkillCard({ card, onOpen }: { card: DiscoveryCard; onOpen: (card: DiscoveryCard) => void }) {
+ return (
+ <button
+ type="button"
+ onClick={() => onOpen(card)}
+ className={cn(
+ "group flex h-full min-h-[11.5rem] flex-col rounded-md border border-border p-4 text-left transition-colors hover:border-primary hover:bg-accent/30 hover:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ card.required && "bg-muted/30",
+ )}
+ >
+ <div className="flex items-start gap-3">
+ <SkillCardIcon card={card} />
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-mono text-sm font-medium text-foreground">{card.name}</div>
+ <div className="truncate text-xs text-muted-foreground">
+ by {card.author}{card.version ? ` · ${card.version}` : ""}
</div>
- {bundled.map(renderRow)}
</div>
- ) : null}
- {optional.length > 0 && kindFilter !== "bundled" ? (
- <div>
- <div className="border-b border-border bg-background px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
- Optional · {optional.length}
- </div>
- {optional.map(renderRow)}
+ {/* Where the skill came from (PAP-10907 E); native title gives a hover hint. */}
+ {(() => {
+ const meta = sourceMeta(card.sourceBadge ?? "catalog", card.sourceLabel ?? null);
+ const SourceIcon = meta.icon;
+ return (
+ <span className="shrink-0 text-muted-foreground" title={`From ${meta.label}`} aria-label={`From ${meta.label}`}>
+ <SourceIcon className="h-3.5 w-3.5" aria-hidden="true" />
+ </span>
+ );
+ })()}
+ </div>
+
+ {card.forkedFrom ? (
+ <div className="mt-2 inline-flex items-center gap-1 text-[11px] text-muted-foreground">
+ <GitFork className="h-3 w-3" aria-hidden="true" />
+ Forked
</div>
) : null}
- {installed.length > 0 ? (
- <div>
- <div className="border-b border-border bg-background px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
- Installed · {installed.length}
- </div>
- {installed.map(renderRow)}
+
+ {/* Always reserve two lines so cards line up even without a description. */}
+ <p className="mt-2 line-clamp-2 min-h-8 text-xs text-muted-foreground">
+ {cardDescriptionText(card.description)}
+ </p>
+
+ <div className="mt-auto pt-3">
+ {/* Stats: installed agents · stars · forks — stars/forks only when > 0. */}
+ <div className="flex items-center gap-2 text-[11px] text-muted-foreground">
+ <span>{card.agentCount} {card.agentCount === 1 ? "agent" : "agents"}</span>
+ {card.starCount > 0 ? (
+ <>
+ <span aria-hidden="true">·</span>
+ <SkillStat icon={Star} value={String(card.starCount)} />
+ </>
+ ) : null}
+ {card.forkCount > 0 ? (
+ <>
+ <span aria-hidden="true">·</span>
+ <SkillStat icon={GitFork} value={String(card.forkCount)} />
+ </>
+ ) : null}
</div>
- ) : null}
- </div>
+ <div className="mt-2 flex flex-wrap items-center gap-1">
+ {card.installed ? (
+ <span className="inline-flex items-center rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2 py-0.5 text-[10px] text-emerald-300">
+ Installed
+ </span>
+ ) : null}
+ {card.categories.slice(0, 2).map((category) => (
+ <SkillCategoryChip key={category} label={category} />
+ ))}
+ {card.required ? (
+ <span className="ml-auto inline-flex items-center gap-1 rounded-full border border-border bg-muted/60 px-2 py-0.5 text-[10px] text-muted-foreground">
+ <Lock className="h-3 w-3" aria-hidden="true" />
+ Bundled
+ </span>
+ ) : null}
+ </div>
+ </div>
+ </button>
);
}
-function CatalogDetailPane({
- skill,
- packageName,
- packageVersion,
- installedSkill,
- installedSkillId,
- fileQuery,
- selectedPath,
- onInstall,
- onUpdate,
- onOpenInstalled,
- loadingPrimaryAction,
+export type DiscoveryCategory = { slug: string; count: number };
+
+function CategoryNav({
+ categories,
+ total,
+ active,
+ onSelect,
}: {
- skill: CatalogSkill | null;
- packageName: string | null;
- packageVersion: string | null;
- installedSkill: CompanySkillListItem | null;
- installedSkillId: string | null;
- fileQuery: { data: CatalogSkillFileDetail | undefined; isLoading: boolean; error: unknown };
- selectedPath: string;
- onInstall: () => void;
- onUpdate: () => void;
+ categories: DiscoveryCategory[];
+ total: number;
+ active: string | null;
+ onSelect: (slug: string | null) => void;
+}) {
+ return (
+ <nav className="flex flex-col gap-0.5 px-2">
+ <button
+ type="button"
+ onClick={() => onSelect(null)}
+ className={cn(
+ "flex items-center justify-between rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-accent/40",
+ active == null ? "bg-accent/60 font-medium text-foreground" : "text-muted-foreground",
+ )}
+ >
+ <span>All</span>
+ <span className="text-xs text-muted-foreground">{total}</span>
+ </button>
+ {categories.map((category) => (
+ <button
+ key={category.slug}
+ type="button"
+ onClick={() => onSelect(category.slug)}
+ className={cn(
+ "flex items-center justify-between rounded-md px-2 py-1.5 text-sm capitalize transition-colors hover:bg-accent/40",
+ active === category.slug ? "bg-accent/60 font-medium text-foreground" : "text-muted-foreground",
+ )}
+ >
+ <span className="truncate">{category.slug}</span>
+ <span className="ml-2 shrink-0 text-xs text-muted-foreground">{category.count}</span>
+ </button>
+ ))}
+ </nav>
+ );
+}
+
+export function DiscoveryGrid({
+ tab,
+ tabCounts,
+ onTabChange,
+ categories,
+ categoryTotal,
+ activeCategory,
+ onCategoryChange,
+ search,
+ onSearchChange,
+ sort,
+ onSortChange,
+ cards,
+ onOpenCard,
+ loading,
+ error,
+ totalCount,
+ onCreate,
+ onImport,
+ onBrowseCatalog,
+ onScan,
+ scanPending,
+ scanStatus,
+}: {
+ tab: DiscoveryTab;
+ tabCounts: Record<DiscoveryTab, number>;
+ onTabChange: (tab: DiscoveryTab) => void;
+ categories: DiscoveryCategory[];
+ categoryTotal: number;
+ activeCategory: string | null;
+ onCategoryChange: (slug: string | null) => void;
+ search: string;
+ onSearchChange: (value: string) => void;
+ sort: DiscoverySort;
+ onSortChange: (sort: DiscoverySort) => void;
+ cards: DiscoveryCard[];
+ onOpenCard: (card: DiscoveryCard) => void;
+ loading: boolean;
+ error: string | null;
+ totalCount: number;
+ onCreate: () => void;
+ onImport: () => void;
+ onBrowseCatalog: () => void;
+ onScan: () => void;
+ scanPending: boolean;
+ scanStatus: string | null;
+}) {
+ // Source filter (github / skills.sh / local / …) lives in the grid so it
+ // narrows whatever the parent already filtered by tab/category/search (PAP-10907 E).
+ const [sourceBadgeFilter, setSourceBadgeFilter] = useState<string>("all");
+ const availableSources = useMemo(() => {
+ const set = new Set<string>();
+ for (const card of cards) if (card.sourceBadge) set.add(card.sourceBadge);
+ return Array.from(set).sort();
+ }, [cards]);
+ useEffect(() => {
+ if (sourceBadgeFilter !== "all" && !availableSources.includes(sourceBadgeFilter)) {
+ setSourceBadgeFilter("all");
+ }
+ }, [availableSources, sourceBadgeFilter]);
+ const sourceFilteredCards = useMemo(
+ () => (sourceBadgeFilter === "all" ? cards : cards.filter((card) => card.sourceBadge === sourceBadgeFilter)),
+ [cards, sourceBadgeFilter],
+ );
+ const sourceFilterActive = sourceBadgeFilter !== "all";
+
+ return (
+ // On desktop the store is bounded to the viewport so the category sidebar
+ // and the results pane each scroll independently (PAP-10907). Mobile keeps
+ // the natural page flow.
+ <div className="flex min-h-[calc(100vh-12rem)] md:h-[calc(100dvh-6rem)] md:min-h-0 md:overflow-hidden">
+ {/* Secondary category sidebar — the main app nav collapses to a rail while
+ this is present (handled in Layout). */}
+ <aside className="hidden w-60 shrink-0 flex-col overflow-hidden border-r border-border md:flex">
+ <div className="border-b border-border px-4 py-4">
+ <h2 className="text-sm font-semibold text-foreground">Skills Store</h2>
+ <p className="text-xs text-muted-foreground">Discover, install, fork, share</p>
+ </div>
+ <div className="px-4 pb-1 pt-3 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
+ Categories
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto pb-4">
+ <CategoryNav
+ categories={categories}
+ total={categoryTotal}
+ active={activeCategory}
+ onSelect={onCategoryChange}
+ />
+ </div>
+ </aside>
+
+ <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
+ {/* Search + sort + actions */}
+ <div className="flex flex-wrap items-center gap-2 border-b border-border px-4 py-3">
+ <div className="flex h-9 min-w-[12rem] flex-1 items-center gap-2 rounded-md border border-border px-2.5">
+ <Search className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <input
+ value={search}
+ onChange={(event) => onSearchChange(event.target.value)}
+ placeholder="Search skills, authors, categories…"
+ className="h-full w-full bg-transparent text-base outline-none placeholder:text-muted-foreground sm:text-sm"
+ />
+ </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" size="sm">
+ <span className="text-muted-foreground">Sort</span>
+ <span className="ml-1.5">{DISCOVERY_SORT_LABELS[sort]}</span>
+ <ChevronDown className="ml-1 h-3.5 w-3.5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuRadioGroup value={sort} onValueChange={(value) => onSortChange(value as DiscoverySort)}>
+ {DISCOVERY_SORTS.map((option) => (
+ <DropdownMenuRadioItem key={option} value={option}>
+ {DISCOVERY_SORT_LABELS[option]}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {availableSources.length > 1 ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" size="sm">
+ <span className="text-muted-foreground">Source</span>
+ <span className="ml-1.5 capitalize">
+ {sourceBadgeFilter === "all" ? "All" : sourceMeta(sourceBadgeFilter as CompanySkillSourceBadge, null).label}
+ </span>
+ <ChevronDown className="ml-1 h-3.5 w-3.5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuRadioGroup value={sourceBadgeFilter} onValueChange={setSourceBadgeFilter}>
+ <DropdownMenuRadioItem value="all">All sources</DropdownMenuRadioItem>
+ {availableSources.map((badge) => (
+ <DropdownMenuRadioItem key={badge} value={badge}>
+ {sourceMeta(badge as CompanySkillSourceBadge, null).label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={onScan}
+ disabled={scanPending}
+ title="Scan project workspaces for skills"
+ >
+ <RefreshCw className={cn("h-4 w-4", scanPending && "animate-spin")} />
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button size="sm" variant="default">
+ <Plus className="mr-1 h-3.5 w-3.5" />
+ New
+ <ChevronDown className="ml-1 h-3.5 w-3.5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onSelect={onCreate}>
+ <Pencil className="mr-2 h-4 w-4" />
+ Create new skill
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={onBrowseCatalog}>
+ <Boxes className="mr-2 h-4 w-4" />
+ Browse catalog
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={onImport}>
+ <Globe className="mr-2 h-4 w-4" />
+ Import from path or URL
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+
+ {/* Mobile category selector (sidebar is hidden below md) */}
+ {categories.length > 0 ? (
+ <div className="border-b border-border px-4 py-2 md:hidden">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" size="sm" className="w-full justify-between">
+ <span className="capitalize">{activeCategory ?? "All categories"}</span>
+ <ChevronDown className="h-3.5 w-3.5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="max-h-72 overflow-auto">
+ <DropdownMenuRadioGroup
+ value={activeCategory ?? "__all__"}
+ onValueChange={(value) => onCategoryChange(value === "__all__" ? null : value)}
+ >
+ <DropdownMenuRadioItem value="__all__">All ({categoryTotal})</DropdownMenuRadioItem>
+ {categories.map((category) => (
+ <DropdownMenuRadioItem key={category.slug} value={category.slug} className="capitalize">
+ {category.slug} ({category.count})
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ ) : null}
+
+ {/* Tab strip — Bundled/required lives at the end */}
+ <div className="border-b border-border px-4">
+ <Tabs value={tab} onValueChange={(value) => onTabChange(value as DiscoveryTab)}>
+ <TabsList variant="line" className="p-0">
+ <TabsTrigger value="all" className="px-3">
+ <span>All</span>
+ <span className="ml-1.5 text-[11px] text-muted-foreground">{tabCounts.all}</span>
+ </TabsTrigger>
+ <TabsTrigger value="installed" className="px-3">
+ <span>Installed</span>
+ <span className="ml-1.5 text-[11px] text-muted-foreground">{tabCounts.installed}</span>
+ </TabsTrigger>
+ <TabsTrigger value="catalog" className="px-3">
+ <span>Catalog</span>
+ <span className="ml-1.5 text-[11px] text-muted-foreground">{tabCounts.catalog}</span>
+ </TabsTrigger>
+ <TabsTrigger value="bundled" className="px-3">
+ <span>Bundled</span>
+ <span className="ml-1.5 text-[11px] text-muted-foreground">{tabCounts.bundled}</span>
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </div>
+
+ {/* Grid body */}
+ <div className="min-h-0 flex-1 overflow-auto p-4">
+ {scanStatus ? <p className="mb-3 text-xs text-muted-foreground">{scanStatus}</p> : null}
+ {loading ? (
+ <PageSkeleton variant="list" />
+ ) : error ? (
+ <div className="py-6 text-sm text-destructive">{error}</div>
+ ) : sourceFilteredCards.length === 0 ? (
+ <div className="py-12">
+ <EmptyState
+ icon={LayoutGrid}
+ message={
+ totalCount === 0
+ ? "No skills yet. Create one or install from the catalog."
+ : search || activeCategory || sourceFilterActive
+ ? "No skills match your filters."
+ : "No skills in this tab yet."
+ }
+ />
+ {totalCount === 0 ? (
+ <div className="mt-3 flex flex-col items-center gap-2">
+ <Button size="sm" onClick={onBrowseCatalog}>
+ <Boxes className="mr-1.5 h-3.5 w-3.5" /> Browse catalog
+ </Button>
+ <Button size="sm" variant="ghost" onClick={onCreate}>
+ Create a skill
+ </Button>
+ </div>
+ ) : (search || activeCategory || sourceFilterActive) ? (
+ <div className="mt-3 flex justify-center">
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => {
+ onSearchChange("");
+ onCategoryChange(null);
+ setSourceBadgeFilter("all");
+ }}
+ >
+ Clear filters
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ ) : (
+ <>
+ <p className="mb-3 text-xs text-muted-foreground">
+ {sourceFilteredCards.length} {sourceFilteredCards.length === 1 ? "skill" : "skills"}
+ {activeCategory ? <span className="capitalize"> · {activeCategory}</span> : null}
+ </p>
+ <div className="grid gap-3 [grid-template-columns:repeat(auto-fill,minmax(19rem,1fr))]">
+ {sourceFilteredCards.map((card) => (
+ <SkillCard key={card.key} card={card} onOpen={onOpenCard} />
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+type SkillCreateDraft = {
+ name: string;
+ slug: string;
+ tagline: string;
+ description: string;
+ color: string;
+ categories: string[];
+ markdown: string;
+ sharingScope: Exclude<CompanySkillSharingScope, "public_link">;
+ forkedFromSkillId: string | null;
+ forkedFromName: string | null;
+};
+
+function buildBlankSkillDraft(): SkillCreateDraft {
+ return {
+ name: "",
+ slug: "",
+ tagline: "",
+ description: "",
+ color: DISCOVERY_ACCENTS[0]!,
+ categories: [],
+ markdown: defaultSkillMarkdown("", ""),
+ sharingScope: "company",
+ forkedFromSkillId: null,
+ forkedFromName: null,
+ };
+}
+
+function buildForkSkillDraft(skill: CompanySkillDetail): SkillCreateDraft {
+ const name = `${skill.name} Fork`;
+ const slug = normalizeSkillDraftSlug(`${skill.slug}-fork`);
+ return {
+ name,
+ slug,
+ tagline: skill.tagline ?? "",
+ description: skill.description ?? "",
+ color: skill.color ?? skillAccentColor(skill.key, null),
+ categories: skill.categories,
+ markdown: skill.markdown.replace(/^name:\s*.*$/m, `name: ${name}`),
+ sharingScope: "company",
+ forkedFromSkillId: skill.id,
+ forkedFromName: skill.name,
+ };
+}
+
+function NewSkillWizard({
+ initialDraft,
+ onCreate,
+ isPending,
+ error,
+ onCancel,
+}: {
+ initialDraft: SkillCreateDraft;
+ onCreate: (payload: CompanySkillCreateRequest) => void;
+ isPending: boolean;
+ error: string | null;
+ onCancel: () => void;
+}) {
+ const [step, setStep] = useState(0);
+ const [draft, setDraft] = useState<SkillCreateDraft>(initialDraft);
+ const [slugDirty, setSlugDirty] = useState(initialDraft.slug.trim().length > 0);
+ const categoryDraft = draft.categories.join(", ");
+ const steps = ["Basics", "Design", "Content", "Review"];
+
+ useEffect(() => {
+ setStep(0);
+ setDraft(initialDraft);
+ setSlugDirty(initialDraft.slug.trim().length > 0);
+ }, [initialDraft]);
+
+ function patchDraft(patch: Partial<SkillCreateDraft>) {
+ setDraft((current) => ({ ...current, ...patch }));
+ }
+
+ const nameValid = draft.name.trim().length > 0;
+ const effectiveSlug = draft.slug.trim() || normalizeSkillDraftSlug(draft.name);
+ const effectiveMarkdown = draft.markdown.trim().length > 0
+ ? draft.markdown
+ : defaultSkillMarkdown(draft.name, draft.tagline);
+
+ function submit() {
+ onCreate({
+ name: draft.name.trim(),
+ slug: effectiveSlug || null,
+ description: draft.description.trim() || draft.tagline.trim() || null,
+ markdown: effectiveMarkdown,
+ color: draft.color,
+ tagline: draft.tagline.trim() || null,
+ categories: draft.categories,
+ sharingScope: draft.sharingScope,
+ forkedFromSkillId: draft.forkedFromSkillId,
+ });
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center gap-2 border-b border-border pb-3">
+ {steps.map((label, index) => (
+ <button
+ key={label}
+ type="button"
+ onClick={() => setStep(index)}
+ className={cn(
+ "rounded-md px-2 py-1 text-xs",
+ step === index ? "bg-accent text-foreground" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+
+ {draft.forkedFromName ? (
+ <div className="flex items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2 text-xs text-muted-foreground">
+ <GitFork className="h-3.5 w-3.5" />
+ Forking {draft.forkedFromName}
+ </div>
+ ) : null}
+
+ {step === 0 ? (
+ <div className="space-y-3">
+ <Input
+ value={draft.name}
+ onChange={(event) => {
+ const nextName = event.target.value;
+ patchDraft({
+ name: nextName,
+ slug: slugDirty ? draft.slug : normalizeSkillDraftSlug(nextName),
+ markdown: draft.markdown === defaultSkillMarkdown(draft.name, draft.tagline)
+ ? defaultSkillMarkdown(nextName, draft.tagline)
+ : draft.markdown,
+ });
+ }}
+ placeholder="Skill name"
+ className="h-9"
+ />
+ <Input
+ value={draft.slug}
+ onChange={(event) => {
+ const nextSlug = normalizeSkillDraftSlug(event.target.value);
+ setSlugDirty(nextSlug.length > 0);
+ patchDraft({ slug: nextSlug });
+ }}
+ placeholder="skill-shortname"
+ className="h-9 font-mono"
+ />
+ <Textarea
+ value={draft.tagline}
+ onChange={(event) => {
+ const nextTagline = event.target.value;
+ patchDraft({
+ tagline: nextTagline,
+ description: draft.description ? draft.description : nextTagline,
+ markdown: draft.markdown === defaultSkillMarkdown(draft.name, draft.tagline)
+ ? defaultSkillMarkdown(draft.name, nextTagline)
+ : draft.markdown,
+ });
+ }}
+ placeholder="One-line promise for the skill"
+ className="min-h-20"
+ />
+ </div>
+ ) : step === 1 ? (
+ <div className="space-y-4">
+ <div className="flex items-center gap-3">
+ <SkillCardIcon
+ size={48}
+ card={{
+ key: effectiveSlug || draft.name || "new-skill",
+ skillId: null,
+ catalogRef: null,
+ name: draft.name || "New Skill",
+ slug: effectiveSlug || "skill",
+ author: "you",
+ version: null,
+ description: draft.tagline,
+ categories: draft.categories,
+ iconUrl: null,
+ color: draft.color,
+ starCount: 0,
+ agentCount: 0,
+ forkCount: 0,
+ installed: false,
+ required: false,
+ forkedFrom: Boolean(draft.forkedFromSkillId),
+ updatedAt: Date.now(),
+ }}
+ />
+ <div className="min-w-0">
+ <div className="truncate text-sm font-medium">{draft.name || "New Skill"}</div>
+ <div className="truncate text-xs text-muted-foreground">{draft.tagline || "No tagline yet."}</div>
+ </div>
+ </div>
+ <div>
+ <label className="mb-2 block text-xs font-medium uppercase tracking-wide text-muted-foreground">Color</label>
+ <div className="flex flex-wrap gap-2">
+ {DISCOVERY_ACCENTS.map((color) => (
+ <button
+ key={color}
+ type="button"
+ onClick={() => patchDraft({ color })}
+ className={cn(
+ "h-7 w-7 rounded-md border",
+ draft.color === color ? "border-foreground" : "border-border",
+ )}
+ style={{ backgroundColor: color }}
+ aria-label={`Use ${color}`}
+ />
+ ))}
+ <Input
+ value={draft.color}
+ onChange={(event) => patchDraft({ color: event.target.value })}
+ className="h-7 w-28 font-mono text-xs"
+ />
+ </div>
+ </div>
+ <div>
+ <label className="mb-2 block text-xs font-medium uppercase tracking-wide text-muted-foreground">Categories</label>
+ <Input
+ value={categoryDraft}
+ onChange={(event) => patchDraft({ categories: splitCategoryDraft(event.target.value) })}
+ placeholder="engineering, review, memory"
+ className="h-9"
+ />
+ </div>
+ </div>
+ ) : step === 2 ? (
+ <div className="space-y-2">
+ <Textarea
+ value={draft.markdown}
+ onChange={(event) => patchDraft({ markdown: event.target.value })}
+ className="h-[clamp(14rem,45vh,28rem)] resize-y font-mono text-xs"
+ />
+ </div>
+ ) : (
+ <div className="space-y-4 text-sm">
+ <div className="grid grid-cols-[7rem_minmax(0,1fr)] gap-y-2">
+ <span className="text-muted-foreground">Name</span>
+ <span>{draft.name || "Untitled"}</span>
+ <span className="text-muted-foreground">Slug</span>
+ <span className="font-mono">{effectiveSlug || "skill"}</span>
+ <span className="text-muted-foreground">Scope</span>
+ <span>{draft.sharingScope === "private" ? "Private" : "Company"}</span>
+ <span className="text-muted-foreground">Categories</span>
+ <span>{draft.categories.length ? draft.categories.join(", ") : "none"}</span>
+ </div>
+ <div className="space-y-2">
+ <label className="block text-xs font-medium uppercase tracking-wide text-muted-foreground">Sharing</label>
+ <div className="grid gap-2 sm:grid-cols-3">
+ {(["company", "private"] as const).map((scope) => (
+ <button
+ key={scope}
+ type="button"
+ onClick={() => patchDraft({ sharingScope: scope })}
+ className={cn(
+ "rounded-md border px-3 py-2 text-left text-sm",
+ draft.sharingScope === scope ? "border-foreground bg-accent/50" : "border-border",
+ )}
+ >
+ <span className="block font-medium">{scope === "company" ? "Company" : "Private"}</span>
+ <span className="mt-1 block text-xs text-muted-foreground">
+ {scope === "company" ? "Visible inside this company." : "Only visible in your library."}
+ </span>
+ </button>
+ ))}
+ <button
+ type="button"
+ disabled
+ className="rounded-md border border-dashed border-border px-3 py-2 text-left text-sm text-muted-foreground"
+ >
+ <span className="block font-medium">Public link</span>
+ <span className="mt-1 block text-xs">Coming later.</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {error ? (
+ <div className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
+ {error}
+ </div>
+ ) : null}
+
+ <div className="flex items-center justify-between gap-2 border-t border-border pt-3">
+ <Button variant="ghost" size="sm" onClick={onCancel} disabled={isPending}>
+ Cancel
+ </Button>
+ <div className="flex items-center gap-2">
+ <Button variant="ghost" size="sm" onClick={() => setStep((value) => Math.max(0, value - 1))} disabled={isPending || step === 0}>
+ Back
+ </Button>
+ {step < steps.length - 1 ? (
+ <Button size="sm" onClick={() => setStep((value) => Math.min(steps.length - 1, value + 1))} disabled={!nameValid}>
+ Next
+ </Button>
+ ) : (
+ <Button size="sm" onClick={submit} disabled={isPending || !nameValid}>
+ {isPending ? "Creating..." : draft.forkedFromSkillId ? "Create fork" : "Create skill"}
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function CatalogList({
+ skills,
+ kindFilter,
+ categoryFilter,
+ catalogFilter,
+ installedByKey,
+ selectedCatalogRef,
+ selectedPath,
+ expandedSkillId,
+ expandedDirs,
+ onSelect,
+ onSelectPath,
+ onToggleSkill,
+ onToggleDir,
+}: {
+ skills: CatalogSkill[];
+ kindFilter: "all" | "bundled" | "optional";
+ categoryFilter: string;
+ catalogFilter: string;
+ installedByKey: Map<string, CompanySkillListItem>;
+ selectedCatalogRef: string | null;
+ selectedPath: string;
+ expandedSkillId: string | null;
+ expandedDirs: Record<string, Set<string>>;
+ onSelect: (catalogRef: string) => void;
+ onSelectPath: (catalogRef: string, path: string) => void;
+ onToggleSkill: (catalogRef: string) => void;
+ onToggleDir: (catalogRef: string, path: string) => void;
+}) {
+ const lowered = catalogFilter.trim().toLowerCase();
+ const filtered = skills.filter((skill) => {
+ if (kindFilter !== "all" && skill.kind !== kindFilter) return false;
+ if (categoryFilter && skill.category !== categoryFilter) return false;
+ if (!lowered) return true;
+ const haystack = `${skill.name} ${skill.slug} ${skill.key} ${skill.description} ${skill.category} ${skill.tags.join(" ")} ${skill.recommendedForRoles.join(" ")}`.toLowerCase();
+ return haystack.includes(lowered);
+ });
+
+ if (filtered.length === 0) {
+ return (
+ <div className="px-4 py-6 text-sm text-muted-foreground">
+ No catalog skills match this filter.
+ </div>
+ );
+ }
+
+ const available = filtered.filter((skill) => !installedByKey.has(skill.key));
+ const installed = filtered.filter((skill) => installedByKey.has(skill.key));
+ const bundled = available.filter((skill) => skill.kind === "bundled");
+ const optional = available.filter((skill) => skill.kind === "optional");
+
+ function renderRow(skill: CatalogSkill) {
+ const isSelected = selectedCatalogRef === skill.id || selectedCatalogRef === skill.key;
+ const expanded = expandedSkillId === skill.id;
+ const tree = buildTree(skill.files.map((file) => ({
+ path: file.path,
+ kind: file.kind,
+ })));
+ return (
+ <div key={skill.id} className="border-b border-border">
+ <div
+ className={cn(
+ "group grid grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-x-1 px-3 py-1.5 hover:bg-accent/30",
+ isSelected && "text-foreground",
+ )}
+ >
+ <Link
+ to={catalogSkillRoute(skill.id)}
+ className="flex min-w-0 items-center self-stretch pr-2 text-left no-underline"
+ onClick={() => onSelect(skill.id)}
+ >
+ <span className="flex min-w-0 items-center gap-2 self-center">
+ <span className="flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground opacity-75 transition-opacity group-hover:opacity-100">
+ <Boxes className={cn("h-3.5 w-3.5", skill.kind === "optional" && "opacity-70")} aria-hidden="true" />
+ </span>
+ <span className="min-w-0 overflow-hidden text-[13px] font-medium leading-5 [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:3]">
+ {skill.name}
+ </span>
+ </span>
+ </Link>
+ <button
+ type="button"
+ className="flex h-9 w-9 shrink-0 items-center justify-center self-center rounded-sm text-muted-foreground opacity-80 transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground group-hover:opacity-100"
+ onClick={() => onToggleSkill(skill.id)}
+ aria-label={expanded ? `Collapse ${skill.name}` : `Expand ${skill.name}`}
+ >
+ {expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
+ </button>
+ </div>
+ <div
+ aria-hidden={!expanded}
+ className={cn(
+ "grid overflow-hidden transition-[grid-template-rows,opacity] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)]",
+ expanded ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0",
+ )}
+ >
+ <div className="min-h-0 overflow-hidden">
+ <SkillTree
+ nodes={tree}
+ skillId={skill.id}
+ selectedPath={isSelected ? selectedPath : "SKILL.md"}
+ expandedDirs={expandedDirs[skill.id] ?? new Set<string>()}
+ onToggleDir={(path) => onToggleDir(skill.id, path)}
+ onSelectPath={(path) => onSelectPath(skill.id, path)}
+ fileHref={(skillId) => catalogSkillRoute(skillId)}
+ depth={1}
+ />
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div>
+ {bundled.length > 0 && kindFilter !== "optional" ? (
+ <div>
+ <div className="border-b border-border bg-background px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ Bundled · {bundled.length}
+ </div>
+ {bundled.map(renderRow)}
+ </div>
+ ) : null}
+ {optional.length > 0 && kindFilter !== "bundled" ? (
+ <div>
+ <div className="border-b border-border bg-background px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ Optional · {optional.length}
+ </div>
+ {optional.map(renderRow)}
+ </div>
+ ) : null}
+ {installed.length > 0 ? (
+ <div>
+ <div className="border-b border-border bg-background px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ Installed · {installed.length}
+ </div>
+ {installed.map(renderRow)}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+function CatalogDetailPane({
+ skill,
+ packageName,
+ packageVersion,
+ installedSkill,
+ installedSkillId,
+ fileQuery,
+ selectedPath,
+ onInstall,
+ onUpdate,
+ onOpenInstalled,
+ loadingPrimaryAction,
+}: {
+ skill: CatalogSkill | null;
+ packageName: string | null;
+ packageVersion: string | null;
+ installedSkill: CompanySkillListItem | null;
+ installedSkillId: string | null;
+ fileQuery: { data: CatalogSkillFileDetail | undefined; isLoading: boolean; error: unknown };
+ selectedPath: string;
+ onInstall: () => void;
+ onUpdate: () => void;
onOpenInstalled: (skillId: string) => void;
loadingPrimaryAction: boolean;
}) {
@@ -765,7 +1709,7 @@ function CatalogDetailPane({
cta = (
<Button onClick={onInstall} disabled={loadingPrimaryAction}>
{skill.trustLevel === "scripts_executables" ? <AlertTriangle className="mr-1.5 h-3.5 w-3.5" /> : <Download className="mr-1.5 h-3.5 w-3.5" />}
- {loadingPrimaryAction ? "Preparing..." : (skill.kind === "bundled" ? "Install bundled skill" : "Install optional skill")}
+ {loadingPrimaryAction ? "Preparing..." : "Install skill in this organization"}
</Button>
);
} else if (hashOutOfSync) {
@@ -1046,45 +1990,69 @@ function InstallPreviewDialog({
);
}
+type AttachAgentOption = {
+ id: string;
+ name: string;
+ adapterType: string;
+ supportsSkills: boolean;
+ required: boolean;
+ icon: string | null;
+ paused: boolean;
+};
+
function AttachAgentsPopover({
- open,
- onOpenChange,
agents,
attachedAgentIds,
+ versions,
+ selectedVersionId,
pending,
onSubmit,
+ fullWidth = false,
}: {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- agents: Array<{ id: string; name: string; adapterType: string; supportsSkills: boolean; required: boolean }>;
+ agents: AttachAgentOption[];
attachedAgentIds: string[];
+ versions: CompanySkillVersion[];
+ selectedVersionId: string | null;
pending: boolean;
- onSubmit: (nextIds: string[]) => void;
+ onSubmit: (nextIds: string[], versionId: string | null) => void;
+ fullWidth?: boolean;
}) {
+ // Each popover instance owns its open state. The detail page renders two of
+ // these (agents tab + sidebar); sharing a single controlled flag made both
+ // open at once and swallowed clicks, so "Add to agent" appeared dead (PAP-10907 H).
+ const [open, setOpen] = useState(false);
const [filter, setFilter] = useState("");
const [draft, setDraft] = useState<Set<string>>(new Set(attachedAgentIds));
+ const [draftVersionId, setDraftVersionId] = useState<string | null>(selectedVersionId);
useEffect(() => {
if (open) {
setDraft(new Set(attachedAgentIds));
+ setDraftVersionId(selectedVersionId);
setFilter("");
}
- }, [open, attachedAgentIds]);
-
- const filtered = agents.filter((agent) => agent.name.toLowerCase().includes(filter.toLowerCase()));
+ }, [open, attachedAgentIds, selectedVersionId]);
+
+ // Checked agents float to the top of the list (PAP-10907); within each group
+ // we keep a stable alphabetical order.
+ const filtered = agents
+ .filter((agent) => agent.name.toLowerCase().includes(filter.toLowerCase()))
+ .sort((a, b) => {
+ const aChecked = draft.has(a.id);
+ const bChecked = draft.has(b.id);
+ if (aChecked !== bChecked) return aChecked ? -1 : 1;
+ return a.name.localeCompare(b.name);
+ });
const eligible = agents.filter((agent) => agent.supportsSkills);
+ const sortedVersions = [...versions].sort((a, b) => b.revisionNumber - a.revisionNumber);
return (
- <Popover open={open} onOpenChange={onOpenChange}>
+ <Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
- <button
- type="button"
- className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
- aria-label="Attach to agents"
- >
- <Pencil className="h-3 w-3" />
- Edit
- </button>
+ <Button size="sm" className={cn(fullWidth && "w-full")}>
+ <Plus className="mr-1.5 h-3.5 w-3.5" />
+ Add to agent
+ </Button>
</PopoverTrigger>
<PopoverContent className="w-80 p-0" align="end">
<div className="border-b border-border px-3 py-2">
@@ -1094,6 +2062,23 @@ function AttachAgentsPopover({
placeholder="Filter agents"
className="h-8"
/>
+ {sortedVersions.length > 0 ? (
+ <div className="mt-2 flex items-center gap-2 text-xs">
+ <span className="shrink-0 text-muted-foreground">Version</span>
+ <select
+ value={draftVersionId ?? "__latest__"}
+ onChange={(event) => setDraftVersionId(event.target.value === "__latest__" ? null : event.target.value)}
+ className="h-8 min-w-0 flex-1 rounded-md border border-border bg-background px-2 text-xs text-foreground"
+ >
+ <option value="__latest__">Latest</option>
+ {sortedVersions.map((version) => (
+ <option key={version.id} value={version.id}>
+ v{version.revisionNumber}{version.label ? ` · ${version.label}` : ""}
+ </option>
+ ))}
+ </select>
+ </div>
+ ) : null}
</div>
{eligible.length === 0 ? (
<div className="px-3 py-4 text-sm text-muted-foreground">
@@ -1124,8 +2109,17 @@ function AttachAgentsPopover({
});
}}
/>
+ <AgentIcon icon={agent.icon} className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<span className="flex min-w-0 flex-col">
- <span className="truncate">{agent.name}</span>
+ <span className="flex items-center gap-1.5">
+ <span className="truncate">{agent.name}</span>
+ {agent.paused ? (
+ <span className="inline-flex shrink-0 items-center gap-1 rounded-full border border-amber-500/30 bg-amber-500/10 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-wide text-amber-500">
+ <Pause className="h-2.5 w-2.5" aria-hidden="true" />
+ Paused
+ </span>
+ ) : null}
+ </span>
<span className="text-[10px] uppercase tracking-wide text-muted-foreground">
{agent.adapterType}
{agent.required ? " · required" : ""}
@@ -1141,10 +2135,17 @@ function AttachAgentsPopover({
</div>
)}
<div className="flex items-center justify-end gap-2 border-t border-border px-3 py-2">
- <Button variant="ghost" size="sm" onClick={() => onOpenChange(false)} disabled={pending}>
+ <Button variant="ghost" size="sm" onClick={() => setOpen(false)} disabled={pending}>
Cancel
</Button>
- <Button size="sm" onClick={() => onSubmit(Array.from(draft))} disabled={pending}>
+ <Button
+ size="sm"
+ onClick={() => {
+ onSubmit(Array.from(draft), draftVersionId);
+ setOpen(false);
+ }}
+ disabled={pending}
+ >
{pending ? "Saving…" : "Save"}
</Button>
</div>
@@ -1169,7 +2170,7 @@ function SkillTree({
expandedDirs: Set<string>;
onToggleDir: (path: string) => void;
onSelectPath: (path: string) => void;
- fileHref?: (skillId: string, path: string) => string;
+ fileHref?: (skillId: string, path?: string | null) => string;
depth?: number;
}) {
return (
@@ -1230,7 +2231,7 @@ function SkillTree({
node.path === selectedPath && "text-foreground",
)}
style={{ paddingInlineStart: `${SKILL_TREE_BASE_INDENT + depth * SKILL_TREE_STEP_INDENT}px` }}
- to={node.path ? fileHref(skillId, node.path) : skillRoute(skillId)}
+ to={fileHref(skillId, node.path)}
onClick={() => node.path && onSelectPath(node.path)}
>
<span className="flex h-4 w-4 shrink-0 items-center justify-center">
@@ -1244,126 +2245,1059 @@ function SkillTree({
);
}
-function SkillList({
- skills,
- selectedSkillId,
- skillFilter,
- sourceFilter,
- expandedSkillId,
+function SkillList({
+ skills,
+ selectedSkillId,
+ skillFilter,
+ sourceFilter,
+ expandedSkillId,
+ expandedDirs,
+ selectedPaths,
+ onToggleSkill,
+ onToggleDir,
+ onSelectSkill,
+ onSelectPath,
+ onClearFilters,
+}: {
+ skills: CompanySkillListItem[];
+ selectedSkillId: string | null;
+ skillFilter: string;
+ sourceFilter: SourceFilter;
+ expandedSkillId: string | null;
+ expandedDirs: Record<string, Set<string>>;
+ selectedPaths: Record<string, string>;
+ onToggleSkill: (skillId: string) => void;
+ onToggleDir: (skillId: string, path: string) => void;
+ onSelectSkill: (skillId: string) => void;
+ onSelectPath: (skillId: string, path: string) => void;
+ onClearFilters: () => void;
+}) {
+ const filteredSkills = skills.filter((skill) => {
+ const haystack = `${skill.name} ${skill.key} ${skill.slug} ${skill.sourceLabel ?? ""}`.toLowerCase();
+ if (!haystack.includes(skillFilter.toLowerCase())) return false;
+ if (sourceFilter === "all") return true;
+ const skillSource = classifySource(skill);
+ return skillSource === sourceFilter;
+ });
+
+ if (filteredSkills.length === 0) {
+ if (sourceFilter !== "all" && skills.length > 0) {
+ return (
+ <div className="px-4 py-6 text-sm text-muted-foreground">
+ No {SOURCE_FILTER_LABELS[sourceFilter].toLowerCase()} skills installed.{" "}
+ <button type="button" className="text-foreground underline" onClick={onClearFilters}>
+ Clear filter
+ </button>
+ </div>
+ );
+ }
+ return (
+ <div className="px-4 py-6 text-sm text-muted-foreground">
+ No skills match this filter.
+ </div>
+ );
+ }
+
+ return (
+ <div>
+ {filteredSkills.map((skill) => {
+ const expanded = expandedSkillId === skill.id;
+ const tree = buildTree(skill.fileInventory);
+ const source = sourceMeta(skill.sourceBadge, skill.sourceLabel);
+ const SourceIcon = source.icon;
+
+ return (
+ <div key={skill.id} className="border-b border-border">
+ <div
+ className={cn(
+ "group grid grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-x-1 px-3 py-1.5 hover:bg-accent/30",
+ skill.id === selectedSkillId && "text-foreground",
+ )}
+ >
+ <Link
+ to={skillRoute(skill, skills)}
+ className="flex min-w-0 items-center self-stretch pr-2 text-left no-underline"
+ onClick={() => onSelectSkill(skill.id)}
+ >
+ <span className="flex min-w-0 items-center gap-2 self-center">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground opacity-75 transition-opacity group-hover:opacity-100">
+ <SourceIcon className="h-3.5 w-3.5" />
+ <span className="sr-only">{source.managedLabel}</span>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top">{source.managedLabel}</TooltipContent>
+ </Tooltip>
+ <span className="min-w-0 overflow-hidden text-[13px] font-medium leading-5 [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:3]">
+ {skill.name}
+ </span>
+ </span>
+ </Link>
+ <button
+ type="button"
+ className="flex h-9 w-9 shrink-0 items-center justify-center self-center rounded-sm text-muted-foreground opacity-80 transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground group-hover:opacity-100"
+ onClick={() => onToggleSkill(skill.id)}
+ aria-label={expanded ? `Collapse ${skill.name}` : `Expand ${skill.name}`}
+ >
+ {expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
+ </button>
+ </div>
+ <div
+ aria-hidden={!expanded}
+ className={cn(
+ "grid overflow-hidden transition-[grid-template-rows,opacity] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)]",
+ expanded ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0",
+ )}
+ >
+ <div className="min-h-0 overflow-hidden">
+ <SkillTree
+ nodes={tree}
+ skillId={skill.id}
+ selectedPath={selectedPaths[skill.id] ?? "SKILL.md"}
+ expandedDirs={expandedDirs[skill.id] ?? new Set<string>()}
+ onToggleDir={(path) => onToggleDir(skill.id, path)}
+ onSelectPath={(path) => onSelectPath(skill.id, path)}
+ fileHref={(_, path) => skillRoute(skill, skills, path)}
+ depth={1}
+ />
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+type SkillDetailTab = "overview" | "files" | "versions" | "agents";
+
+const SKILL_DETAIL_TABS: Array<{ value: SkillDetailTab; label: string; icon: typeof FileText }> = [
+ { value: "overview", label: "Overview", icon: FileText },
+ { value: "files", label: "Files", icon: FolderOpen },
+ { value: "versions", label: "Versions", icon: History },
+ { value: "agents", label: "Agents", icon: Users },
+];
+
+function currentVersionSelection(detail: CompanySkillDetail | null | undefined) {
+ const selected = detail?.usedByAgents.find((agent) => agent.versionId)?.versionId;
+ return selected ?? null;
+}
+
+function versionLabel(version: CompanySkillVersion | null | undefined) {
+ if (!version) return "Latest";
+ return `v${version.revisionNumber}${version.label ? ` · ${version.label}` : ""}`;
+}
+
+export function getSkillVersionDiffSelection(versions: CompanySkillVersion[], targetVersionId?: string | null) {
+ const sorted = [...versions].sort((a, b) => b.revisionNumber - a.revisionNumber);
+ const right = targetVersionId
+ ? sorted.find((version) => version.id === targetVersionId) ?? null
+ : sorted[0] ?? null;
+ if (!right) return { leftVersionId: null, rightVersionId: null };
+
+ const left = sorted.find((version) => version.revisionNumber < right.revisionNumber) ?? null;
+ return {
+ leftVersionId: left?.id ?? null,
+ rightVersionId: right.id,
+ };
+}
+
+function SkillVersionDiffDialog({
+ open,
+ onOpenChange,
+ versions,
+ leftVersionId,
+ rightVersionId,
+ onLeftVersionChange,
+ onRightVersionChange,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ versions: CompanySkillVersion[];
+ leftVersionId: string | null;
+ rightVersionId: string | null;
+ onLeftVersionChange: (id: string | null) => void;
+ onRightVersionChange: (id: string | null) => void;
+}) {
+ const sorted = [...versions].sort((a, b) => b.revisionNumber - a.revisionNumber);
+ const left = sorted.find((version) => version.id === leftVersionId) ?? null;
+ const right = sorted.find((version) => version.id === rightVersionId) ?? null;
+ const allPaths = useMemo(() => {
+ const paths = new Set<string>();
+ for (const file of left?.fileInventory ?? []) paths.add(file.path);
+ for (const file of right?.fileInventory ?? []) paths.add(file.path);
+ return Array.from(paths).sort((a, b) => {
+ if (a === "SKILL.md") return -1;
+ if (b === "SKILL.md") return 1;
+ return a.localeCompare(b);
+ });
+ }, [left, right]);
+ const [selectedPath, setSelectedPath] = useState("SKILL.md");
+ const effectivePath = allPaths.includes(selectedPath) ? selectedPath : allPaths[0] ?? "SKILL.md";
+ const leftFile = left?.fileInventory.find((file) => file.path === effectivePath);
+ const rightFile = right?.fileInventory.find((file) => file.path === effectivePath);
+ const diffRows = useMemo(
+ () => buildLineDiff(leftFile?.content ?? "", rightFile?.content ?? ""),
+ [leftFile?.content, rightFile?.content],
+ );
+ const lineClassesByKind: Record<DiffRow["kind"], string> = {
+ context: "bg-transparent",
+ removed: "bg-red-500/10 text-red-100",
+ added: "bg-green-500/10 text-green-100",
+ };
+ const markerByKind: Record<DiffRow["kind"], string> = {
+ context: " ",
+ removed: "-",
+ added: "+",
+ };
+
+ useEffect(() => {
+ if (open && allPaths.length > 0 && !allPaths.includes(selectedPath)) {
+ setSelectedPath(allPaths[0]!);
+ }
+ }, [allPaths, open, selectedPath]);
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="flex max-h-[85vh] w-full !max-w-[90%] flex-col overflow-hidden">
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ <DialogHeader className="shrink-0">
+ <DialogTitle>Diff · skill files</DialogTitle>
+ </DialogHeader>
+ <div className="flex flex-wrap items-center gap-3 text-xs">
+ <label className="flex items-center gap-2">
+ <span className="rounded-full border border-red-500/30 bg-red-500/10 px-2 py-0.5 font-medium uppercase tracking-wider text-red-400">Old</span>
+ <select
+ value={leftVersionId ?? ""}
+ onChange={(event) => onLeftVersionChange(event.target.value || null)}
+ className="h-8 w-44 rounded-md border border-border bg-background px-2 text-xs"
+ >
+ <option value="">Initial</option>
+ {sorted.map((version) => (
+ <option key={version.id} value={version.id}>{versionLabel(version)}</option>
+ ))}
+ </select>
+ </label>
+ <label className="flex items-center gap-2">
+ <span className="rounded-full border border-green-500/30 bg-green-500/10 px-2 py-0.5 font-medium uppercase tracking-wider text-green-400">New</span>
+ <select
+ value={right?.id ?? ""}
+ onChange={(event) => onRightVersionChange(event.target.value || null)}
+ className="h-8 w-44 rounded-md border border-border bg-background px-2 text-xs"
+ >
+ {sorted.map((version) => (
+ <option key={version.id} value={version.id}>{versionLabel(version)}</option>
+ ))}
+ </select>
+ </label>
+ </div>
+ </div>
+ <div className="flex min-h-0 flex-1 gap-3">
+ <aside className="hidden w-56 shrink-0 overflow-auto border-r border-border pr-3 md:block">
+ {allPaths.map((path) => (
+ <button
+ key={path}
+ type="button"
+ onClick={() => setSelectedPath(path)}
+ className={cn(
+ "flex w-full items-center gap-2 px-2 py-1.5 text-left font-mono text-xs text-muted-foreground hover:bg-accent/40 hover:text-foreground",
+ effectivePath === path && "bg-accent/50 text-foreground",
+ )}
+ >
+ <FileText className="h-3.5 w-3.5 shrink-0" />
+ <span className="truncate">{path}</span>
+ </button>
+ ))}
+ </aside>
+ <div className="min-w-0 flex-1 overflow-auto rounded-md border border-border text-xs">
+ {!right ? (
+ <div className="p-6 text-center text-sm text-muted-foreground">Select a version to compare.</div>
+ ) : left?.id === right.id ? (
+ <div className="p-6 text-center text-sm text-muted-foreground">Both sides are the same version.</div>
+ ) : (
+ <div className="font-mono text-[12px] leading-6">
+ <div className="grid grid-cols-[56px_56px_24px_minmax(0,1fr)] border-b border-border/60 bg-muted/30 px-3 py-2 text-[11px] uppercase tracking-wide text-muted-foreground">
+ <span>Old</span>
+ <span>New</span>
+ <span />
+ <span>{effectivePath}</span>
+ </div>
+ {diffRows.map((row, index) => (
+ <div
+ key={`${row.kind}-${index}-${row.oldLineNumber ?? "x"}-${row.newLineNumber ?? "x"}`}
+ className={cn("grid grid-cols-[56px_56px_24px_minmax(0,1fr)] gap-0 border-b border-border/30 px-3", lineClassesByKind[row.kind])}
+ >
+ <span className="select-none border-r border-border/30 pr-3 text-right text-muted-foreground">{row.oldLineNumber ?? ""}</span>
+ <span className="select-none border-r border-border/30 px-3 text-right text-muted-foreground">{row.newLineNumber ?? ""}</span>
+ <span className="select-none px-3 text-center text-muted-foreground">{markerByKind[row.kind]}</span>
+ <pre className="overflow-x-auto whitespace-pre-wrap break-words px-3 py-0 text-inherit">{row.text.length > 0 ? row.text : " "}</pre>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+export function SkillDetailPage({
+ detail,
+ catalogSource,
+ routeSkills,
+ loading,
+ activeTab,
+ onTabChange,
+ selectedPath,
+ file,
+ fileLoading,
+ viewMode,
+ editMode,
+ draft,
+ setViewMode,
+ setEditMode,
+ setDraft,
+ onSave,
+ savePending,
+ versions,
+ versionsLoading,
+ attachAgents,
+ onSubmitAttach,
+ attachPending,
expandedDirs,
- selectedPaths,
- onToggleSkill,
onToggleDir,
- onSelectSkill,
onSelectPath,
- onClearFilters,
+ updateStatus,
+ updateStatusLoading,
+ onCheckUpdates,
+ checkUpdatesPending,
+ onInstallUpdate,
+ installUpdatePending,
+ onToggleStar,
+ starPending,
+ onFork,
+ onUpdateSharingScope,
+ updateSharingPending,
+ onDelete,
+ deletePending,
}: {
- skills: CompanySkillListItem[];
- selectedSkillId: string | null;
- skillFilter: string;
- sourceFilter: SourceFilter;
- expandedSkillId: string | null;
- expandedDirs: Record<string, Set<string>>;
- selectedPaths: Record<string, string>;
- onToggleSkill: (skillId: string) => void;
- onToggleDir: (skillId: string, path: string) => void;
- onSelectSkill: (skillId: string) => void;
- onSelectPath: (skillId: string, path: string) => void;
- onClearFilters: () => void;
+ detail: CompanySkillDetail | null | undefined;
+ catalogSource?: CatalogSkillSource | null;
+ routeSkills?: CompanySkillRouteSubject[];
+ loading: boolean;
+ activeTab: SkillDetailTab;
+ onTabChange: (tab: SkillDetailTab) => void;
+ selectedPath: string;
+ file: CompanySkillFileDetail | null | undefined;
+ fileLoading: boolean;
+ viewMode: "preview" | "code";
+ editMode: boolean;
+ draft: string;
+ setViewMode: (mode: "preview" | "code") => void;
+ setEditMode: (value: boolean) => void;
+ setDraft: (value: string) => void;
+ onSave: () => void;
+ savePending: boolean;
+ versions: CompanySkillVersion[];
+ versionsLoading: boolean;
+ attachAgents: AttachAgentOption[];
+ onSubmitAttach: (ids: string[], versionId: string | null) => void;
+ attachPending: boolean;
+ expandedDirs: Set<string>;
+ onToggleDir: (path: string) => void;
+ onSelectPath: (path: string) => void;
+ updateStatus: CompanySkillUpdateStatus | null | undefined;
+ updateStatusLoading: boolean;
+ onCheckUpdates: () => void;
+ checkUpdatesPending: boolean;
+ onInstallUpdate: () => void;
+ installUpdatePending: boolean;
+ onToggleStar: () => void;
+ starPending: boolean;
+ onFork: () => void;
+ onUpdateSharingScope: (scope: Exclude<CompanySkillSharingScope, "public_link">) => void;
+ updateSharingPending: boolean;
+ onDelete: () => void;
+ deletePending: boolean;
}) {
- const filteredSkills = skills.filter((skill) => {
- const haystack = `${skill.name} ${skill.key} ${skill.slug} ${skill.sourceLabel ?? ""}`.toLowerCase();
- if (!haystack.includes(skillFilter.toLowerCase())) return false;
- if (sourceFilter === "all") return true;
- const skillSource = classifySource(skill);
- return skillSource === sourceFilter;
- });
+ const [diffOpen, setDiffOpen] = useState(false);
+ const [settingsOpen, setSettingsOpen] = useState(false);
+ // Top-level description is clamped to four lines; "View all" expands it. We
+ // only surface the toggle when the text actually overflows the clamp.
+ const descriptionRef = useRef<HTMLParagraphElement | null>(null);
+ const [descExpanded, setDescExpanded] = useState(false);
+ const [descClamped, setDescClamped] = useState(false);
+ useEffect(() => {
+ const el = descriptionRef.current;
+ if (!el || descExpanded) return;
+ setDescClamped(el.scrollHeight - el.clientHeight > 1);
+ }, [detail?.description, detail?.tagline, detail?.id, descExpanded]);
+ useEffect(() => {
+ setDescExpanded(false);
+ }, [detail?.id]);
+ const sortedVersions = [...versions].sort((a, b) => b.revisionNumber - a.revisionNumber);
+ const [leftVersionId, setLeftVersionId] = useState<string | null>(null);
+ const [rightVersionId, setRightVersionId] = useState<string | null>(null);
+
+ function openVersionDiff(targetVersionId?: string | null) {
+ const selection = getSkillVersionDiffSelection(sortedVersions, targetVersionId);
+ setLeftVersionId(selection.leftVersionId);
+ setRightVersionId(selection.rightVersionId);
+ setDiffOpen(Boolean(selection.rightVersionId));
+ }
- if (filteredSkills.length === 0) {
- if (sourceFilter !== "all" && skills.length > 0) {
- return (
- <div className="px-4 py-6 text-sm text-muted-foreground">
- No {SOURCE_FILTER_LABELS[sourceFilter].toLowerCase()} skills installed.{" "}
- <button type="button" className="text-foreground underline" onClick={onClearFilters}>
- Clear filter
- </button>
+ // Track unsaved edits so we can float a save bar and warn before the page is
+ // unloaded with a dirty draft (PAP-10907 J).
+ const savedFileContent = file?.content ?? "";
+ const isDirty = editMode && Boolean(file?.editable) && draft !== savedFileContent;
+ useEffect(() => {
+ if (!isDirty) return;
+ const handler = (event: BeforeUnloadEvent) => {
+ event.preventDefault();
+ event.returnValue = "";
+ };
+ window.addEventListener("beforeunload", handler);
+ return () => window.removeEventListener("beforeunload", handler);
+ }, [isDirty]);
+
+ if (!detail) {
+ return loading ? <PageSkeleton variant="detail" /> : <EmptyState icon={Boxes} message="Skill not found." />;
+ }
+
+ const skill = detail;
+ const source = sourceMeta(skill.sourceBadge, skill.sourceLabel);
+ const SourceIcon = source.icon;
+ const body = file?.markdown ? stripFrontmatter(file.content) : file?.content ?? "";
+ const currentPin = shortRef(skill.sourceRef);
+ const latestPin = shortRef(updateStatus?.latestRef);
+ const selectedVersion = versions.find((version) => version.id === currentVersionSelection(skill)) ?? null;
+ const subtitleText = skill.tagline || skill.description
+ ? cardDescriptionText(skill.tagline ?? skill.description)
+ : source.label;
+ // Look up the richer agent record (icon, paused) for agents using this skill.
+ const attachAgentMetaById = new Map(attachAgents.map((agent) => [agent.id, agent]));
+
+ // Sidebar provenance: prefer the rich upstream attribution from the catalog
+ // entry (GitHub owner/repo/path with a real link). Catalog-installed skills
+ // only persist a local staging path, so without this they'd show a long,
+ // unhelpful filesystem path (PAP-10907).
+ const githubSource = catalogSource && catalogSource.type === "github" ? catalogSource : null;
+ const githubLabel = githubSource
+ ? githubSource.hostname === "github.com"
+ ? "GitHub"
+ : githubSource.hostname
+ : null;
+ const githubRepoText = githubSource
+ ? `${githubSource.owner}/${githubSource.repo}${githubSource.path ? `/${githubSource.path}` : ""}`
+ : null;
+ const githubHref = githubSource
+ ? githubSource.url
+ ?? `https://${githubSource.hostname}/${githubSource.owner}/${githubSource.repo}/tree/${githubSource.ref}/${githubSource.path}`.replace(/\/$/, "")
+ : null;
+ // Fallback for non-catalog skills: the recorded locator/path, middle-truncated
+ // so long file paths stay readable in the narrow sidebar.
+ const sourceLocatorText = skill.sourcePath || skill.sourceLocator || null;
+ const sourceLocatorDisplay = sourceLocatorText ? middleTruncate(sourceLocatorText, 44) : null;
+ const sourceHref =
+ skill.homepageUrl
+ ?? (sourceLocatorText && /^(https?:\/\/|[\w.-]+\.[a-z]{2,}\/)/i.test(sourceLocatorText)
+ ? sourceLocatorText.startsWith("http")
+ ? sourceLocatorText
+ : `https://${sourceLocatorText}`
+ : null);
+
+ function renderFilesBody() {
+ return (
+ <div className="grid min-h-[560px] gap-0 lg:grid-cols-[13rem_minmax(0,1fr)]">
+ <aside className="border-b border-border pb-3 lg:border-b-0 lg:border-r lg:pb-0 lg:pr-3">
+ <div className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">Files</div>
+ <SkillTree
+ nodes={buildTree(skill.fileInventory)}
+ skillId={skill.id}
+ selectedPath={selectedPath}
+ expandedDirs={expandedDirs}
+ onToggleDir={onToggleDir}
+ onSelectPath={onSelectPath}
+ fileHref={(_, path) => skillRoute(skill, routeSkills ?? [skill], path)}
+ />
+ </aside>
+ <section className="min-w-0 lg:pl-5">
+ <div className="mb-3 flex flex-wrap items-center justify-between gap-3 border-b border-border pb-3">
+ <div className="min-w-0 truncate font-mono text-sm">{file?.path ?? selectedPath}</div>
+ <div className="flex items-center gap-2">
+ {file?.markdown && !editMode ? (
+ <div className="flex items-center border border-border">
+ <button
+ className={cn("px-3 py-1.5 text-sm", viewMode === "preview" ? "text-foreground" : "text-muted-foreground")}
+ onClick={() => setViewMode("preview")}
+ >
+ <span className="flex items-center gap-1.5"><Eye className="h-3.5 w-3.5" /> View</span>
+ </button>
+ <button
+ className={cn("border-l border-border px-3 py-1.5 text-sm", viewMode === "code" ? "text-foreground" : "text-muted-foreground")}
+ onClick={() => setViewMode("code")}
+ >
+ <span className="flex items-center gap-1.5"><Code2 className="h-3.5 w-3.5" /> Code</span>
+ </button>
+ </div>
+ ) : null}
+ {skill.editable && file?.editable ? (
+ editMode ? (
+ <>
+ <Button variant="ghost" size="sm" onClick={() => setEditMode(false)} disabled={savePending}>Cancel</Button>
+ <Button size="sm" onClick={onSave} disabled={savePending}>
+ <Save className="mr-1.5 h-3.5 w-3.5" />
+ {savePending ? "Saving..." : "Save"}
+ </Button>
+ </>
+ ) : (
+ <Button variant="ghost" size="sm" onClick={() => setEditMode(true)}>
+ <Pencil className="mr-1.5 h-3.5 w-3.5" /> Edit
+ </Button>
+ )
+ ) : null}
+ </div>
+ </div>
+ {fileLoading ? (
+ <PageSkeleton variant="detail" />
+ ) : !file ? (
+ <div className="text-sm text-muted-foreground">Select a file to inspect.</div>
+ ) : editMode && file.editable ? (
+ file.markdown ? (
+ <MarkdownEditor value={draft} onChange={setDraft} bordered={false} className="min-h-[520px]" />
+ ) : (
+ <Textarea
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ className="min-h-[520px] rounded-none border-0 bg-transparent px-0 py-0 font-mono text-sm shadow-none focus-visible:ring-0"
+ />
+ )
+ ) : file.markdown && viewMode === "preview" ? (
+ <MarkdownBody softBreaks={false} linkIssueReferences={false}>{body}</MarkdownBody>
+ ) : (
+ <pre className="overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground">
+ <code>{file.content}</code>
+ </pre>
+ )}
+ </section>
+ </div>
+ );
+ }
+
+ function renderOverviewBody() {
+ return (
+ <div className="space-y-6">
+ <section>
+ <h2 className="mb-2 text-sm font-medium">About</h2>
+ {fileLoading ? (
+ <PageSkeleton variant="detail" />
+ ) : file?.markdown ? (
+ <MarkdownBody softBreaks={false} linkIssueReferences={false}>{body || skill.description || "No overview yet."}</MarkdownBody>
+ ) : (
+ <p className="text-sm text-muted-foreground">{skill.description ?? "No overview yet."}</p>
+ )}
+ </section>
+ <section className="grid min-w-0 gap-3 text-sm sm:grid-cols-2">
+ <div className="min-w-0 border-b border-border py-2">
+ <div className="text-xs text-muted-foreground">Key</div>
+ <div className="mt-1 truncate font-mono">{skill.key}</div>
+ </div>
+ <div className="min-w-0 border-b border-border py-2">
+ <div className="text-xs text-muted-foreground">Source</div>
+ <div className="mt-1 truncate">{skill.sourcePath ?? source.label}</div>
+ </div>
+ <div className="min-w-0 border-b border-border py-2">
+ <div className="text-xs text-muted-foreground">Version</div>
+ <div className="mt-1">{versionLabel(skill.currentVersion ?? null)}</div>
+ </div>
+ <div className="min-w-0 border-b border-border py-2">
+ <div className="text-xs text-muted-foreground">Mode</div>
+ <div className="mt-1">{skill.editable ? "Editable" : skill.editableReason ?? "Read only"}</div>
+ </div>
+ </section>
+ </div>
+ );
+ }
+
+ function renderVersionsBody() {
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between gap-3">
+ <div className="text-sm text-muted-foreground">
+ {versionsLoading ? "Loading versions..." : `${versions.length} ${versions.length === 1 ? "version" : "versions"}`}
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => openVersionDiff()}
+ disabled={sortedVersions.length < 2}
+ >
+ <History className="mr-1.5 h-3.5 w-3.5" /> Compare
+ </Button>
</div>
- );
- }
+ <div className="border-y border-border">
+ {versionsLoading ? (
+ <PageSkeleton variant="list" />
+ ) : sortedVersions.length === 0 ? (
+ <div className="py-6 text-sm text-muted-foreground">No saved versions yet.</div>
+ ) : (
+ sortedVersions.map((version) => (
+ <div key={version.id} className="grid gap-2 border-b border-border px-0 py-3 text-sm last:border-b-0 sm:grid-cols-[minmax(0,1fr)_auto]">
+ <div className="min-w-0">
+ <div className="font-medium">{versionLabel(version)}</div>
+ <div className="mt-1 text-xs text-muted-foreground">
+ {relativeTime(version.createdAt)} · {version.fileInventory.length} files
+ </div>
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => openVersionDiff(version.id)}
+ >
+ View diff
+ </Button>
+ </div>
+ ))
+ )}
+ </div>
+ <SkillVersionDiffDialog
+ open={diffOpen}
+ onOpenChange={setDiffOpen}
+ versions={sortedVersions}
+ leftVersionId={leftVersionId}
+ rightVersionId={rightVersionId}
+ onLeftVersionChange={setLeftVersionId}
+ onRightVersionChange={setRightVersionId}
+ />
+ </div>
+ );
+ }
+
+ function renderAgentsBody() {
+ // Only the agents actually using this skill are listed (PAP-10907); the
+ // multi-selector behind "Add to agent" is where you attach more.
+ const attached = skill.usedByAgents;
return (
- <div className="px-4 py-6 text-sm text-muted-foreground">
- No skills match this filter.
+ <div className="space-y-3">
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-sm text-muted-foreground">
+ {attached.length} {attached.length === 1 ? "agent" : "agents"} attached
+ {selectedVersion ? ` · ${versionLabel(selectedVersion)}` : " · Latest"}
+ </p>
+ <AttachAgentsPopover
+ agents={attachAgents}
+ attachedAgentIds={attached.map((agent) => agent.id)}
+ versions={versions}
+ selectedVersionId={currentVersionSelection(skill)}
+ pending={attachPending}
+ onSubmit={onSubmitAttach}
+ />
+ </div>
+ {attached.length === 0 ? (
+ <div className="rounded-md border border-dashed border-border py-8 text-center text-sm text-muted-foreground">
+ No agents are using this skill yet. Use “Add to agent” to attach it.
+ </div>
+ ) : (
+ <div className="border-y border-border">
+ {attached.map((agent) => {
+ const meta = attachAgentMetaById.get(agent.id);
+ return (
+ <div key={agent.id} className="flex items-center gap-3 border-b border-border py-3 text-sm last:border-b-0">
+ <AgentIcon icon={meta?.icon ?? null} className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <span className="truncate font-medium">{agent.name}</span>
+ {meta?.paused ? (
+ <span className="inline-flex shrink-0 items-center gap-1 rounded-full border border-amber-500/30 bg-amber-500/10 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-wide text-amber-500">
+ <Pause className="h-2.5 w-2.5" aria-hidden="true" />
+ Paused
+ </span>
+ ) : null}
+ </div>
+ <div className="mt-0.5 text-xs text-muted-foreground">{agent.adapterType}</div>
+ </div>
+ <Link
+ to={`/agents/${agent.urlKey}/skills`}
+ className="shrink-0 text-xs text-muted-foreground no-underline hover:text-foreground"
+ >
+ View
+ </Link>
+ </div>
+ );
+ })}
+ </div>
+ )}
</div>
);
}
- return (
- <div>
- {filteredSkills.map((skill) => {
- const expanded = expandedSkillId === skill.id;
- const tree = buildTree(skill.fileInventory);
- const source = sourceMeta(skill.sourceBadge, skill.sourceLabel);
- const SourceIcon = source.icon;
+ const tabBody = activeTab === "files"
+ ? renderFilesBody()
+ : activeTab === "versions"
+ ? renderVersionsBody()
+ : activeTab === "agents"
+ ? renderAgentsBody()
+ : renderOverviewBody();
- return (
- <div key={skill.id} className="border-b border-border">
- <div
- className={cn(
- "group grid grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-x-1 px-3 py-1.5 hover:bg-accent/30",
- skill.id === selectedSkillId && "text-foreground",
- )}
- >
- <Link
- to={skillRoute(skill.id)}
- className="flex min-w-0 items-center self-stretch pr-2 text-left no-underline"
- onClick={() => onSelectSkill(skill.id)}
- >
- <span className="flex min-w-0 items-center gap-2 self-center">
+ return (
+ <div className="min-h-[calc(100vh-12rem)]">
+ <div className="border-b border-border px-4 py-5">
+ <div className="flex flex-wrap items-start justify-between gap-4">
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-start gap-3">
+ <SkillCardIcon
+ card={{
+ key: detail.key,
+ skillId: detail.id,
+ catalogRef: null,
+ name: detail.name,
+ slug: detail.slug,
+ author: detail.authorName ?? source.label,
+ version: null,
+ description: detail.description,
+ categories: detail.categories,
+ iconUrl: detail.iconUrl,
+ color: detail.color,
+ starCount: detail.starCount,
+ agentCount: detail.attachedAgentCount,
+ forkCount: detail.forkCount,
+ installed: true,
+ required: false,
+ forkedFrom: Boolean(detail.forkedFromSkillId),
+ updatedAt: new Date(detail.updatedAt).getTime() || 0,
+ }}
+ size={44}
+ />
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-center gap-2">
+ <h1 className="truncate text-2xl font-semibold">{detail.name}</h1>
+ {/* Source icon sits right after the title; the tooltip names
+ where the skill was installed from (PAP-10907). */}
<Tooltip>
<TooltipTrigger asChild>
- <span className="flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground opacity-75 transition-opacity group-hover:opacity-100">
- <SourceIcon className="h-3.5 w-3.5" />
- <span className="sr-only">{source.managedLabel}</span>
+ <span
+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground"
+ aria-label={`Installed from ${source.label}`}
+ >
+ <SourceIcon className="h-4 w-4" />
</span>
</TooltipTrigger>
- <TooltipContent side="top">{source.managedLabel}</TooltipContent>
+ <TooltipContent>Installed from {source.label}</TooltipContent>
</Tooltip>
- <span className="min-w-0 overflow-hidden text-[13px] font-medium leading-5 [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:3]">
- {skill.name}
+ </div>
+ {/* GitHub-style "by" attribution sits directly under the title. */}
+ {detail.authorName ? (
+ <p className="mt-0.5 text-sm text-muted-foreground">
+ by <span className="text-foreground">{detail.authorName}</span>
+ </p>
+ ) : null}
+ {subtitleText ? (
+ <div className="mt-1 max-w-2xl">
+ <p
+ ref={descriptionRef}
+ className={cn(
+ "text-sm text-muted-foreground",
+ !descExpanded && "line-clamp-4",
+ )}
+ >
+ {subtitleText}
+ </p>
+ {descClamped ? (
+ <button
+ type="button"
+ onClick={() => setDescExpanded((value) => !value)}
+ className="mt-0.5 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"
+ >
+ {descExpanded ? "Show less" : "View all"}
+ </button>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ </div>
+ <div className="mt-4 flex flex-wrap items-center gap-2">
+ {detail.categories.slice(0, 4).map((category) => (
+ <SkillCategoryChip key={category} label={category} />
+ ))}
+ </div>
+ </div>
+ {/* GitHub-style social proof, top-right: installs · stars · fork.
+ "Installs" counts agents that currently have this skill attached
+ (PAP-10907); stars and fork are interactive. */}
+ <div className="flex flex-wrap items-center justify-end gap-1">
+ <div className="flex items-center overflow-hidden rounded-md border border-border">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs text-muted-foreground">
+ <Download className="h-3.5 w-3.5" aria-hidden="true" />
+ <span className="font-medium text-foreground">{detail.attachedAgentCount}</span>
+ <span className="hidden sm:inline">{detail.attachedAgentCount === 1 ? "install" : "installs"}</span>
</span>
- </span>
- </Link>
+ </TooltipTrigger>
+ <TooltipContent>Agents in this company that currently have this skill installed.</TooltipContent>
+ </Tooltip>
<button
type="button"
- className="flex h-9 w-9 shrink-0 items-center justify-center self-center rounded-sm text-muted-foreground opacity-80 transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground group-hover:opacity-100"
- onClick={() => onToggleSkill(skill.id)}
- aria-label={expanded ? `Collapse ${skill.name}` : `Expand ${skill.name}`}
+ onClick={onToggleStar}
+ disabled={starPending}
+ className="inline-flex items-center gap-1.5 border-l border-border px-2.5 py-1.5 text-xs text-muted-foreground transition-colors hover:bg-accent/40 hover:text-foreground disabled:opacity-50"
+ title={detail.starredByCurrentActor ? "Unstar this skill" : "Star this skill"}
>
- {expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
+ <Star className={cn("h-3.5 w-3.5", detail.starredByCurrentActor && "fill-current text-yellow-400")} />
+ <span className="hidden sm:inline">{detail.starredByCurrentActor ? "Starred" : "Star"}</span>
+ <span className="font-medium text-foreground">{detail.starCount}</span>
+ </button>
+ <button
+ type="button"
+ onClick={onFork}
+ className="inline-flex items-center gap-1.5 border-l border-border px-2.5 py-1.5 text-xs text-muted-foreground transition-colors hover:bg-accent/40 hover:text-foreground"
+ title="Fork this skill"
+ >
+ <GitFork className="h-3.5 w-3.5" />
+ <span className="hidden sm:inline">Fork</span>
+ <span className="font-medium text-foreground">{detail.forkCount}</span>
</button>
</div>
- <div
- aria-hidden={!expanded}
- className={cn(
- "grid overflow-hidden transition-[grid-template-rows,opacity] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)]",
- expanded ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0",
+ </div>
+ </div>
+ </div>
+
+ <div className="grid gap-6 px-4 py-4 xl:grid-cols-[minmax(0,1fr)_18rem]">
+ <main className="min-w-0">
+ <Tabs value={activeTab} onValueChange={(value) => onTabChange(value as SkillDetailTab)}>
+ {/* Underlined tab strip: the bottom padding keeps the active-tab
+ underline inside the horizontal-scroll clip box (PAP-10907). */}
+ <TabsList variant="line" className="mb-5 w-full max-w-full justify-start overflow-x-auto border-b border-border p-0 pb-1.5 [scrollbar-width:none]">
+ {SKILL_DETAIL_TABS.map((tab) => {
+ const Icon = tab.icon;
+ return (
+ <TabsTrigger key={tab.value} value={tab.value} className="px-3">
+ <Icon className="mr-1.5 h-3.5 w-3.5" />
+ {tab.label}
+ </TabsTrigger>
+ );
+ })}
+ </TabsList>
+ </Tabs>
+ {tabBody}
+ </main>
+
+ <aside className="min-w-0 space-y-6 border-t border-border pt-4 xl:border-l xl:border-t-0 xl:pl-5 xl:pt-0">
+ <section>
+ <div className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">Agents</div>
+ <div className="space-y-3">
+ {/* Big primary action opens the agent multi-selector (PAP-10907). */}
+ <AttachAgentsPopover
+ agents={attachAgents}
+ attachedAgentIds={detail.usedByAgents.map((agent) => agent.id)}
+ versions={versions}
+ selectedVersionId={currentVersionSelection(detail)}
+ pending={attachPending}
+ onSubmit={onSubmitAttach}
+ fullWidth
+ />
+ {detail.usedByAgents.length === 0 ? (
+ <p className="text-xs text-muted-foreground">No agents attached yet.</p>
+ ) : (
+ <div className="space-y-0.5">
+ {/* Preview up to three attached agents, then summarise the rest. */}
+ {detail.usedByAgents.slice(0, 3).map((agent) => {
+ const meta = attachAgentMetaById.get(agent.id);
+ return (
+ <Link
+ key={agent.id}
+ to={`/agents/${agent.urlKey}/skills`}
+ className="flex items-center gap-2 rounded-md px-1.5 py-1 text-sm no-underline hover:bg-accent/40"
+ >
+ <AgentIcon icon={meta?.icon ?? null} className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate text-foreground">{agent.name}</span>
+ {meta?.paused ? (
+ <Pause className="h-3 w-3 shrink-0 text-amber-500" aria-label="Paused" />
+ ) : null}
+ </Link>
+ );
+ })}
+ {detail.usedByAgents.length > 3 ? (
+ <p className="px-1.5 pt-0.5 text-xs text-muted-foreground">
+ and {detail.usedByAgents.length - 3} more
+ </p>
+ ) : null}
+ </div>
)}
- >
- <div className="min-h-0 overflow-hidden">
- <SkillTree
- nodes={tree}
- skillId={skill.id}
- selectedPath={selectedPaths[skill.id] ?? "SKILL.md"}
- expandedDirs={expandedDirs[skill.id] ?? new Set<string>()}
- onToggleDir={(path) => onToggleDir(skill.id, path)}
- onSelectPath={(path) => onSelectPath(skill.id, path)}
- depth={1}
- />
+ </div>
+ </section>
+
+ {/* Provenance: where this skill came from, with org/path linked when
+ available. Bundled/catalog skills surface their source label too
+ (PAP-10907). */}
+ <section>
+ <div className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">Source</div>
+ {githubSource ? (
+ <div className="flex items-start gap-2 text-sm">
+ <Github className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <div className="min-w-0">
+ <div className="text-foreground">{githubLabel}</div>
+ <a
+ href={githubHref ?? undefined}
+ target="_blank"
+ rel="noreferrer"
+ title={githubRepoText ?? undefined}
+ className="mt-0.5 flex max-w-full items-center gap-1 text-xs text-muted-foreground no-underline transition-colors hover:text-foreground"
+ >
+ <span className="truncate">{githubRepoText}</span>
+ <ExternalLink className="h-3 w-3 shrink-0" aria-hidden="true" />
+ </a>
+ <div className="mt-0.5 truncate font-mono text-[11px] text-muted-foreground" title={githubSource.commit}>
+ {githubSource.ref}
+ {githubSource.commit ? ` · ${githubSource.commit.slice(0, 7)}` : ""}
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="flex items-start gap-2 text-sm">
+ <SourceIcon className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <div className="min-w-0">
+ <div className="text-foreground">{source.label}</div>
+ {sourceLocatorDisplay ? (
+ sourceHref ? (
+ <a
+ href={sourceHref}
+ target="_blank"
+ rel="noreferrer"
+ title={sourceLocatorText ?? undefined}
+ className="mt-0.5 flex max-w-full items-center gap-1 text-xs text-muted-foreground no-underline transition-colors hover:text-foreground"
+ >
+ <span className="truncate">{sourceLocatorDisplay}</span>
+ <ExternalLink className="h-3 w-3 shrink-0" aria-hidden="true" />
+ </a>
+ ) : (
+ <div className="mt-0.5 truncate text-xs text-muted-foreground" title={sourceLocatorText ?? undefined}>
+ {sourceLocatorDisplay}
+ </div>
+ )
+ ) : (
+ <div className="mt-0.5 text-xs text-muted-foreground">{source.managedLabel}</div>
+ )}
+ </div>
+ </div>
+ )}
+ </section>
+
+ {/* Revision / update controls sit under Agents, above the config gear
+ (PAP-10907 F). Only GitHub-sourced skills can pull updates. */}
+ {detail.sourceType === "github" ? (
+ <section>
+ <div className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">Updates</div>
+ <div className="space-y-2">
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Pin className="h-3.5 w-3.5 shrink-0" aria-label="Pinned source revision" />
+ </TooltipTrigger>
+ <TooltipContent>Pinned source revision</TooltipContent>
+ </Tooltip>
+ <span className="truncate font-mono text-foreground">{currentPin ?? "untracked"}</span>
+ </div>
+ <Button variant="outline" size="sm" className="w-full" onClick={onCheckUpdates} disabled={checkUpdatesPending || updateStatusLoading}>
+ <RefreshCw className={cn("mr-1.5 h-3.5 w-3.5", (checkUpdatesPending || updateStatusLoading) && "animate-spin")} />
+ Check for updates
+ </Button>
+ {updateStatus?.supported && updateStatus.hasUpdate ? (
+ <Button size="sm" className="w-full" onClick={onInstallUpdate} disabled={installUpdatePending}>
+ <ArrowUpCircle className={cn("mr-1.5 h-3.5 w-3.5", installUpdatePending && "animate-spin")} />
+ Install update{latestPin ? ` ${latestPin}` : ""}
+ </Button>
+ ) : updateStatus?.supported && !updateStatus.hasUpdate && !updateStatusLoading ? (
+ <p className="text-xs text-muted-foreground">Up to date.</p>
+ ) : null}
</div>
+ </section>
+ ) : null}
+
+ {/* Config lives behind a gear; sharing + danger zone open in a modal
+ (PAP-10907 A). */}
+ <section>
+ <button
+ type="button"
+ onClick={() => setSettingsOpen(true)}
+ className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm text-muted-foreground transition-colors hover:bg-accent/30 hover:text-foreground"
+ >
+ <Settings className="h-4 w-4 shrink-0" />
+ <span className="flex-1">Settings</span>
+ </button>
+ </section>
+ </aside>
+ </div>
+
+ {/* Floating save bar: stays visible while a file edit is dirty so the
+ unsaved state is obvious (PAP-10907 J). */}
+ {isDirty ? (
+ <div className="fixed bottom-6 left-1/2 z-40 flex -translate-x-1/2 items-center gap-3 rounded-full border border-border bg-background/95 px-4 py-2 shadow-lg backdrop-blur">
+ <span className="text-sm text-muted-foreground">Unsaved changes</span>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ setDraft(savedFileContent);
+ setEditMode(false);
+ }}
+ disabled={savePending}
+ >
+ Discard
+ </Button>
+ <Button size="sm" onClick={onSave} disabled={savePending}>
+ <Save className="mr-1.5 h-3.5 w-3.5" />
+ {savePending ? "Saving…" : "Save changes"}
+ </Button>
+ </div>
+ ) : null}
+
+ <Dialog open={settingsOpen} onOpenChange={setSettingsOpen}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Skill settings</DialogTitle>
+ <DialogDescription>Manage how {detail.name} is shared.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-5">
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Sharing</label>
+ <select
+ value={detail.sharingScope === "public_link" ? "company" : detail.sharingScope}
+ onChange={(event) => onUpdateSharingScope(event.target.value as Exclude<CompanySkillSharingScope, "public_link">)}
+ disabled={updateSharingPending}
+ className="h-9 w-full rounded-md border border-border bg-background px-2 text-sm text-foreground"
+ >
+ <option value="company">Company — visible inside this company</option>
+ <option value="private">Private — only visible in your library</option>
+ </select>
+ <p className="text-xs text-muted-foreground">Public link sharing is coming later.</p>
</div>
+ {detail.editable ? (
+ <div className="rounded-md border border-destructive/40 p-3">
+ <div className="text-xs font-semibold uppercase tracking-wide text-destructive">Danger zone</div>
+ <div className="mt-2 flex items-center justify-between gap-3">
+ <p className="min-w-0 text-xs text-muted-foreground">Remove this skill from the company library.</p>
+ <Button
+ variant="destructive"
+ size="sm"
+ className="shrink-0"
+ onClick={onDelete}
+ disabled={deletePending}
+ title={detail.usedByAgents.length > 0 ? "Detach this skill from all agents before removing it." : undefined}
+ >
+ <Trash2 className="mr-1.5 h-3.5 w-3.5" />
+ {deletePending ? "Removing…" : "Remove"}
+ </Button>
+ </div>
+ </div>
+ ) : null}
</div>
- );
- })}
+ </DialogContent>
+ </Dialog>
</div>
);
}
@@ -1390,8 +3324,7 @@ function SkillPane({
onSave,
savePending,
attachAgents,
- attachPopoverOpen,
- setAttachPopoverOpen,
+ versions,
onSubmitAttach,
attachPending,
}: {
@@ -1415,10 +3348,9 @@ function SkillPane({
deletePending: boolean;
onSave: () => void;
savePending: boolean;
- attachAgents: Array<{ id: string; name: string; adapterType: string; supportsSkills: boolean; required: boolean }>;
- attachPopoverOpen: boolean;
- setAttachPopoverOpen: (open: boolean) => void;
- onSubmitAttach: (ids: string[]) => void;
+ attachAgents: AttachAgentOption[];
+ versions: CompanySkillVersion[];
+ onSubmitAttach: (ids: string[], versionId: string | null) => void;
attachPending: boolean;
}) {
if (!detail) {
@@ -1580,10 +3512,10 @@ function SkillPane({
<div className="flex items-center gap-2">
<span className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground">Used by</span>
<AttachAgentsPopover
- open={attachPopoverOpen}
- onOpenChange={setAttachPopoverOpen}
agents={attachAgents}
attachedAgentIds={usedBy.map((agent) => agent.id)}
+ versions={versions}
+ selectedVersionId={usedBy.find((agent) => agent.versionId)?.versionId ?? null}
pending={attachPending}
onSubmit={onSubmitAttach}
/>
@@ -1693,7 +3625,6 @@ export function CompanySkills() {
const adapterCaps = useAdapterCapabilities();
const [skillFilter, setSkillFilter] = useState("");
const [source, setSource] = useState("");
- const [createOpen, setCreateOpen] = useState(false);
const [emptySourceHelpOpen, setEmptySourceHelpOpen] = useState(false);
const [expandedSkillId, setExpandedSkillId] = useState<string | null>(null);
const [expandedDirs, setExpandedDirs] = useState<Record<string, Set<string>>>({});
@@ -1721,9 +3652,14 @@ export function CompanySkills() {
defaultAction: "install" | "update" | "replace";
error: string | null;
}>({ open: false, catalogSkill: null, conflict: null, defaultSlug: null, defaultForce: false, defaultAction: "install", error: null });
- const [attachPopoverOpen, setAttachPopoverOpen] = useState(false);
+ const [discoverySearch, setDiscoverySearch] = useState("");
+ const [discoverySort, setDiscoverySort] = useState<DiscoverySort>("agents");
+ const [createDialogOpen, setCreateDialogOpen] = useState(false);
+ const [createDraft, setCreateDraft] = useState<SkillCreateDraft>(() => buildBlankSkillDraft());
+ const [createError, setCreateError] = useState<string | null>(null);
+ const [importDialogOpen, setImportDialogOpen] = useState(false);
const parsedRoute = useMemo(() => parseSkillRoute(routePath), [routePath]);
- const routeSkillId = parsedRoute.skillId;
+ const routeSkillToken = parsedRoute.skillToken;
const selectedPath = parsedRoute.filePath;
const viewParam = searchParams.get("view");
const activeView: "installed" | "catalog" = viewParam === "catalog" ? "catalog" : "installed";
@@ -1732,13 +3668,45 @@ export function CompanySkills() {
? (sourceFilterParam as SourceFilter)
: "all";
const selectedCatalogRef = searchParams.get("catalog");
+ const tabParam = searchParams.get("tab");
+ const discoveryTab: DiscoveryTab = DISCOVERY_TABS.includes(tabParam as DiscoveryTab)
+ ? (tabParam as DiscoveryTab)
+ : "all";
+ const detailTab: SkillDetailTab = (["overview", "files", "versions", "agents"] as SkillDetailTab[]).includes(tabParam as SkillDetailTab)
+ ? (tabParam as SkillDetailTab)
+ : selectedPath !== "SKILL.md"
+ ? "files"
+ : "overview";
+ const discoveryCategory = searchParams.get("category");
+ // Discovery grid owns `/skills` whenever no specific skill or catalog entry is
+ // selected; selecting either drops into the existing master/detail surfaces.
+ const isDiscovery = !routeSkillToken && !selectedCatalogRef;
+
+ function setDiscoveryTab(tab: DiscoveryTab) {
+ setSearchParams((current) => {
+ const params = new URLSearchParams(current);
+ if (tab === "all") params.delete("tab");
+ else params.set("tab", tab);
+ params.delete("category");
+ return params;
+ });
+ }
+
+ function setDetailTab(tab: SkillDetailTab) {
+ setSearchParams((current) => {
+ const params = new URLSearchParams(current);
+ if (tab === "overview") params.delete("tab");
+ else params.set("tab", tab);
+ return params;
+ });
+ }
- function setViewParam(view: "installed" | "catalog") {
+ function setDiscoveryCategory(slug: string | null) {
setSearchParams((current) => {
- const next = new URLSearchParams(current);
- if (view === "installed") next.delete("view");
- else next.set("view", "catalog");
- return next;
+ const params = new URLSearchParams(current);
+ if (slug) params.set("category", slug);
+ else params.delete("category");
+ return params;
});
}
@@ -1761,12 +3729,33 @@ export function CompanySkills() {
setCatalogSelectedPath(path);
}
+ function openCreateWizard(initialDraft: SkillCreateDraft = buildBlankSkillDraft()) {
+ setCreateDraft(initialDraft);
+ setCreateError(null);
+ setCreateDialogOpen(true);
+ }
+
useEffect(() => {
setBreadcrumbs([
{ label: "Skills", href: "/skills" },
- ...(routeSkillId ? [{ label: "Detail" }] : []),
+ ...(routeSkillToken ? [{ label: "Detail" }] : []),
]);
- }, [routeSkillId, setBreadcrumbs]);
+ }, [routeSkillToken, setBreadcrumbs]);
+
+ // The old split catalog view no longer exists — catalog/bundled skills now open
+ // as a regular full page keyed by `?catalog=<ref>`. Strip the legacy `view`
+ // param so stale `?view=catalog` deep links land on the new surface (PAP-10907).
+ useEffect(() => {
+ if (!searchParams.has("view")) return;
+ setSearchParams(
+ (current) => {
+ const next = new URLSearchParams(current);
+ next.delete("view");
+ return next;
+ },
+ { replace: true },
+ );
+ }, [searchParams, setSearchParams]);
const skillsQuery = useQuery({
queryKey: queryKeys.companySkills.list(selectedCompanyId ?? ""),
@@ -1774,15 +3763,15 @@ export function CompanySkills() {
enabled: Boolean(selectedCompanyId),
});
- const selectedSkillId = useMemo(() => {
- if (!routeSkillId) return skillsQuery.data?.[0]?.id ?? null;
- return routeSkillId;
- }, [routeSkillId, skillsQuery.data]);
+ const installedSkills = skillsQuery.data ?? [];
+ const routeResolution = useMemo(
+ () => resolveSkillRouteToken(routeSkillToken, installedSkills),
+ [routeSkillToken, installedSkills],
+ );
- useEffect(() => {
- if (activeView !== "installed" || routeSkillId || !selectedSkillId) return;
- navigate(skillRoute(selectedSkillId), { replace: true });
- }, [activeView, navigate, routeSkillId, selectedSkillId]);
+ // At `/skills` root the discovery grid is shown, so we no longer auto-select
+ // the first skill; a skill is only "selected" once it is in the route.
+ const selectedSkillId = routeResolution.skill?.id ?? null;
const detailQuery = useQuery({
queryKey: queryKeys.companySkills.detail(selectedCompanyId ?? "", selectedSkillId ?? ""),
@@ -1796,6 +3785,12 @@ export function CompanySkills() {
enabled: Boolean(selectedCompanyId && selectedSkillId && selectedPath),
});
+ const versionsQuery = useQuery({
+ queryKey: queryKeys.companySkills.versions(selectedCompanyId ?? "", selectedSkillId ?? ""),
+ queryFn: () => companySkillsApi.versions(selectedCompanyId!, selectedSkillId!),
+ enabled: Boolean(selectedCompanyId && selectedSkillId),
+ });
+
const updateStatusQuery = useQuery({
queryKey: queryKeys.companySkills.updateStatus(selectedCompanyId ?? "", selectedSkillId ?? ""),
queryFn: () => companySkillsApi.updateStatus(selectedCompanyId!, selectedSkillId!),
@@ -1807,6 +3802,18 @@ export function CompanySkills() {
staleTime: 60_000,
});
+ useEffect(() => {
+ if (!routeResolution.skill || !routeResolution.shouldRedirect || skillsQuery.isLoading) return;
+ const search = searchParams.toString();
+ navigate(
+ {
+ pathname: skillRoute(routeResolution.skill, installedSkills, selectedPath),
+ search: search ? `?${search}` : "",
+ },
+ { replace: true },
+ );
+ }, [installedSkills, navigate, routeResolution, searchParams, selectedPath, skillsQuery.isLoading]);
+
useEffect(() => {
setExpandedSkillId(selectedSkillId);
}, [selectedSkillId]);
@@ -1854,6 +3861,16 @@ export function CompanySkills() {
const activeDetail = detailQuery.data ?? displayedDetail;
const activeFile = fileQuery.data ?? displayedFile;
+ function routeForSkill(skill: CompanySkillRouteSubject, path?: string | null) {
+ return skillRoute(skill, withRouteSkill(installedSkills, skill), path);
+ }
+
+ function routeForSkillId(skillId: string, path?: string | null) {
+ const skill = installedSkills.find((entry) => entry.id === skillId)
+ ?? (activeDetail?.id === skillId ? activeDetail : null);
+ return skill ? routeForSkill(skill, path) : skillRoute(skillId, path);
+ }
+
function openDeleteDialog() {
setDeleteTargetSkillId(selectedSkillId);
setDeleteTargetDetail(activeDetail ?? null);
@@ -1872,7 +3889,7 @@ export function CompanySkills() {
mutationFn: (importSource: string) => companySkillsApi.importFromSource(selectedCompanyId!, importSource),
onSuccess: async (result) => {
await queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) });
- if (result.imported[0]) navigate(skillRoute(result.imported[0].id));
+ if (result.imported[0]) navigate(routeForSkill(result.imported[0]));
pushToast({
tone: "success",
title: "Skills imported",
@@ -1896,19 +3913,23 @@ export function CompanySkills() {
mutationFn: (payload: CompanySkillCreateRequest) => companySkillsApi.create(selectedCompanyId!, payload),
onSuccess: async (skill) => {
await queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) });
- navigate(skillRoute(skill.id));
- setCreateOpen(false);
+ navigate(routeForSkill(skill));
+ setCreateDialogOpen(false);
+ setCreateError(null);
+ setCreateDraft(buildBlankSkillDraft());
pushToast({
tone: "success",
- title: "Skill created",
+ title: skill.forkedFromSkillId ? "Skill fork created" : "Skill created",
body: `${skill.name} is now editable in the Paperclip workspace.`,
});
},
onError: (error) => {
+ const message = error instanceof Error ? error.message : "Failed to create skill.";
+ setCreateError(message);
pushToast({
tone: "error",
title: "Skill creation failed",
- body: error instanceof Error ? error.message : "Failed to create skill.",
+ body: message,
});
},
});
@@ -1982,6 +4003,48 @@ export function CompanySkills() {
},
});
+ const toggleStar = useMutation({
+ mutationFn: () => {
+ if (!activeDetail) throw new Error("Select a skill first.");
+ return activeDetail.starredByCurrentActor
+ ? companySkillsApi.unstar(selectedCompanyId!, activeDetail.id)
+ : companySkillsApi.star(selectedCompanyId!, activeDetail.id);
+ },
+ onSuccess: async () => {
+ if (!activeDetail) return;
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, activeDetail.id) }),
+ ]);
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Star failed",
+ body: error instanceof Error ? error.message : "Failed to update star.",
+ });
+ },
+ });
+
+ const updateSkillSettings = useMutation({
+ mutationFn: (payload: { skillId: string; sharingScope: Exclude<CompanySkillSharingScope, "public_link"> }) =>
+ companySkillsApi.update(selectedCompanyId!, payload.skillId, { sharingScope: payload.sharingScope }),
+ onSuccess: async (skill) => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, skill.id) }),
+ ]);
+ pushToast({ tone: "success", title: "Sharing updated", body: skill.sharingScope === "private" ? "Private" : "Company" });
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Sharing update failed",
+ body: error instanceof Error ? error.message : "Failed to update sharing scope.",
+ });
+ },
+ });
+
const installUpdate = useMutation({
mutationFn: () => companySkillsApi.installUpdate(selectedCompanyId!, selectedSkillId!),
onSuccess: async (skill) => {
@@ -1991,7 +4054,7 @@ export function CompanySkills() {
queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.updateStatus(selectedCompanyId!, selectedSkillId!) }),
queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.file(selectedCompanyId!, selectedSkillId!, selectedPath) }),
]);
- navigate(skillRoute(skill.id, selectedPath));
+ navigate(routeForSkill(skill, selectedPath));
pushToast({
tone: "success",
title: "Skill updated",
@@ -2017,14 +4080,14 @@ export function CompanySkills() {
const catalogDetailQuery = useQuery({
queryKey: queryKeys.companySkills.catalogDetail(selectedCatalogRef ?? ""),
queryFn: () => companySkillsApi.catalogDetail(selectedCatalogRef!),
- enabled: Boolean(selectedCompanyId && selectedCatalogRef && activeView === "catalog"),
+ enabled: Boolean(selectedCompanyId && selectedCatalogRef),
staleTime: 60_000,
});
const catalogFileQuery = useQuery({
queryKey: queryKeys.companySkills.catalogFile(selectedCatalogRef ?? "", catalogSelectedPath),
queryFn: () => companySkillsApi.catalogFile(selectedCatalogRef!, catalogSelectedPath),
- enabled: Boolean(selectedCompanyId && selectedCatalogRef && activeView === "catalog" && catalogSelectedPath),
+ enabled: Boolean(selectedCompanyId && selectedCatalogRef && catalogSelectedPath),
staleTime: 60_000,
});
@@ -2034,7 +4097,6 @@ export function CompanySkills() {
enabled: Boolean(selectedCompanyId),
});
- const installedSkills = skillsQuery.data ?? [];
const installedByKey = useMemo(
() => new Map(installedSkills.map((skill) => [skill.key, skill])),
[installedSkills],
@@ -2045,6 +4107,40 @@ export function CompanySkills() {
return Array.from(set).sort();
}, [catalogListQuery.data]);
+ // --- Discovery grid derived data (PAP-10879) ---
+ const discoveryCards = useMemo(
+ () => buildDiscoveryCards(installedSkills, catalogListQuery.data ?? []),
+ [installedSkills, catalogListQuery.data],
+ );
+ const discoveryTabCounts = useMemo(() => ({
+ all: discoveryCards.length,
+ installed: discoveryCards.filter((card) => card.installed).length,
+ catalog: discoveryCards.filter((card) => card.catalogRef != null).length,
+ bundled: discoveryCards.filter((card) => card.required).length,
+ }), [discoveryCards]);
+ const discoveryTabCards = useMemo(
+ () => cardsForTab(discoveryCards, discoveryTab),
+ [discoveryCards, discoveryTab],
+ );
+ const discoveryCategoryCounts = useMemo<DiscoveryCategory[]>(() => {
+ const counts = new Map<string, number>();
+ for (const card of discoveryTabCards) {
+ for (const category of card.categories) {
+ counts.set(category, (counts.get(category) ?? 0) + 1);
+ }
+ }
+ return Array.from(counts.entries())
+ .map(([slug, count]) => ({ slug, count }))
+ .sort((a, b) => b.count - a.count || a.slug.localeCompare(b.slug));
+ }, [discoveryTabCards]);
+ const visibleDiscoveryCards = useMemo(() => {
+ const filtered = discoveryTabCards.filter((card) => {
+ if (discoveryCategory && !card.categories.includes(discoveryCategory)) return false;
+ return discoveryMatchesSearch(card, discoverySearch.trim());
+ });
+ return sortDiscoveryCards(filtered, discoverySort, discoveryTab !== "bundled");
+ }, [discoveryTabCards, discoveryCategory, discoverySearch, discoverySort, discoveryTab]);
+
const selectedCatalogSkill = catalogDetailQuery.data
?? (catalogListQuery.data ?? []).find((entry) => entry.id === selectedCatalogRef || entry.key === selectedCatalogRef)
?? null;
@@ -2078,7 +4174,6 @@ export function CompanySkills() {
}
return counts;
}, [installedSkills]);
-
const installCatalog = useMutation({
mutationFn: (payload: { catalogSkillId: string; slug: string | null; force: boolean }) =>
companySkillsApi.installCatalog(selectedCompanyId!, {
@@ -2101,8 +4196,7 @@ export function CompanySkills() {
pushToast({ tone: "warn", title: "Install warnings", body: result.warnings[0] });
}
if (result.action === "created") {
- setViewParam("installed");
- navigate(skillRoute(result.skill.id));
+ navigate(routeForSkill(result.skill));
}
},
onError: (error) => {
@@ -2124,6 +4218,8 @@ export function CompanySkills() {
adapterType: agent.adapterType,
supportsSkills: Boolean(caps.supportsSkills),
required: isRequired,
+ icon: agent.icon,
+ paused: agent.status === "paused" || agent.pausedAt != null,
attached: usedSet.has(agent.id),
requiredKeys,
};
@@ -2131,40 +4227,47 @@ export function CompanySkills() {
}, [agentsQuery.data, adapterCaps, activeDetail]);
const attachAgentsMutation = useMutation({
- mutationFn: async (input: { agentId: string; desiredSkills: string[] }) => {
+ mutationFn: async (input: { agentId: string; desiredSkills: Array<string | AgentDesiredSkillEntry> }) => {
return agentsApi.syncSkills(input.agentId, input.desiredSkills, selectedCompanyId ?? undefined);
},
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, selectedSkillId ?? "") }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.versions(selectedCompanyId!, selectedSkillId ?? "") }),
]);
},
});
- async function handleAttachSubmit(nextAgentIds: string[]) {
+ async function handleAttachSubmit(nextAgentIds: string[], versionId: string | null = null) {
if (!activeDetail) return;
const skillKey = activeDetail.key;
const targetSet = new Set(nextAgentIds);
const current = (activeDetail.usedByAgents ?? []).map((entry) => entry.id);
const currentSet = new Set(current);
+ const currentVersionByAgent = new Map(
+ (activeDetail.usedByAgents ?? []).map((entry) => [entry.id, entry.versionId ?? null]),
+ );
const toAdd = nextAgentIds.filter((id) => !currentSet.has(id));
const toRemove = current.filter((id) => !targetSet.has(id));
- const affected = new Set<string>([...toAdd, ...toRemove]);
+ const toUpdateVersion = nextAgentIds.filter((id) =>
+ currentSet.has(id) && (currentVersionByAgent.get(id) ?? null) !== versionId,
+ );
+ const affected = new Set<string>([...toAdd, ...toRemove, ...toUpdateVersion]);
if (affected.size === 0) {
- setAttachPopoverOpen(false);
return;
}
try {
for (const agentId of affected) {
const snapshot = await agentsApi.skills(agentId, selectedCompanyId ?? undefined);
- const current = new Set(snapshot.desiredSkills ?? []);
- if (targetSet.has(agentId)) current.add(skillKey);
- else current.delete(skillKey);
- await attachAgentsMutation.mutateAsync({ agentId, desiredSkills: Array.from(current) });
+ const currentEntries: AgentDesiredSkillEntry[] = (snapshot.desiredSkillEntries ?? snapshot.desiredSkills.map((key) => ({ key, versionId: null })))
+ .filter((entry) => entry.key !== skillKey);
+ if (targetSet.has(agentId)) {
+ currentEntries.push({ key: skillKey, versionId });
+ }
+ await attachAgentsMutation.mutateAsync({ agentId, desiredSkills: currentEntries });
}
pushToast({ tone: "success", title: "Agents updated", body: `${nextAgentIds.length} agent(s) attached.` });
- setAttachPopoverOpen(false);
} catch (error) {
pushToast({ tone: "error", title: "Update failed", body: error instanceof Error ? error.message : "Failed to update agent skills." });
}
@@ -2242,6 +4345,32 @@ export function CompanySkills() {
importSkill.mutate(trimmedSource);
}
+ // Opening a card stays inside the new store and always lands on a regular full
+ // page: installed skills go to their detail route; catalog/bundled/optional
+ // skills open the standalone catalog page (no modal, no legacy split view).
+ function openDiscoveryCard(card: DiscoveryCard) {
+ if (card.skillId) {
+ navigate(routeForSkillId(card.skillId));
+ return;
+ }
+ if (card.catalogRef) {
+ selectCatalog(card.catalogRef);
+ }
+ }
+
+ // "Back to store" returns to the discovery grid while keeping the tab /
+ // category / source filters the user arrived with (PAP-10907).
+ const backToStoreParams = new URLSearchParams(searchParams);
+ backToStoreParams.delete("catalog");
+ const backToStoreParamString = backToStoreParams.toString();
+ const backToStoreHref = backToStoreParamString ? `/skills?${backToStoreParamString}` : "/skills";
+
+ // Surface the upstream catalog source (GitHub owner/repo/path) on the installed
+ // skill detail, matched by canonical key (PAP-10907).
+ const catalogSourceForDetail = activeDetail
+ ? (catalogListQuery.data ?? []).find((entry) => entry.key === activeDetail.key)?.source ?? null
+ : null;
+
return (
<>
<Dialog open={deleteOpen} onOpenChange={closeDeleteDialog}>
@@ -2356,265 +4485,217 @@ export function CompanySkills() {
}}
/>
- <div className="flex min-h-[calc(100vh-12rem)] flex-col">
- <div className="flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 pt-3 pb-[5px]">
- <Tabs value={activeView} onValueChange={(value) => setViewParam(value === "catalog" ? "catalog" : "installed")}>
- <TabsList variant="line" className="p-0">
- <TabsTrigger value="installed" className="px-3">
- <span>Installed</span>
- <span className="ml-1.5 text-[11px] text-muted-foreground">{installedSkills.length}</span>
- </TabsTrigger>
- <TabsTrigger value="catalog" className="px-3">
- <span>Catalog</span>
- <span className="ml-1.5 text-[11px] text-muted-foreground">{catalogListQuery.data?.length ?? 0}</span>
- </TabsTrigger>
- </TabsList>
- </Tabs>
- <div className="flex items-center gap-2">
- {activeView === "installed" ? (
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => scanProjects.mutate()}
- disabled={scanProjects.isPending}
- title="Scan project workspaces for skills"
- >
- <RefreshCw className={cn("h-4 w-4", scanProjects.isPending && "animate-spin")} />
- </Button>
- ) : null}
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button size="sm" variant="default">
- <Plus className="mr-1 h-3.5 w-3.5" />
- Add skill
- <ChevronDown className="ml-1 h-3.5 w-3.5" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onSelect={() => setViewParam("catalog")}>
- <Boxes className="mr-2 h-4 w-4" />
- Browse catalog
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={() => {
- setViewParam("installed");
- setEmptySourceHelpOpen(true);
- }}
- >
- <Globe className="mr-2 h-4 w-4" />
- Import from URL or path
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={() => {
- setViewParam("installed");
- setCreateOpen(true);
- }}
- >
- <Pencil className="mr-2 h-4 w-4" />
- Create blank skill
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
-
- {activeView === "installed" ? (
- <div className="grid flex-1 gap-0 xl:grid-cols-[19rem_minmax(0,1fr)]">
- <aside className="border-r border-border">
- <div className="border-b border-border px-4 py-3">
- <div className="flex items-center gap-2 border-b border-border pb-2">
- <Search className="h-4 w-4 text-muted-foreground" />
- <input
- value={skillFilter}
- onChange={(event) => setSkillFilter(event.target.value)}
- placeholder="Filter skills"
- className="w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
- />
- <SourceFilterMenu counts={sourceCounts} value={sourceFilter} onChange={setSourceFilter} />
- </div>
-
- <div className="mt-3 flex items-center gap-2 border-b border-border pb-2">
- <input
- value={source}
- onChange={(event) => setSource(event.target.value)}
- placeholder="Paste path, GitHub URL, or skills.sh command"
- className="w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
- />
- <Button
- size="sm"
- variant="ghost"
- onClick={handleAddSkillSource}
- disabled={importSkill.isPending}
- >
- {importSkill.isPending ? <RefreshCw className="h-4 w-4 animate-spin" /> : "Add"}
- </Button>
- </div>
- {scanStatusMessage && (
- <p className="mt-3 text-xs text-muted-foreground">{scanStatusMessage}</p>
- )}
- </div>
-
- {createOpen && (
- <NewSkillForm
- onCreate={(payload) => createSkill.mutate(payload)}
- isPending={createSkill.isPending}
- onCancel={() => setCreateOpen(false)}
- />
- )}
+ <Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
+ <DialogContent className="flex max-h-[85vh] flex-col overflow-y-auto sm:max-w-3xl">
+ <DialogHeader>
+ <DialogTitle>{createDraft.forkedFromSkillId ? "Fork skill" : "Create a new skill"}</DialogTitle>
+ <DialogDescription>
+ {createDraft.forkedFromSkillId
+ ? "Review the fork metadata and create an editable company copy."
+ : "Create an editable company skill in the Paperclip workspace."}
+ </DialogDescription>
+ </DialogHeader>
+ <NewSkillWizard
+ initialDraft={createDraft}
+ onCreate={(payload) => createSkill.mutate(payload)}
+ isPending={createSkill.isPending}
+ error={createError}
+ onCancel={() => setCreateDialogOpen(false)}
+ />
+ </DialogContent>
+ </Dialog>
- {skillsQuery.isLoading ? (
- <PageSkeleton variant="list" />
- ) : skillsQuery.error ? (
- <div className="px-4 py-6 text-sm text-destructive">{skillsQuery.error.message}</div>
- ) : installedSkills.length === 0 ? (
- <div className="px-4 py-8">
- <EmptyState
- icon={Boxes}
- message="No skills installed yet."
- />
- <div className="mt-3 flex flex-col items-center gap-2">
- <Button size="sm" onClick={() => setViewParam("catalog")}>
- <Boxes className="mr-1.5 h-3.5 w-3.5" /> Browse catalog
- </Button>
- <Button size="sm" variant="ghost" onClick={() => setEmptySourceHelpOpen(true)}>
- Import from URL
- </Button>
- </div>
- </div>
- ) : (
- <SkillList
- skills={installedSkills}
- selectedSkillId={selectedSkillId}
- skillFilter={skillFilter}
- sourceFilter={sourceFilter}
- expandedSkillId={expandedSkillId}
- expandedDirs={expandedDirs}
- selectedPaths={selectedSkillId ? { [selectedSkillId]: selectedPath } : {}}
- onToggleSkill={(currentSkillId) =>
- setExpandedSkillId((current) => current === currentSkillId ? null : currentSkillId)
- }
- onToggleDir={(currentSkillId, path) => {
- setExpandedDirs((current) => {
- const next = new Set(current[currentSkillId] ?? []);
- if (next.has(path)) next.delete(path);
- else next.add(path);
- return { ...current, [currentSkillId]: next };
- });
- }}
- onSelectSkill={(currentSkillId) => setExpandedSkillId(currentSkillId)}
- onSelectPath={() => {}}
- onClearFilters={() => setSourceFilter("all")}
- />
- )}
- </aside>
-
- <div className="min-w-0 pl-6">
- <SkillPane
- loading={skillsQuery.isLoading || detailQuery.isLoading}
- detail={activeDetail}
- file={activeFile}
- fileLoading={fileQuery.isLoading && !activeFile}
- updateStatus={updateStatusQuery.data}
- updateStatusLoading={updateStatusQuery.isLoading}
- viewMode={viewMode}
- editMode={editMode}
- draft={draft}
- setViewMode={setViewMode}
- setEditMode={setEditMode}
- setDraft={setDraft}
- onCheckUpdates={() => {
- void updateStatusQuery.refetch();
- }}
- checkUpdatesPending={updateStatusQuery.isFetching}
- onInstallUpdate={() => installUpdate.mutate()}
- installUpdatePending={installUpdate.isPending}
- onDelete={openDeleteDialog}
- deletePending={deleteSkill.isPending}
- onSave={() => saveFile.mutate()}
- savePending={saveFile.isPending}
- attachAgents={eligibleAgentsForAttach}
- attachPopoverOpen={attachPopoverOpen}
- setAttachPopoverOpen={setAttachPopoverOpen}
- onSubmitAttach={handleAttachSubmit}
- attachPending={attachAgentsMutation.isPending}
+ <Dialog open={importDialogOpen} onOpenChange={setImportDialogOpen}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Import a skill</DialogTitle>
+ <DialogDescription>
+ Paste a local path, GitHub URL, or `skills.sh` command to import a skill into this company.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-3">
+ <div className="flex items-center gap-2 border-b border-border pb-2">
+ <Input
+ value={source}
+ onChange={(event) => setSource(event.target.value)}
+ placeholder="Paste path, GitHub URL, or skills.sh command"
+ className="h-9 rounded-none border-0 px-0 shadow-none focus-visible:ring-0"
/>
+ <Button size="sm" onClick={handleAddSkillSource} disabled={importSkill.isPending}>
+ {importSkill.isPending ? <RefreshCw className="h-4 w-4 animate-spin" /> : "Import"}
+ </Button>
</div>
+ <a
+ href="https://skills.sh"
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-start justify-between rounded-md border border-border px-3 py-3 text-sm text-foreground no-underline transition-colors hover:bg-accent/40"
+ >
+ <span>
+ <span className="block font-medium">Browse skills.sh</span>
+ <span className="mt-1 block text-muted-foreground">Find install commands and paste one here.</span>
+ </span>
+ <ExternalLink className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ </a>
+ <a
+ href="https://github.com/search?q=SKILL.md&type=code"
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-start justify-between rounded-md border border-border px-3 py-3 text-sm text-foreground no-underline transition-colors hover:bg-accent/40"
+ >
+ <span>
+ <span className="block font-medium">Search GitHub</span>
+ <span className="mt-1 block text-muted-foreground">Look for repositories with `SKILL.md`, then paste the repo URL.</span>
+ </span>
+ <ExternalLink className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ </a>
</div>
- ) : (
- <div className="grid flex-1 gap-0 xl:grid-cols-[19rem_minmax(0,1fr)]">
- <aside className="border-r border-border">
- <div className="border-b border-border px-4 py-3">
- <div className="flex items-center gap-2 border-b border-border pb-2">
- <Search className="h-4 w-4 text-muted-foreground" />
- <input
- value={catalogFilter}
- onChange={(event) => setCatalogFilter(event.target.value)}
- placeholder="Search catalog"
- className="w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
- />
- <CatalogFilterMenu
- kindFilter={catalogKindFilter}
- categoryFilter={catalogCategoryFilter}
- categories={catalogCategories}
- onKindChange={setCatalogKindFilter}
- onCategoryChange={setCatalogCategoryFilter}
- />
- </div>
- </div>
+ </DialogContent>
+ </Dialog>
- {catalogListQuery.isLoading ? (
- <PageSkeleton variant="list" />
- ) : catalogListQuery.error ? (
- <div className="px-4 py-6 text-sm text-destructive">{catalogListQuery.error.message}</div>
- ) : (
- <CatalogList
- skills={catalogListQuery.data ?? []}
- kindFilter={catalogKindFilter}
- categoryFilter={catalogCategoryFilter}
- catalogFilter={catalogFilter}
- installedByKey={installedByKey}
- selectedCatalogRef={selectedCatalogRef}
+ {isDiscovery ? (
+ <DiscoveryGrid
+ tab={discoveryTab}
+ tabCounts={discoveryTabCounts}
+ onTabChange={setDiscoveryTab}
+ categories={discoveryCategoryCounts}
+ categoryTotal={discoveryTabCards.length}
+ activeCategory={discoveryCategory}
+ onCategoryChange={setDiscoveryCategory}
+ search={discoverySearch}
+ onSearchChange={setDiscoverySearch}
+ sort={discoverySort}
+ onSortChange={setDiscoverySort}
+ cards={visibleDiscoveryCards}
+ onOpenCard={openDiscoveryCard}
+ loading={skillsQuery.isLoading || catalogListQuery.isLoading}
+ error={skillsQuery.error?.message ?? catalogListQuery.error?.message ?? null}
+ totalCount={discoveryCards.length}
+ onCreate={() => openCreateWizard()}
+ onImport={() => setImportDialogOpen(true)}
+ onBrowseCatalog={() => setDiscoveryTab("catalog")}
+ onScan={() => scanProjects.mutate()}
+ scanPending={scanProjects.isPending}
+ scanStatus={scanStatusMessage}
+ />
+ ) : activeView === "installed" && selectedSkillId ? (
+ <SkillDetailPage
+ detail={activeDetail}
+ catalogSource={catalogSourceForDetail}
+ routeSkills={installedSkills}
+ loading={skillsQuery.isLoading || detailQuery.isLoading}
+ activeTab={detailTab}
+ onTabChange={setDetailTab}
+ selectedPath={selectedPath}
+ file={activeFile}
+ fileLoading={fileQuery.isLoading && !activeFile}
+ viewMode={viewMode}
+ editMode={editMode}
+ draft={draft}
+ setViewMode={setViewMode}
+ setEditMode={setEditMode}
+ setDraft={setDraft}
+ onSave={() => saveFile.mutate()}
+ savePending={saveFile.isPending}
+ versions={versionsQuery.data ?? []}
+ versionsLoading={versionsQuery.isLoading}
+ attachAgents={eligibleAgentsForAttach}
+ onSubmitAttach={handleAttachSubmit}
+ attachPending={attachAgentsMutation.isPending}
+ expandedDirs={expandedDirs[selectedSkillId] ?? new Set<string>()}
+ onToggleDir={(path) => {
+ setExpandedDirs((current) => {
+ const next = new Set(current[selectedSkillId] ?? []);
+ if (next.has(path)) next.delete(path);
+ else next.add(path);
+ return { ...current, [selectedSkillId]: next };
+ });
+ }}
+ onSelectPath={(path) => {
+ setDetailTab("files");
+ navigate(routeForSkillId(selectedSkillId, path));
+ }}
+ updateStatus={updateStatusQuery.data}
+ updateStatusLoading={updateStatusQuery.isLoading}
+ onCheckUpdates={() => {
+ void updateStatusQuery.refetch();
+ }}
+ checkUpdatesPending={updateStatusQuery.isFetching}
+ onInstallUpdate={() => installUpdate.mutate()}
+ installUpdatePending={installUpdate.isPending}
+ onToggleStar={() => toggleStar.mutate()}
+ starPending={toggleStar.isPending}
+ onFork={() => activeDetail && openCreateWizard(buildForkSkillDraft(activeDetail))}
+ onUpdateSharingScope={(sharingScope) => activeDetail && updateSkillSettings.mutate({ skillId: activeDetail.id, sharingScope })}
+ updateSharingPending={updateSkillSettings.isPending}
+ onDelete={openDeleteDialog}
+ deletePending={deleteSkill.isPending}
+ />
+ ) : selectedCatalogRef ? (
+ // Catalog / optional / bundled skills open as a regular full page in the
+ // new store — no modal, no legacy split view (PAP-10907).
+ <div className="min-h-[calc(100vh-12rem)]">
+ <div className="border-b border-border px-4 py-3">
+ <Link
+ to={backToStoreHref}
+ className="inline-flex items-center gap-1.5 text-sm text-muted-foreground no-underline transition-colors hover:text-foreground"
+ >
+ <ChevronLeft className="h-4 w-4" />
+ Back to store
+ </Link>
+ </div>
+ {catalogListQuery.isLoading || catalogDetailQuery.isLoading ? (
+ <PageSkeleton variant="detail" />
+ ) : !selectedCatalogSkill ? (
+ <EmptyState icon={Boxes} message="Catalog skill not found." />
+ ) : (
+ <div className="grid gap-0 xl:grid-cols-[14rem_minmax(0,1fr)]">
+ <aside className="border-b border-border px-3 py-4 xl:border-b-0 xl:border-r">
+ <div className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">Files</div>
+ <SkillTree
+ nodes={buildTree(selectedCatalogSkill.files.map((file) => ({ path: file.path, kind: file.kind })))}
+ skillId={selectedCatalogSkill.id}
selectedPath={catalogSelectedPath}
- expandedSkillId={expandedCatalogSkillId}
- expandedDirs={expandedCatalogDirs}
- onSelect={selectCatalog}
- onSelectPath={selectCatalog}
- onToggleSkill={(catalogRef) =>
- setExpandedCatalogSkillId((current) => current === catalogRef ? null : catalogRef)
- }
- onToggleDir={(catalogRef, path) => {
+ expandedDirs={expandedCatalogDirs[selectedCatalogSkill.id] ?? new Set<string>()}
+ onToggleDir={(path) =>
setExpandedCatalogDirs((current) => {
- const next = new Set(current[catalogRef] ?? []);
+ const next = new Set(current[selectedCatalogSkill.id] ?? []);
if (next.has(path)) next.delete(path);
else next.add(path);
- return { ...current, [catalogRef]: next };
- });
- }}
+ return { ...current, [selectedCatalogSkill.id]: next };
+ })
+ }
+ onSelectPath={(path) => setCatalogSelectedPath(path)}
+ fileHref={() => `/skills?catalog=${encodeURIComponent(selectedCatalogRef)}`}
/>
- )}
- </aside>
-
- <div className="min-w-0 pl-6">
- <CatalogDetailPane
- skill={selectedCatalogSkill}
- packageName={selectedCatalogSkill?.packageName ?? (selectedCatalogSkill ? installedByKey.get(selectedCatalogSkill.key)?.packageName : null) ?? null}
- packageVersion={selectedCatalogSkill?.packageVersion ?? (selectedCatalogSkill ? installedByKey.get(selectedCatalogSkill.key)?.packageVersion : null) ?? null}
- installedSkill={selectedCatalogSkill ? installedByKey.get(selectedCatalogSkill.key) ?? null : null}
- installedSkillId={(selectedCatalogSkill ? installedByKey.get(selectedCatalogSkill.key)?.id : null) ?? null}
- fileQuery={catalogFileQuery}
- selectedPath={catalogSelectedPath}
- onInstall={() => selectedCatalogSkill && openInstallDialog(selectedCatalogSkill)}
- onUpdate={() => selectedCatalogSkill && openInstallDialog(selectedCatalogSkill)}
- onOpenInstalled={(skillId) => {
- setViewParam("installed");
- navigate(skillRoute(skillId));
- }}
- loadingPrimaryAction={installCatalog.isPending}
- />
+ </aside>
+ <div className="min-w-0">
+ <CatalogDetailPane
+ skill={selectedCatalogSkill}
+ packageName={selectedCatalogSkill.packageName ?? installedByKey.get(selectedCatalogSkill.key)?.packageName ?? null}
+ packageVersion={selectedCatalogSkill.packageVersion ?? installedByKey.get(selectedCatalogSkill.key)?.packageVersion ?? null}
+ installedSkill={installedByKey.get(selectedCatalogSkill.key) ?? null}
+ installedSkillId={installedByKey.get(selectedCatalogSkill.key)?.id ?? null}
+ fileQuery={catalogFileQuery}
+ selectedPath={catalogSelectedPath}
+ onInstall={() => openInstallDialog(selectedCatalogSkill)}
+ onUpdate={() => openInstallDialog(selectedCatalogSkill)}
+ onOpenInstalled={(skillId) => navigate(routeForSkillId(skillId))}
+ loadingPrimaryAction={installCatalog.isPending}
+ />
+ </div>
</div>
- </div>
- )}
- </div>
+ )}
+ </div>
+ ) : (
+ <div className="min-h-[calc(100vh-12rem)]">
+ {skillsQuery.isLoading ? (
+ <PageSkeleton variant="detail" />
+ ) : (
+ <EmptyState icon={Boxes} message="Skill not found." />
+ )}
+ </div>
+ )}
</>
);
}
diff --git a/ui/storybook/stories/acpx-local.stories.tsx b/ui/storybook/stories/acpx-local.stories.tsx
index 740b24ccab..7baf5d9e63 100644
--- a/ui/storybook/stories/acpx-local.stories.tsx
+++ b/ui/storybook/stories/acpx-local.stories.tsx
@@ -424,6 +424,23 @@ function AcpxLocalTranscriptStory() {
const SKILLS_COMPANY_ID = "company-storybook";
+const defaultStoreSkillFields = {
+ iconUrl: null,
+ color: null,
+ tagline: null,
+ authorName: null,
+ homepageUrl: null,
+ categories: [],
+ sharingScope: "company" as const,
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 0,
+ installCount: 1,
+ forkCount: 0,
+ currentVersionId: null,
+};
+
const acpxSkillsCompanyLibrary: CompanySkillListItem[] = [
{
id: "skill-paperclip",
@@ -439,6 +456,7 @@ const acpxSkillsCompanyLibrary: CompanySkillListItem[] = [
trustLevel: "scripts_executables",
compatibility: "compatible",
fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ ...defaultStoreSkillFields,
createdAt: new Date("2026-04-12T09:00:00.000Z"),
updatedAt: new Date("2026-04-22T15:30:00.000Z"),
attachedAgentCount: 4,
@@ -466,6 +484,7 @@ const acpxSkillsCompanyLibrary: CompanySkillListItem[] = [
trustLevel: "markdown_only",
compatibility: "compatible",
fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ ...defaultStoreSkillFields,
createdAt: new Date("2026-04-15T10:00:00.000Z"),
updatedAt: new Date("2026-04-25T12:00:00.000Z"),
attachedAgentCount: 2,
@@ -493,6 +512,7 @@ const acpxSkillsCompanyLibrary: CompanySkillListItem[] = [
trustLevel: "assets",
compatibility: "compatible",
fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ ...defaultStoreSkillFields,
createdAt: new Date("2026-04-18T11:00:00.000Z"),
updatedAt: new Date("2026-04-26T09:30:00.000Z"),
attachedAgentCount: 1,
diff --git a/ui/storybook/stories/skills-store-detail.stories.tsx b/ui/storybook/stories/skills-store-detail.stories.tsx
new file mode 100644
index 0000000000..a592dfbecd
--- /dev/null
+++ b/ui/storybook/stories/skills-store-detail.stories.tsx
@@ -0,0 +1,205 @@
+import { useState } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import type {
+ CompanySkillDetail,
+ CompanySkillFileDetail,
+ CompanySkillVersion,
+} from "@paperclipai/shared";
+import { SkillDetailPage } from "@/pages/CompanySkills";
+
+type DetailTab = "overview" | "files" | "versions" | "agents";
+
+const NOW = new Date("2026-06-01T12:00:00Z");
+
+const MOCK_DETAIL: CompanySkillDetail = {
+ id: "skill-1",
+ companyId: "company-1",
+ key: "paperclipai/paperclip/deep-research",
+ slug: "deep-research",
+ name: "deep-research",
+ description:
+ "Fan-out web searches, fetch sources, adversarially verify claims, and synthesize a cited report. Best for multi-source, fact-checked research where one search angle will not find everything.",
+ markdown: "# deep-research\n\nResearch harness.",
+ sourceType: "github",
+ sourceLocator: "github.com/paperclipai/skills",
+ sourceRef: "a1b2c3d4e5f6",
+ trustLevel: "scripts_executables",
+ compatibility: "compatible",
+ fileInventory: [
+ { path: "SKILL.md", kind: "skill" },
+ { path: "references/methodology.md", kind: "reference" },
+ { path: "scripts/fetch.ts", kind: "script" },
+ ],
+ iconUrl: null,
+ color: "#6366f1",
+ tagline: "Multi-source research with citation-grade synthesis.",
+ authorName: "Astra",
+ homepageUrl: null,
+ categories: ["research", "writing"],
+ sharingScope: "company",
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 211,
+ installCount: 96,
+ forkCount: 17,
+ currentVersionId: "v-2",
+ metadata: null,
+ createdAt: NOW,
+ updatedAt: NOW,
+ attachedAgentCount: 4,
+ usedByAgents: [
+ { id: "a-1", name: "Astra", urlKey: "astra", adapterType: "process", desired: true, actualState: null, versionId: null },
+ { id: "a-2", name: "Scout", urlKey: "scout", adapterType: "http", desired: true, actualState: null, versionId: null },
+ { id: "a-3", name: "Quill", urlKey: "quill", adapterType: "process", desired: true, actualState: null, versionId: null },
+ { id: "a-4", name: "Marlow", urlKey: "marlow", adapterType: "process", desired: true, actualState: null, versionId: null },
+ ],
+ editable: true,
+ editableReason: null,
+ sourceLabel: "GitHub",
+ sourceBadge: "github",
+ sourcePath: "github.com/paperclipai/skills/tree/main/deep-research",
+ currentVersion: {
+ id: "v-2",
+ companyId: "company-1",
+ companySkillId: "skill-1",
+ revisionNumber: 2,
+ label: "tighten verifier",
+ fileInventory: [],
+ authorAgentId: "a-1",
+ authorUserId: null,
+ createdAt: NOW,
+ },
+ starredByCurrentActor: true,
+};
+
+const MOCK_VERSIONS: CompanySkillVersion[] = [
+ {
+ id: "v-2",
+ companyId: "company-1",
+ companySkillId: "skill-1",
+ revisionNumber: 2,
+ label: "tighten verifier",
+ fileInventory: [{ path: "SKILL.md", kind: "skill", content: "# v2" }],
+ authorAgentId: "a-1",
+ authorUserId: null,
+ createdAt: NOW,
+ },
+ {
+ id: "v-1",
+ companyId: "company-1",
+ companySkillId: "skill-1",
+ revisionNumber: 1,
+ label: null,
+ fileInventory: [{ path: "SKILL.md", kind: "skill", content: "# v1" }],
+ authorAgentId: "a-1",
+ authorUserId: null,
+ createdAt: NOW,
+ },
+];
+
+const MOCK_FILE: CompanySkillFileDetail = {
+ skillId: "skill-1",
+ path: "SKILL.md",
+ kind: "skill",
+ content: "---\nname: deep-research\n---\n\n# deep-research\n\nFan out, verify, synthesize.",
+ language: "markdown",
+ markdown: true,
+ editable: true,
+};
+
+// Agents available to attach, including a paused one to exercise the badge.
+const MOCK_ATTACH_AGENTS = [
+ { id: "a-1", name: "Astra", adapterType: "process", supportsSkills: true, required: false, icon: "telescope", paused: false },
+ { id: "a-2", name: "Scout", adapterType: "http", supportsSkills: true, required: false, icon: "compass", paused: false },
+ { id: "a-3", name: "Quill", adapterType: "process", supportsSkills: true, required: false, icon: "feather", paused: true },
+ { id: "a-4", name: "Marlow", adapterType: "process", supportsSkills: true, required: false, icon: "bot", paused: false },
+ { id: "a-5", name: "Pixel", adapterType: "process", supportsSkills: true, required: false, icon: "palette", paused: false },
+ { id: "a-6", name: "Forge", adapterType: "process", supportsSkills: false, required: false, icon: "hammer", paused: false },
+];
+
+function SkillDetailHarness({ initialTab = "overview" as DetailTab }: { initialTab?: DetailTab }) {
+ const [activeTab, setActiveTab] = useState<DetailTab>(initialTab);
+ const [viewMode, setViewMode] = useState<"preview" | "code">("preview");
+ const [editMode, setEditMode] = useState(false);
+ const [draft, setDraft] = useState(MOCK_FILE.content);
+
+ return (
+ <SkillDetailPage
+ detail={MOCK_DETAIL}
+ catalogSource={{
+ type: "github",
+ hostname: "github.com",
+ owner: "mvanhorn",
+ repo: "last30days-skill",
+ ref: "v3.3.0",
+ commit: "daca71f89eb71d0d56d01a43ed7627aa919dba4f",
+ path: "skills/last30days",
+ url: "https://github.com/mvanhorn/last30days-skill/tree/v3.3.0/skills/last30days",
+ }}
+ loading={false}
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ selectedPath="SKILL.md"
+ file={MOCK_FILE}
+ fileLoading={false}
+ viewMode={viewMode}
+ editMode={editMode}
+ draft={draft}
+ setViewMode={setViewMode}
+ setEditMode={setEditMode}
+ setDraft={setDraft}
+ onSave={() => {}}
+ savePending={false}
+ versions={MOCK_VERSIONS}
+ versionsLoading={false}
+ attachAgents={MOCK_ATTACH_AGENTS}
+ onSubmitAttach={() => {}}
+ attachPending={false}
+ expandedDirs={new Set<string>()}
+ onToggleDir={() => {}}
+ onSelectPath={() => {}}
+ updateStatus={{
+ supported: true,
+ reason: null,
+ trackingRef: "main",
+ currentRef: "a1b2c3d4e5f6",
+ latestRef: "a1b2c3d4e5f6",
+ hasUpdate: false,
+ installedHash: null,
+ originHash: null,
+ userModifiedAt: null,
+ updateHoldReason: null,
+ auditVerdict: null,
+ auditCodes: [],
+ }}
+ updateStatusLoading={false}
+ onCheckUpdates={() => {}}
+ checkUpdatesPending={false}
+ onInstallUpdate={() => {}}
+ installUpdatePending={false}
+ onToggleStar={() => {}}
+ starPending={false}
+ onFork={() => {}}
+ onUpdateSharingScope={() => {}}
+ updateSharingPending={false}
+ onDelete={() => {}}
+ deletePending={false}
+ />
+ );
+}
+
+const meta: Meta<typeof SkillDetailHarness> = {
+ title: "Skills Store/Skill detail",
+ component: SkillDetailHarness,
+ parameters: { layout: "fullscreen" },
+};
+
+export default meta;
+
+type Story = StoryObj<typeof SkillDetailHarness>;
+
+export const Overview: Story = { args: { initialTab: "overview" } };
+export const AgentsTab: Story = { args: { initialTab: "agents" } };
+export const FilesTab: Story = { args: { initialTab: "files" } };
+export const VersionsTab: Story = { args: { initialTab: "versions" } };
diff --git a/ui/storybook/stories/skills-store-discovery.stories.tsx b/ui/storybook/stories/skills-store-discovery.stories.tsx
new file mode 100644
index 0000000000..eb13b82b80
--- /dev/null
+++ b/ui/storybook/stories/skills-store-discovery.stories.tsx
@@ -0,0 +1,322 @@
+import { useMemo, useState } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { DiscoveryGrid, type DiscoveryCard, type DiscoveryCategory } from "@/pages/CompanySkills";
+
+type DiscoveryTab = "all" | "installed" | "catalog" | "bundled";
+type DiscoverySort = "agents" | "stars" | "forks" | "recent" | "alphabetical";
+
+const MOCK_CARDS: DiscoveryCard[] = [
+ {
+ key: "paperclipai/paperclip/paperclip-dev",
+ skillId: "s-dev",
+ catalogRef: null,
+ name: "paperclip-dev",
+ slug: "paperclip-dev",
+ author: "Paperclip",
+ version: "v2.4.1",
+ description: "Develop and operate a local Paperclip instance.",
+ categories: ["devops", "coding"],
+ iconUrl: null,
+ color: null,
+ starCount: 48,
+ agentCount: 12,
+ forkCount: 3,
+ installed: true,
+ required: false,
+ forkedFrom: false,
+ updatedAt: Date.now() - 2 * 86_400_000,
+ sourceBadge: "github",
+ },
+ {
+ key: "here.now/agent-browser",
+ skillId: "s-browser",
+ catalogRef: null,
+ name: "agent-browser",
+ slug: "agent-browser",
+ author: "here.now",
+ version: "v0.8.2",
+ description: "Browser automation CLI for AI agents.",
+ categories: ["research", "browsers"],
+ iconUrl: null,
+ color: null,
+ starCount: 81,
+ agentCount: 9,
+ forkCount: 11,
+ installed: false,
+ required: false,
+ forkedFrom: false,
+ updatedAt: Date.now() - 5 * 86_400_000,
+ sourceBadge: "skills_sh",
+ },
+ {
+ key: "paperclipai/paperclip/verify",
+ skillId: "s-verify",
+ catalogRef: null,
+ name: "verify",
+ slug: "verify",
+ author: "Paperclip",
+ version: "v1.0.3",
+ description: "Verify a code change works by running the app.",
+ categories: ["testing"],
+ iconUrl: null,
+ color: null,
+ starCount: 22,
+ agentCount: 7,
+ forkCount: 1,
+ installed: true,
+ required: false,
+ forkedFrom: false,
+ updatedAt: Date.now() - 9 * 86_400_000,
+ sourceBadge: "local",
+ },
+ {
+ key: "you/hue-prosumer",
+ skillId: "s-hue",
+ catalogRef: null,
+ name: "hue-prosumer",
+ slug: "hue-prosumer",
+ author: "you",
+ version: "v0.1.0",
+ description: "Generate design language skills, prosumer remix.",
+ categories: ["design"],
+ iconUrl: null,
+ color: null,
+ starCount: 4,
+ agentCount: 2,
+ forkCount: 0,
+ installed: true,
+ required: false,
+ forkedFrom: true,
+ updatedAt: Date.now() - 1 * 86_400_000,
+ sourceBadge: "paperclip",
+ },
+ {
+ key: "anthropic/claude-api",
+ skillId: null,
+ catalogRef: "c-claude-api",
+ name: "claude-api",
+ slug: "claude-api",
+ author: "Anthropic",
+ version: "v1.6.0",
+ description: "Build, debug and optimize Claude API apps.",
+ categories: ["coding", "ai"],
+ iconUrl: null,
+ color: null,
+ starCount: 0,
+ agentCount: 0,
+ forkCount: 0,
+ installed: false,
+ required: false,
+ forkedFrom: false,
+ updatedAt: 0,
+ sourceBadge: "url",
+ },
+ {
+ key: "paperclipai/paperclip/security-review",
+ skillId: "s-sec",
+ catalogRef: null,
+ name: "security-review",
+ slug: "security-review",
+ author: "Paperclip",
+ version: "v1.1.0",
+ description: "Security review of pending changes on a branch.",
+ categories: ["security"],
+ iconUrl: null,
+ color: null,
+ starCount: 29,
+ agentCount: 5,
+ forkCount: 2,
+ installed: true,
+ required: false,
+ forkedFrom: false,
+ updatedAt: Date.now() - 3 * 86_400_000,
+ sourceBadge: "github",
+ },
+ {
+ key: "yuki/commit-perfect",
+ skillId: null,
+ catalogRef: "c-commit",
+ name: "commit-perfect",
+ slug: "commit-perfect",
+ author: "Yuki",
+ version: "v3.0.1",
+ description: "Polish commits and PR titles before review.",
+ categories: ["git", "workflow"],
+ iconUrl: null,
+ color: null,
+ starCount: 0,
+ agentCount: 0,
+ forkCount: 0,
+ installed: false,
+ required: false,
+ forkedFrom: false,
+ updatedAt: 0,
+ sourceBadge: "skills_sh",
+ },
+ {
+ key: "astra/deep-research",
+ skillId: "s-research",
+ catalogRef: null,
+ name: "deep-research",
+ slug: "deep-research",
+ author: "Astra",
+ version: "v2.0.0",
+ description: "Multi-source research with citation-grade synthesis.",
+ categories: ["research"],
+ iconUrl: null,
+ color: null,
+ starCount: 211,
+ agentCount: 31,
+ forkCount: 17,
+ installed: true,
+ required: false,
+ forkedFrom: false,
+ updatedAt: Date.now() - 4 * 86_400_000,
+ sourceBadge: "local",
+ },
+ {
+ key: "paperclipai/paperclip/paperclip",
+ skillId: "s-core",
+ catalogRef: "c-core",
+ name: "paperclip",
+ slug: "paperclip",
+ author: "Paperclip",
+ version: "core",
+ description: "Control plane API for tasks, routines, and coordination.",
+ categories: ["core"],
+ iconUrl: null,
+ color: null,
+ starCount: 0,
+ agentCount: 12,
+ forkCount: 0,
+ installed: true,
+ required: true,
+ forkedFrom: false,
+ updatedAt: Date.now() - 30 * 86_400_000,
+ sourceBadge: "paperclip",
+ },
+ {
+ key: "paperclipai/paperclip/diagnose-why-work-stopped",
+ skillId: "s-diag",
+ catalogRef: "c-diag",
+ name: "diagnose-why-work-stopped",
+ slug: "diagnose-why-work-stopped",
+ author: "Paperclip",
+ version: "core",
+ description: "Forensics for stalled or looping work trees.",
+ categories: ["workflow"],
+ iconUrl: null,
+ color: null,
+ starCount: 0,
+ agentCount: 8,
+ forkCount: 0,
+ installed: true,
+ required: true,
+ forkedFrom: false,
+ updatedAt: Date.now() - 28 * 86_400_000,
+ sourceBadge: "url",
+ },
+];
+
+const DISCOVERY_TABS: DiscoveryTab[] = ["all", "installed", "catalog", "bundled"];
+
+function cardsForTab(cards: DiscoveryCard[], tab: DiscoveryTab): DiscoveryCard[] {
+ if (tab === "installed") return cards.filter((c) => c.installed);
+ if (tab === "catalog") return cards.filter((c) => c.catalogRef != null);
+ if (tab === "bundled") return cards.filter((c) => c.required);
+ return cards;
+}
+
+function DiscoveryGridHarness({
+ initialTab = "all",
+ cards = MOCK_CARDS,
+}: {
+ initialTab?: DiscoveryTab;
+ cards?: DiscoveryCard[];
+}) {
+ const [tab, setTab] = useState<DiscoveryTab>(initialTab);
+ const [sort, setSort] = useState<DiscoverySort>("agents");
+ const [category, setCategory] = useState<string | null>(null);
+ const [search, setSearch] = useState("");
+
+ const tabCards = useMemo(() => cardsForTab(cards, tab), [cards, tab]);
+ const categories = useMemo<DiscoveryCategory[]>(() => {
+ const counts = new Map<string, number>();
+ for (const card of tabCards) for (const c of card.categories) counts.set(c, (counts.get(c) ?? 0) + 1);
+ return Array.from(counts.entries())
+ .map(([slug, count]) => ({ slug, count }))
+ .sort((a, b) => b.count - a.count || a.slug.localeCompare(b.slug));
+ }, [tabCards]);
+ const visible = useMemo(() => {
+ const q = search.trim().toLowerCase();
+ const filtered = tabCards.filter((card) => {
+ if (category && !card.categories.includes(category)) return false;
+ if (!q) return true;
+ return `${card.name} ${card.author} ${card.categories.join(" ")}`.toLowerCase().includes(q);
+ });
+ const demote = tab !== "bundled";
+ return [...filtered].sort((a, b) => {
+ if (demote && a.required !== b.required) return a.required ? 1 : -1;
+ if (sort === "stars") return b.starCount - a.starCount;
+ if (sort === "forks") return b.forkCount - a.forkCount;
+ if (sort === "recent") return b.updatedAt - a.updatedAt;
+ if (sort === "alphabetical") return a.name.localeCompare(b.name);
+ return b.agentCount - a.agentCount;
+ });
+ }, [tabCards, category, search, sort, tab]);
+
+ const tabCounts = useMemo(
+ () => ({
+ all: cards.length,
+ installed: cards.filter((c) => c.installed).length,
+ catalog: cards.filter((c) => c.catalogRef != null).length,
+ bundled: cards.filter((c) => c.required).length,
+ }),
+ [cards],
+ ) as Record<DiscoveryTab, number>;
+
+ return (
+ <DiscoveryGrid
+ tab={tab}
+ tabCounts={tabCounts}
+ onTabChange={(next) => {
+ setTab(next);
+ setCategory(null);
+ }}
+ categories={categories}
+ categoryTotal={tabCards.length}
+ activeCategory={category}
+ onCategoryChange={setCategory}
+ search={search}
+ onSearchChange={setSearch}
+ sort={sort}
+ onSortChange={setSort}
+ cards={visible}
+ onOpenCard={() => {}}
+ loading={false}
+ error={null}
+ totalCount={cards.length}
+ onCreate={() => {}}
+ onImport={() => {}}
+ onBrowseCatalog={() => setTab("catalog")}
+ onScan={() => {}}
+ scanPending={false}
+ scanStatus={null}
+ />
+ );
+}
+
+const meta: Meta<typeof DiscoveryGridHarness> = {
+ title: "Skills Store/Discovery grid",
+ component: DiscoveryGridHarness,
+ parameters: { layout: "fullscreen" },
+};
+
+export default meta;
+
+type Story = StoryObj<typeof DiscoveryGridHarness>;
+
+export const AllSkills: Story = { args: { initialTab: "all" } };
+export const InstalledTab: Story = { args: { initialTab: "installed" } };
+export const BundledRequiredTab: Story = { args: { initialTab: "bundled" } };
+export const EmptyLibrary: Story = { args: { initialTab: "all", cards: [] } };