Skip to content

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

Skill Studio: three-pane skill IDE with sandboxed test runs (#9241)

Dottab13eb5b2b5cc
diff --git a/packages/db/src/migrations/0137_skill_studio_server_foundation.sql b/packages/db/src/migrations/0137_skill_studio_server_foundation.sql
new file mode 100644
index 0000000000..49d85b3cbd
--- /dev/null
+++ b/packages/db/src/migrations/0137_skill_studio_server_foundation.sql
@@ -0,0 +1,76 @@
+ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "harness_kind" text;--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "issues_company_harness_kind_idx" ON "issues" USING btree ("company_id","harness_kind");--> statement-breakpoint
+CREATE TABLE IF NOT EXISTS "company_skill_test_inputs" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "company_id" uuid NOT NULL,
+ "skill_id" uuid NOT NULL,
+ "name" text NOT NULL,
+ "content" text NOT NULL,
+ "created_by" text,
+ "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
+CREATE TABLE IF NOT EXISTS "company_skill_test_runs" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "company_id" uuid NOT NULL,
+ "skill_id" uuid NOT NULL,
+ "input_id" uuid,
+ "input_snapshot" text NOT NULL,
+ "skill_version_id" uuid NOT NULL,
+ "agent_id" uuid NOT NULL,
+ "agent_config_snapshot" jsonb DEFAULT '{}'::jsonb NOT NULL,
+ "issue_id" uuid NOT NULL,
+ "status" text DEFAULT 'queued' NOT NULL,
+ "output_document_key" text DEFAULT 'output' NOT NULL,
+ "output_snapshot" text DEFAULT '' NOT NULL,
+ "error" text,
+ "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_skill_test_inputs" ADD CONSTRAINT "company_skill_test_inputs_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_test_inputs" ADD CONSTRAINT "company_skill_test_inputs_skill_id_company_skills_id_fk" FOREIGN KEY ("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_test_runs" ADD CONSTRAINT "company_skill_test_runs_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_test_runs" ADD CONSTRAINT "company_skill_test_runs_skill_id_company_skills_id_fk" FOREIGN KEY ("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_test_runs" ADD CONSTRAINT "company_skill_test_runs_input_id_company_skill_test_inputs_id_fk" FOREIGN KEY ("input_id") REFERENCES "public"."company_skill_test_inputs"("id") ON DELETE set null ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_test_runs" ADD CONSTRAINT "company_skill_test_runs_skill_version_id_company_skill_versions_id_fk" FOREIGN KEY ("skill_version_id") REFERENCES "public"."company_skill_versions"("id") ON DELETE restrict ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_test_runs" ADD CONSTRAINT "company_skill_test_runs_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE restrict ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "company_skill_test_runs" ADD CONSTRAINT "company_skill_test_runs_issue_id_issues_id_fk" FOREIGN KEY ("issue_id") REFERENCES "public"."issues"("id") ON DELETE restrict ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skill_test_inputs_company_skill_name_idx" ON "company_skill_test_inputs" USING btree ("company_id","skill_id","name");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skill_test_inputs_company_skill_active_idx" ON "company_skill_test_inputs" USING btree ("company_id","skill_id","deleted_at");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skill_test_runs_company_skill_created_idx" ON "company_skill_test_runs" USING btree ("company_id","skill_id","created_at");--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS "company_skill_test_runs_company_issue_idx" ON "company_skill_test_runs" USING btree ("company_id","issue_id");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skill_test_runs_company_input_created_idx" ON "company_skill_test_runs" USING btree ("company_id","input_id","created_at");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skill_test_runs_company_status_idx" ON "company_skill_test_runs" USING btree ("company_id","status");
diff --git a/packages/db/src/migrations/0138_skill_studio_run_retention.sql b/packages/db/src/migrations/0138_skill_studio_run_retention.sql
new file mode 100644
index 0000000000..3abc9ad741
--- /dev/null
+++ b/packages/db/src/migrations/0138_skill_studio_run_retention.sql
@@ -0,0 +1,5 @@
+ALTER TABLE "company_skill_test_runs" ADD COLUMN IF NOT EXISTS "deleted_at" timestamp with time zone;--> statement-breakpoint
+ALTER TABLE "company_skill_test_runs" ADD COLUMN IF NOT EXISTS "superseded_at" timestamp with time zone;--> statement-breakpoint
+ALTER TABLE "company_skill_test_runs" ADD COLUMN IF NOT EXISTS "harness_issue_expires_at" timestamp with time zone;--> statement-breakpoint
+ALTER TABLE "company_skill_test_runs" ADD COLUMN IF NOT EXISTS "harness_issue_deleted_at" timestamp with time zone;--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "company_skill_test_runs_company_harness_expires_idx" ON "company_skill_test_runs" USING btree ("company_id","harness_issue_expires_at");
diff --git a/packages/db/src/migrations/0139_skill_studio_run_templates.sql b/packages/db/src/migrations/0139_skill_studio_run_templates.sql
new file mode 100644
index 0000000000..069a99d36c
--- /dev/null
+++ b/packages/db/src/migrations/0139_skill_studio_run_templates.sql
@@ -0,0 +1,44 @@
+CREATE TABLE IF NOT EXISTS "company_skill_test_run_templates" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "company_id" uuid NOT NULL,
+ "name" text NOT NULL,
+ "description" text,
+ "body" text NOT NULL,
+ "created_by_agent_id" uuid,
+ "created_by_user_id" text,
+ "updated_by_agent_id" uuid,
+ "updated_by_user_id" text,
+ "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_skill_test_run_templates" ADD CONSTRAINT "company_skill_test_run_templates_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_test_run_templates" ADD CONSTRAINT "company_skill_test_run_templates_created_by_agent_id_agents_id_fk" FOREIGN KEY ("created_by_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_skill_test_run_templates" ADD CONSTRAINT "company_skill_test_run_templates_updated_by_agent_id_agents_id_fk" FOREIGN KEY ("updated_by_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_skill_test_run_templates_company_active_idx" ON "company_skill_test_run_templates" USING btree ("company_id","deleted_at","name");
+--> statement-breakpoint
+ALTER TABLE "company_skill_test_runs" ADD COLUMN IF NOT EXISTS "template_id" text;
+--> statement-breakpoint
+ALTER TABLE "company_skill_test_runs" ADD COLUMN IF NOT EXISTS "template_name" text;
+--> statement-breakpoint
+ALTER TABLE "company_skill_test_runs" ADD COLUMN IF NOT EXISTS "template_body" text;
+--> statement-breakpoint
+ALTER TABLE "company_skill_test_runs" ADD COLUMN IF NOT EXISTS "rendered_template_body" text;
+--> statement-breakpoint
+ALTER TABLE "company_skill_test_runs" ADD COLUMN IF NOT EXISTS "harness_issue_description" text DEFAULT '' NOT NULL;
diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json
index 8269c18347..1526989ee3 100644
--- a/packages/db/src/migrations/meta/_journal.json
+++ b/packages/db/src/migrations/meta/_journal.json
@@ -946,6 +946,27 @@
"when": 1783555200000,
"tag": "0136_acpx_default_engine_migration",
"breakpoints": true
+ },
+ {
+ "idx": 137,
+ "version": "7",
+ "when": 1783555201000,
+ "tag": "0137_skill_studio_server_foundation",
+ "breakpoints": true
+ },
+ {
+ "idx": 138,
+ "version": "7",
+ "when": 1783555202000,
+ "tag": "0138_skill_studio_run_retention",
+ "breakpoints": true
+ },
+ {
+ "idx": 139,
+ "version": "7",
+ "when": 1783555203000,
+ "tag": "0139_skill_studio_run_templates",
+ "breakpoints": true
}
]
}
diff --git a/packages/db/src/schema/company_skills.ts b/packages/db/src/schema/company_skills.ts
index abb1d2b6b9..7e6ad7d1d5 100644
--- a/packages/db/src/schema/company_skills.ts
+++ b/packages/db/src/schema/company_skills.ts
@@ -12,6 +12,7 @@ import {
import type { CompanySkillFileInventoryEntry, CompanySkillSharingScope } from "@paperclipai/shared";
import { agents } from "./agents.js";
import { companies } from "./companies.js";
+import { issues } from "./issues.js";
export const companySkills = pgTable(
"company_skills",
@@ -131,3 +132,103 @@ export const companySkillComments = pgTable(
parentIdx: index("company_skill_comments_parent_idx").on(table.parentCommentId),
}),
);
+
+export const companySkillTestInputs = pgTable(
+ "company_skill_test_inputs",
+ {
+ id: uuid("id").primaryKey().defaultRandom(),
+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
+ skillId: uuid("skill_id").notNull().references(() => companySkills.id, { onDelete: "cascade" }),
+ name: text("name").notNull(),
+ content: text("content").notNull(),
+ createdBy: text("created_by"),
+ deletedAt: timestamp("deleted_at", { withTimezone: true }),
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
+ },
+ (table) => ({
+ companySkillNameIdx: index("company_skill_test_inputs_company_skill_name_idx").on(
+ table.companyId,
+ table.skillId,
+ table.name,
+ ),
+ companySkillActiveIdx: index("company_skill_test_inputs_company_skill_active_idx").on(
+ table.companyId,
+ table.skillId,
+ table.deletedAt,
+ ),
+ }),
+);
+
+export const companySkillTestRunTemplates = pgTable(
+ "company_skill_test_run_templates",
+ {
+ id: uuid("id").primaryKey().defaultRandom(),
+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
+ name: text("name").notNull(),
+ description: text("description"),
+ body: text("body").notNull(),
+ createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
+ createdByUserId: text("created_by_user_id"),
+ updatedByAgentId: uuid("updated_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
+ updatedByUserId: text("updated_by_user_id"),
+ deletedAt: timestamp("deleted_at", { withTimezone: true }),
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
+ },
+ (table) => ({
+ companyActiveIdx: index("company_skill_test_run_templates_company_active_idx").on(
+ table.companyId,
+ table.deletedAt,
+ table.name,
+ ),
+ }),
+);
+
+export const companySkillTestRuns = pgTable(
+ "company_skill_test_runs",
+ {
+ id: uuid("id").primaryKey().defaultRandom(),
+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
+ skillId: uuid("skill_id").notNull().references(() => companySkills.id, { onDelete: "cascade" }),
+ inputId: uuid("input_id").references(() => companySkillTestInputs.id, { onDelete: "set null" }),
+ inputSnapshot: text("input_snapshot").notNull(),
+ skillVersionId: uuid("skill_version_id").notNull().references(() => companySkillVersions.id, { onDelete: "restrict" }),
+ agentId: uuid("agent_id").notNull().references(() => agents.id, { onDelete: "restrict" }),
+ agentConfigSnapshot: jsonb("agent_config_snapshot").$type<Record<string, unknown>>().notNull().default({}),
+ issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "restrict" }),
+ templateId: text("template_id"),
+ templateName: text("template_name"),
+ templateBody: text("template_body"),
+ renderedTemplateBody: text("rendered_template_body"),
+ harnessIssueDescription: text("harness_issue_description").notNull().default(""),
+ status: text("status").notNull().default("queued"),
+ outputDocumentKey: text("output_document_key").notNull().default("output"),
+ outputSnapshot: text("output_snapshot").notNull().default(""),
+ error: text("error"),
+ deletedAt: timestamp("deleted_at", { withTimezone: true }),
+ supersededAt: timestamp("superseded_at", { withTimezone: true }),
+ harnessIssueExpiresAt: timestamp("harness_issue_expires_at", { withTimezone: true }),
+ harnessIssueDeletedAt: timestamp("harness_issue_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_test_runs_company_skill_created_idx").on(
+ table.companyId,
+ table.skillId,
+ table.createdAt,
+ ),
+ companyIssueIdx: uniqueIndex("company_skill_test_runs_company_issue_idx").on(table.companyId, table.issueId),
+ companyInputCreatedIdx: index("company_skill_test_runs_company_input_created_idx").on(
+ table.companyId,
+ table.inputId,
+ table.createdAt,
+ ),
+ companyStatusIdx: index("company_skill_test_runs_company_status_idx").on(table.companyId, table.status),
+ companyHarnessIssueExpiresIdx: index("company_skill_test_runs_company_harness_expires_idx").on(
+ table.companyId,
+ table.harnessIssueExpiresAt,
+ ),
+ }),
+);
diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts
index 6d418922cc..7d1180376c 100644
--- a/packages/db/src/schema/index.ts
+++ b/packages/db/src/schema/index.ts
@@ -90,7 +90,15 @@ export { companySecretVersions } from "./company_secret_versions.js";
export { companySecretBindings } from "./company_secret_bindings.js";
export { userSecretDeclarations } from "./user_secret_declarations.js";
export { secretAccessEvents } from "./secret_access_events.js";
-export { companySkills, companySkillVersions, companySkillStars, companySkillComments } from "./company_skills.js";
+export {
+ companySkills,
+ companySkillVersions,
+ companySkillStars,
+ companySkillComments,
+ companySkillTestInputs,
+ companySkillTestRunTemplates,
+ companySkillTestRuns,
+} 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/db/src/schema/issues.ts b/packages/db/src/schema/issues.ts
index 18164184f4..f70957efab 100644
--- a/packages/db/src/schema/issues.ts
+++ b/packages/db/src/schema/issues.ts
@@ -32,6 +32,7 @@ export const issues = pgTable(
description: text("description"),
status: text("status").notNull().default("backlog"),
workMode: text("work_mode").notNull().default("standard"),
+ harnessKind: text("harness_kind"),
priority: text("priority").notNull().default("medium"),
assigneeAgentId: uuid("assignee_agent_id").references(() => agents.id),
assigneeUserId: text("assignee_user_id"),
@@ -73,6 +74,7 @@ export const issues = pgTable(
},
(table) => ({
companyStatusIdx: index("issues_company_status_idx").on(table.companyId, table.status),
+ companyHarnessKindIdx: index("issues_company_harness_kind_idx").on(table.companyId, table.harnessKind),
assigneeStatusIdx: index("issues_company_assignee_status_idx").on(
table.companyId,
table.assigneeAgentId,
diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts
index f326328dbd..aab701a670 100644
--- a/packages/shared/src/constants.ts
+++ b/packages/shared/src/constants.ts
@@ -212,8 +212,10 @@ export const INBOX_MINE_ISSUE_STATUS_FILTER = INBOX_MINE_ISSUE_STATUSES.join(","
export const ISSUE_PRIORITIES = ["critical", "high", "medium", "low"] as const;
export type IssuePriority = (typeof ISSUE_PRIORITIES)[number];
-export const ISSUE_WORK_MODES = ["standard", "ask", "planning"] as const;
+export const ISSUE_WORK_MODES = ["standard", "ask", "planning", "skill_test"] as const;
export type IssueWorkMode = (typeof ISSUE_WORK_MODES)[number];
+export const ISSUE_HARNESS_KINDS = ["skill_test"] as const;
+export type IssueHarnessKind = (typeof ISSUE_HARNESS_KINDS)[number];
export const MAX_ISSUE_REQUEST_DEPTH = 1024;
export const ISSUE_COMMENT_AUTHOR_TYPES = ["user", "agent", "system"] as const;
diff --git a/packages/shared/src/frontmatter.test.ts b/packages/shared/src/frontmatter.test.ts
index fa5dda0ae6..ee9e36feda 100644
--- a/packages/shared/src/frontmatter.test.ts
+++ b/packages/shared/src/frontmatter.test.ts
@@ -1,5 +1,27 @@
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
-import { parseFrontmatterMarkdown } from "./frontmatter.js";
+import {
+ analyzeFrontmatterBlock,
+ detectFrontmatterRoundTripIssues,
+ getSkillFrontmatterUnknownKeys,
+ joinFrontmatterBlock,
+ parseFrontmatterFields,
+ parseFrontmatterMarkdown,
+ skillFrontmatterSchema,
+ splitFrontmatterBlock,
+ stringifyFrontmatter,
+} from "./frontmatter.js";
+
+const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
+const skillMarkdownSearchRoots = [
+ "packages/skills-catalog/catalog",
+ "packages/teams-catalog/catalog",
+ "packages/adapters/hermes/skills",
+ "packages/plugins/plugin-llm-wiki/skills",
+ "skills",
+];
describe("parseFrontmatterMarkdown", () => {
it("parses folded and literal YAML block scalars", () => {
@@ -99,3 +121,225 @@ describe("parseFrontmatterMarkdown", () => {
expect(parsed.frontmatter.version).toBe("1.");
});
});
+
+describe("splitFrontmatterBlock", () => {
+ it("splits every bundled skill markdown file without losing bytes", () => {
+ const skillMarkdownFiles = collectSkillMarkdownFiles();
+
+ expect(skillMarkdownFiles.length).toBeGreaterThan(0);
+ for (const filePath of skillMarkdownFiles) {
+ const raw = fs.readFileSync(filePath, "utf8");
+ const split = splitFrontmatterBlock(raw);
+ const joined = split.hasFrontmatter
+ ? `---\n${split.frontmatterText}\n---\n${split.body}`
+ : split.body;
+
+ expect(joined, path.relative(repoRoot, filePath)).toBe(raw);
+ }
+ });
+
+ it("leaves files without frontmatter untouched", () => {
+ const raw = "Body starts immediately.\n\n---\nThis is not frontmatter.\n";
+ const split = splitFrontmatterBlock(raw);
+
+ expect(split).toEqual({
+ frontmatterText: "",
+ body: raw,
+ hasFrontmatter: false,
+ });
+ });
+
+ it("treats an empty opening block as frontmatter", () => {
+ const raw = "---\n---\nBody\n";
+
+ expect(splitFrontmatterBlock(raw)).toEqual({
+ frontmatterText: "",
+ body: "Body\n",
+ hasFrontmatter: true,
+ });
+ });
+});
+
+describe("stringifyFrontmatter", () => {
+ it.each([
+ {
+ label: "nested metadata",
+ value: {
+ name: "demo-skill",
+ description: "Demo skill",
+ metadata: {
+ source: {
+ kind: "github-dir",
+ repo: "paperclipai/paperclip",
+ path: "skills/paperclip",
+ },
+ },
+ },
+ },
+ {
+ label: "arrays",
+ value: {
+ name: "tool-skill",
+ description: "Tool skill",
+ "allowed-tools": ["Read", "Write", "Bash"],
+ tags: ["skills", "frontmatter"],
+ },
+ },
+ {
+ label: "block scalars",
+ value: {
+ name: "block-skill",
+ description: "First line\nsecond line\n\nThird paragraph\n",
+ metadata: {
+ notes: "Keep\nall\nline breaks",
+ },
+ },
+ },
+ ])("serializes parser-compatible YAML for $label", ({ value }) => {
+ const first = parseFrontmatterMarkdown(`---\n${stringifyFrontmatter(value)}\n---\n`).frontmatter;
+ const second = parseFrontmatterMarkdown(`---\n${stringifyFrontmatter(first)}\n---\n`).frontmatter;
+
+ expect(second).toEqual(first);
+ });
+});
+
+describe("skillFrontmatterSchema", () => {
+ it("validates core skill frontmatter fields while allowing unknown keys", () => {
+ const parsed = skillFrontmatterSchema.parse({
+ name: "demo-skill",
+ description: "A demo skill.",
+ "allowed-tools": ["Read", "Write"],
+ metadata: { nested: { enabled: true } },
+ tags: ["demo"],
+ });
+
+ expect(parsed.tags).toEqual(["demo"]);
+ expect(getSkillFrontmatterUnknownKeys(parsed)).toEqual(["tags"]);
+ });
+
+ it("rejects non-slug skill names", () => {
+ expect(() => skillFrontmatterSchema.parse({
+ name: "Demo Skill",
+ description: "A demo skill.",
+ })).toThrow();
+ });
+});
+
+describe("detectFrontmatterRoundTripIssues", () => {
+ it("reports YAML constructs that fields mode cannot preserve", () => {
+ const issues = detectFrontmatterRoundTripIssues([
+ "# leading comment",
+ "\"quoted-key\": value",
+ "base: &base",
+ "copy: *base",
+ ].join("\n"));
+
+ expect(issues.map((issue) => issue.kind)).toEqual([
+ "comment",
+ "quoted_key",
+ "anchor",
+ "alias",
+ ]);
+ });
+});
+
+describe("joinFrontmatterBlock", () => {
+ it("is the exact inverse of splitFrontmatterBlock (byte-identity round-trip)", () => {
+ const samples = [
+ "---\nname: reflection-coach\ndescription: A coach\n---\n# Body\n\nHello\n",
+ "---\nname: x\n---\nno trailing newline",
+ "---\nname: x\n---\n", // empty body
+ "---\ndescription: >\n folded\n text\n---\nBody with comment: value\n",
+ "# just markdown, no frontmatter\n",
+ "---\nunterminated frontmatter\nstill body",
+ "---\nmetadata:\n author: Paperclip\n # comment stays\n---\nbody\n",
+ ];
+ for (const raw of samples) {
+ expect(joinFrontmatterBlock(splitFrontmatterBlock(raw))).toBe(raw);
+ }
+ });
+
+ it("returns the body untouched when there is no frontmatter", () => {
+ expect(
+ joinFrontmatterBlock({ frontmatterText: "", body: "just body", hasFrontmatter: false }),
+ ).toBe("just body");
+ });
+});
+
+describe("parseFrontmatterFields", () => {
+ it("parses the raw block text into an object and is lenient on garbage", () => {
+ expect(parseFrontmatterFields("name: foo\ndescription: bar")).toEqual({
+ name: "foo",
+ description: "bar",
+ });
+ expect(parseFrontmatterFields("")).toEqual({});
+ expect(parseFrontmatterFields("# only a comment")).toEqual({});
+ });
+});
+
+describe("analyzeFrontmatterBlock", () => {
+ it("marks a simple inline block as round-trippable", () => {
+ const result = analyzeFrontmatterBlock("name: reflection-coach\ndescription: A coach");
+ expect(result.canRoundTrip).toBe(true);
+ expect(result.issues).toEqual([]);
+ expect(result.parsed).toEqual({ name: "reflection-coach", description: "A coach" });
+ });
+
+ it("marks a block with allowed-tools and metadata as round-trippable", () => {
+ const raw = [
+ "name: coach",
+ "description: A coach",
+ "allowed-tools:",
+ " - Read",
+ " - Grep",
+ "metadata:",
+ " author: Paperclip",
+ " version: 2",
+ ].join("\n");
+ const result = analyzeFrontmatterBlock(raw);
+ expect(result.canRoundTrip).toBe(true);
+ expect(result.parsed["allowed-tools"]).toEqual(["Read", "Grep"]);
+ });
+
+ it("refuses fields mode when comments are present (would be dropped)", () => {
+ const result = analyzeFrontmatterBlock("name: coach # inline note\ndescription: x");
+ expect(result.canRoundTrip).toBe(false);
+ expect(result.issues.some((issue) => issue.kind === "comment")).toBe(true);
+ });
+
+ it("refuses fields mode for folded scalars the serializer cannot reproduce", () => {
+ const raw = ["description: >", " first line", " second line"].join("\n");
+ const result = analyzeFrontmatterBlock(raw);
+ // No detector "issue", but re-serialization is not byte-identical, so it is
+ // still not round-trippable — the strict serialize-back gate catches it.
+ expect(result.canRoundTrip).toBe(false);
+ });
+
+ it("treats an empty block as round-trippable", () => {
+ const result = analyzeFrontmatterBlock("");
+ expect(result.canRoundTrip).toBe(true);
+ expect(result.parsed).toEqual({});
+ });
+});
+
+function collectSkillMarkdownFiles() {
+ return skillMarkdownSearchRoots.flatMap((relativeRoot) => {
+ const absoluteRoot = path.join(repoRoot, relativeRoot);
+ return fs.existsSync(absoluteRoot) ? collectSkillMarkdownFilesUnder(absoluteRoot) : [];
+ }).sort();
+}
+
+function collectSkillMarkdownFilesUnder(root: string): string[] {
+ const files: string[] = [];
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
+ const absolutePath = path.join(root, entry.name);
+ if (entry.isDirectory()) {
+ files.push(...collectSkillMarkdownFilesUnder(absolutePath));
+ continue;
+ }
+ if (entry.isFile() && entry.name === "SKILL.md") {
+ files.push(absolutePath);
+ }
+ }
+ return files;
+}
diff --git a/packages/shared/src/frontmatter.ts b/packages/shared/src/frontmatter.ts
index 610bd1d57a..4ee9c9b9d7 100644
--- a/packages/shared/src/frontmatter.ts
+++ b/packages/shared/src/frontmatter.ts
@@ -1,9 +1,67 @@
+import { z } from "zod";
+
export interface MarkdownDoc {
frontmatter: Record<string, unknown>;
body: string;
hasFrontmatter: boolean;
}
+export interface FrontmatterBlock {
+ frontmatterText: string;
+ body: string;
+ hasFrontmatter: boolean;
+}
+
+export type FrontmatterRoundTripIssueKind =
+ | "anchor"
+ | "alias"
+ | "comment"
+ | "quoted_key"
+ | "tag";
+
+export interface FrontmatterRoundTripIssue {
+ kind: FrontmatterRoundTripIssueKind;
+ line: number;
+ column: number;
+ message: string;
+}
+
+const SKILL_FRONTMATTER_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+const SUPPORTED_FRONTMATTER_KEY_RE = /^[A-Za-z0-9_. -]+$/;
+
+type SerializableFrontmatterValue =
+ | null
+ | string
+ | number
+ | boolean
+ | SerializableFrontmatterValue[]
+ | { [key: string]: SerializableFrontmatterValue };
+
+const skillMetadataValueSchema: z.ZodType<unknown> = z.lazy(() =>
+ z.union([
+ z.string(),
+ z.number(),
+ z.boolean(),
+ z.null(),
+ z.array(skillMetadataValueSchema),
+ z.record(skillMetadataValueSchema),
+ ])
+);
+
+export const skillFrontmatterSchema = z.object({
+ name: z.string().regex(SKILL_FRONTMATTER_SLUG_RE, "Expected a lowercase URL slug."),
+ description: z.string().min(1),
+ "allowed-tools": z.array(z.string()).optional(),
+ metadata: z.record(skillMetadataValueSchema).optional(),
+}).passthrough();
+
+export const skillFrontmatterKnownKeys = [
+ "name",
+ "description",
+ "allowed-tools",
+ "metadata",
+] as const;
+
export function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -31,6 +89,160 @@ export function asStringArray(value: unknown): string[] | null {
return out;
}
+export function splitFrontmatterBlock(raw: string): FrontmatterBlock {
+ if (!raw.startsWith("---\n")) {
+ return { frontmatterText: "", body: raw, hasFrontmatter: false };
+ }
+
+ const closing = raw.indexOf("\n---\n", 3);
+ if (closing < 0) {
+ return { frontmatterText: "", body: raw, hasFrontmatter: false };
+ }
+
+ return {
+ frontmatterText: raw.slice(4, closing),
+ body: raw.slice(closing + 5),
+ hasFrontmatter: true,
+ };
+}
+
+export function stringifyFrontmatter(value: Record<string, unknown>): string {
+ return stringifyYamlRecord(assertSerializableRecord(value), 0).join("\n");
+}
+
+export function getSkillFrontmatterUnknownKeys(value: Record<string, unknown>) {
+ const known = new Set<string>(skillFrontmatterKnownKeys);
+ return Object.keys(value).filter((key) => !known.has(key));
+}
+
+export function detectFrontmatterRoundTripIssues(rawYaml: string): FrontmatterRoundTripIssue[] {
+ const issues: FrontmatterRoundTripIssue[] = [];
+ const lines = rawYaml.split("\n");
+
+ for (let index = 0; index < lines.length; index += 1) {
+ const line = lines[index]!;
+ const contentStart = line.search(/\S/u);
+ if (contentStart < 0) continue;
+
+ const content = line.slice(contentStart);
+ if (content.startsWith("#")) {
+ issues.push({
+ kind: "comment",
+ line: index + 1,
+ column: contentStart + 1,
+ message: "Comments are not preserved by the frontmatter field serializer.",
+ });
+ continue;
+ }
+
+ const inlineComment = findRoundTripPattern(line, /(^|\s)#/u);
+ if (inlineComment >= 0) {
+ issues.push({
+ kind: "comment",
+ line: index + 1,
+ column: inlineComment + 1,
+ message: "Inline comments are not preserved by the frontmatter field serializer.",
+ });
+ }
+
+ const quotedKey = /^\s*(?:-\s*)?(["']).+?\1\s*:/u.exec(line);
+ if (quotedKey) {
+ issues.push({
+ kind: "quoted_key",
+ line: index + 1,
+ column: line.indexOf(quotedKey[1]!) + 1,
+ message: "Quoted YAML keys cannot be round-tripped by the frontmatter parser.",
+ });
+ }
+
+ const anchor = findRoundTripPattern(line, /(^|[\s,[{])&[A-Za-z0-9_-]+/u);
+ if (anchor >= 0) {
+ issues.push({
+ kind: "anchor",
+ line: index + 1,
+ column: anchor + 1,
+ message: "YAML anchors cannot be round-tripped by the frontmatter parser.",
+ });
+ }
+
+ const alias = findRoundTripPattern(line, /(^|[\s,[{])\*[A-Za-z0-9_-]+/u);
+ if (alias >= 0) {
+ issues.push({
+ kind: "alias",
+ line: index + 1,
+ column: alias + 1,
+ message: "YAML aliases cannot be round-tripped by the frontmatter parser.",
+ });
+ }
+
+ const tag = findRoundTripPattern(line, /(^|\s)![A-Za-z!][^\s]*/u);
+ if (tag >= 0) {
+ issues.push({
+ kind: "tag",
+ line: index + 1,
+ column: tag + 1,
+ message: "YAML tags cannot be round-tripped by the frontmatter parser.",
+ });
+ }
+ }
+
+ return issues;
+}
+
+/**
+ * Recombine a split block into a full markdown document. This is the exact
+ * inverse of {@link splitFrontmatterBlock}: `join(split(x)) === x` for every
+ * input, so opening a file and saving it untouched is byte-identical. The body
+ * is passed through verbatim — never re-parsed or re-serialized.
+ */
+export function joinFrontmatterBlock(block: FrontmatterBlock): string {
+ if (!block.hasFrontmatter) return block.body;
+ return `---\n${block.frontmatterText}\n---\n${block.body}`;
+}
+
+/**
+ * Parse the raw YAML of a frontmatter block (the text between the `---` fences,
+ * as returned by {@link splitFrontmatterBlock}) into a plain object. Lenient:
+ * unparseable input yields `{}` rather than throwing.
+ */
+export function parseFrontmatterFields(frontmatterText: string): Record<string, unknown> {
+ return parseYamlFrontmatter(frontmatterText);
+}
+
+export interface FrontmatterAnalysis {
+ /** The parsed field object (best-effort; `{}` when nothing parses). */
+ parsed: Record<string, unknown>;
+ /**
+ * True when the field editor is safe to use: the raw YAML both parses and
+ * re-serializes byte-for-byte. When false, editing must stay in raw-YAML mode
+ * so bytes the serializer can't reproduce (comments, anchors, folded scalars,
+ * custom ordering, quoting) are never silently rewritten.
+ */
+ canRoundTrip: boolean;
+ /** Structural features that make the block non-round-trippable, if any. */
+ issues: FrontmatterRoundTripIssue[];
+}
+
+/**
+ * Decide whether a frontmatter block can be edited through the structured
+ * field form. Fields mode is only offered when re-serializing the parsed object
+ * reproduces the original block exactly — this is the load-bearing round-trip
+ * safety gate for the Skill Studio FrontmatterPanel (PAP-13145 Option B).
+ */
+export function analyzeFrontmatterBlock(frontmatterText: string): FrontmatterAnalysis {
+ const issues = detectFrontmatterRoundTripIssues(frontmatterText);
+ const parsed = parseYamlFrontmatter(frontmatterText);
+ let canRoundTrip = issues.length === 0;
+ if (canRoundTrip) {
+ try {
+ canRoundTrip = stringifyFrontmatter(parsed) === frontmatterText;
+ } catch {
+ canRoundTrip = false;
+ }
+ }
+ return { parsed, canRoundTrip, issues };
+}
+
export function parseFrontmatterMarkdown(raw: string): MarkdownDoc {
const normalized = raw.replace(/\r\n/g, "\n");
if (!normalized.startsWith("---\n")) {
@@ -51,6 +263,163 @@ export function parseFrontmatterMarkdown(raw: string): MarkdownDoc {
};
}
+function assertSerializableRecord(value: Record<string, unknown>) {
+ const out: Record<string, SerializableFrontmatterValue> = {};
+ for (const [key, entryValue] of Object.entries(value)) {
+ if (entryValue === undefined) continue;
+ out[key] = assertSerializableValue(entryValue);
+ }
+ return out;
+}
+
+function assertSerializableValue(value: unknown): SerializableFrontmatterValue {
+ if (
+ value === null
+ || typeof value === "string"
+ || typeof value === "boolean"
+ ) {
+ return value;
+ }
+ if (typeof value === "number") {
+ if (!Number.isFinite(value)) {
+ throw new TypeError("Frontmatter numbers must be finite.");
+ }
+ return value;
+ }
+ if (Array.isArray(value)) {
+ return value
+ .filter((entry) => entry !== undefined)
+ .map((entry) => assertSerializableValue(entry));
+ }
+ if (isPlainRecord(value)) {
+ return assertSerializableRecord(value);
+ }
+ throw new TypeError(`Unsupported frontmatter value type: ${typeof value}`);
+}
+
+function stringifyYamlRecord(record: Record<string, SerializableFrontmatterValue>, indentLevel: number): string[] {
+ const lines: string[] = [];
+ for (const [key, value] of Object.entries(record)) {
+ assertYamlKey(key);
+ lines.push(...stringifyYamlProperty(key, value, indentLevel));
+ }
+ return lines;
+}
+
+function stringifyYamlProperty(key: string, value: SerializableFrontmatterValue, indentLevel: number): string[] {
+ const indent = " ".repeat(indentLevel);
+ if (Array.isArray(value)) {
+ if (value.length === 0) return [`${indent}${key}: []`];
+ return [`${indent}${key}:`, ...stringifyYamlArray(value, indentLevel + 2)];
+ }
+ if (isSerializableRecord(value)) {
+ const entries = Object.entries(value);
+ if (entries.length === 0) return [`${indent}${key}: {}`];
+ return [`${indent}${key}:`, ...stringifyYamlRecord(value, indentLevel + 2)];
+ }
+ if (typeof value === "string" && value.includes("\n")) {
+ return stringifyBlockScalarProperty(key, value, indentLevel);
+ }
+ return [`${indent}${key}: ${stringifyYamlScalar(value)}`];
+}
+
+function stringifyYamlArray(values: SerializableFrontmatterValue[], indentLevel: number): string[] {
+ const indent = " ".repeat(indentLevel);
+ const lines: string[] = [];
+ for (const value of values) {
+ if (Array.isArray(value)) {
+ if (value.length === 0) {
+ lines.push(`${indent}- []`);
+ } else {
+ lines.push(`${indent}-`);
+ lines.push(...stringifyYamlArray(value, indentLevel + 2));
+ }
+ continue;
+ }
+
+ if (isSerializableRecord(value)) {
+ const entries = Object.entries(value);
+ if (entries.length === 0) {
+ lines.push(`${indent}- {}`);
+ } else {
+ lines.push(`${indent}-`);
+ lines.push(...stringifyYamlRecord(value, indentLevel + 2));
+ }
+ continue;
+ }
+
+ if (typeof value === "string" && value.includes("\n")) {
+ lines.push(...stringifyBlockScalarArrayItem(value, indentLevel));
+ continue;
+ }
+
+ lines.push(`${indent}- ${stringifyYamlScalar(value)}`);
+ }
+ return lines;
+}
+
+function stringifyBlockScalarProperty(key: string, value: string, indentLevel: number) {
+ const indent = " ".repeat(indentLevel);
+ return [
+ `${indent}${key}: ${blockScalarIndicator(value)}`,
+ ...indentBlockScalarValue(value, indentLevel + 2),
+ ];
+}
+
+function stringifyBlockScalarArrayItem(value: string, indentLevel: number) {
+ const indent = " ".repeat(indentLevel);
+ return [
+ `${indent}- ${blockScalarIndicator(value)}`,
+ ...indentBlockScalarValue(value, indentLevel + 2),
+ ];
+}
+
+function blockScalarIndicator(value: string) {
+ if (!value.endsWith("\n")) return "|-";
+ if (value.endsWith("\n\n")) return "|+";
+ return "|";
+}
+
+function indentBlockScalarValue(value: string, indentLevel: number) {
+ const indent = " ".repeat(indentLevel);
+ return value.split("\n").map((line) => `${indent}${line}`);
+}
+
+function stringifyYamlScalar(value: Exclude<SerializableFrontmatterValue, SerializableFrontmatterValue[] | Record<string, SerializableFrontmatterValue>>) {
+ if (value === null) return "null";
+ if (typeof value === "boolean") return value ? "true" : "false";
+ if (typeof value === "number") return String(value);
+ if (isPlainYamlScalar(value)) return value;
+ return JSON.stringify(value);
+}
+
+function isPlainYamlScalar(value: string) {
+ if (value.length === 0) return false;
+ if (value.trim() !== value) return false;
+ if (value === "null" || value === "~" || value === "true" || value === "false") return false;
+ if (value === "[]" || value === "{}") return false;
+ if (/^-?\d+(\.\d+)?$/u.test(value)) return false;
+ if (/["'[\]{}#,>&*!|@`]/u.test(value)) return false;
+ if (value.includes(":")) return false;
+ return true;
+}
+
+function assertYamlKey(key: string) {
+ if (!SUPPORTED_FRONTMATTER_KEY_RE.test(key) || key.includes(":")) {
+ throw new TypeError(`Unsupported frontmatter key: ${key}`);
+ }
+}
+
+function isSerializableRecord(value: SerializableFrontmatterValue): value is Record<string, SerializableFrontmatterValue> {
+ return isPlainRecord(value);
+}
+
+function findRoundTripPattern(line: string, pattern: RegExp) {
+ const match = pattern.exec(line);
+ if (!match) return -1;
+ return match.index + (match[1]?.length ?? 0);
+}
+
function parseYamlFrontmatter(raw: string): Record<string, unknown> {
const prepared = prepareYamlLines(raw);
const firstContentIndex = prepared.findIndex((line) => !line.isBlank && !line.isComment);
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index d888cea22c..9502219f3e 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -80,11 +80,24 @@ export type {
PipelineStageAutomation,
} from "./types/pipeline.js";
export {
+ analyzeFrontmatterBlock,
asBoolean,
asString,
asStringArray,
+ detectFrontmatterRoundTripIssues,
+ getSkillFrontmatterUnknownKeys,
isPlainRecord as isFrontmatterPlainRecord,
+ joinFrontmatterBlock,
+ parseFrontmatterFields,
parseFrontmatterMarkdown,
+ skillFrontmatterKnownKeys,
+ skillFrontmatterSchema,
+ splitFrontmatterBlock,
+ stringifyFrontmatter,
+ type FrontmatterAnalysis,
+ type FrontmatterBlock,
+ type FrontmatterRoundTripIssue,
+ type FrontmatterRoundTripIssueKind,
type MarkdownDoc,
} from "./frontmatter.js";
export {
@@ -128,6 +141,7 @@ export {
INBOX_MINE_ISSUE_STATUS_FILTER,
ISSUE_PRIORITIES,
ISSUE_WORK_MODES,
+ ISSUE_HARNESS_KINDS,
MAX_ISSUE_REQUEST_DEPTH,
ISSUE_COMMENT_AUTHOR_TYPES,
ISSUE_COMMENT_METADATA_ROW_TYPES,
@@ -273,6 +287,7 @@ export {
type IssueStatus,
type IssuePriority,
type IssueWorkMode,
+ type IssueHarnessKind,
type IssueCommentAuthorType,
type IssueCommentMetadataRowType,
type IssueCommentPresentationKind,
@@ -442,6 +457,8 @@ export type {
CompanySkillSourceBadge,
CompanySkillSharingScope,
CompanySkillListSort,
+ CompanySkillListInclude,
+ CompanySkillLastEditor,
CompanySkillFileInventoryEntry,
CompanySkillVersionFileInventoryEntry,
CompanySkill,
@@ -480,6 +497,23 @@ export type {
CompanySkillCreateRequest,
CompanySkillFileDetail,
CompanySkillFileUpdateRequest,
+ CompanySkillFileDeleteRequest,
+ CompanySkillFileDeleteResult,
+ CompanySkillTestRunStatus,
+ CompanySkillTestInput,
+ CompanySkillTestInputCreateRequest,
+ CompanySkillTestInputUpdateRequest,
+ CompanySkillTestRunTemplate,
+ CompanySkillTestRunTemplateCreateRequest,
+ CompanySkillTestRunTemplateUpdateRequest,
+ CompanySkillTestRunTemplateSnapshot,
+ CompanySkillTestRunCostSummary,
+ CompanySkillTestRun,
+ CompanySkillTestRunCreateRequest,
+ CompanySkillTestRunListQuery,
+ CompanySkillTestRunHarnessContentUnavailableReason,
+ CompanySkillTestRunHarnessContent,
+ CompanySkillTestRunDetail,
CatalogSkillKind,
CatalogSkillFileKind,
CatalogSkillFile,
@@ -1139,6 +1173,7 @@ export {
normalizeAgentApiKeyScope,
standardAgentKeyScopeSchema,
taskBridgeAgentKeyScopeSchema,
+ skillTestAgentKeyScopeSchema,
createAgentKeySchema,
agentMineInboxQuerySchema,
wakeAgentSchema,
@@ -1154,6 +1189,7 @@ export {
type UpdateAgentInstructionsPath,
type AgentApiKeyScope,
type TaskBridgeAgentKeyScope,
+ type SkillTestAgentKeyScope,
type CreateAgentKey,
type AgentMineInboxQuery,
type WakeAgent,
@@ -1475,6 +1511,19 @@ export {
companySkillCreateSchema,
companySkillFileDetailSchema,
companySkillFileUpdateSchema,
+ companySkillFileDeleteSchema,
+ companySkillTestRunStatusSchema,
+ companySkillTestInputSchema,
+ companySkillTestInputCreateSchema,
+ companySkillTestInputUpdateSchema,
+ companySkillTestRunTemplateSchema,
+ companySkillTestRunTemplateCreateSchema,
+ companySkillTestRunTemplateUpdateSchema,
+ companySkillTestRunTemplateSnapshotSchema,
+ companySkillTestRunCostSummarySchema,
+ companySkillTestRunSchema,
+ companySkillTestRunCreateSchema,
+ companySkillTestRunListQuerySchema,
catalogSkillKindSchema,
catalogSkillFileSchema,
catalogSkillGitHubSourceSchema,
diff --git a/packages/shared/src/types/company-skill.ts b/packages/shared/src/types/company-skill.ts
index 4573ecc816..c255c1f67f 100644
--- a/packages/shared/src/types/company-skill.ts
+++ b/packages/shared/src/types/company-skill.ts
@@ -1,3 +1,6 @@
+import type { IssueAttachment, IssueDocument } from "./issue.js";
+import type { IssueWorkProduct } from "./work-product.js";
+
export type CompanySkillSourceType = "local_path" | "github" | "url" | "catalog" | "skills_sh";
export type CompanySkillTrustLevel = "markdown_only" | "assets" | "scripts_executables";
@@ -10,6 +13,15 @@ export type CompanySkillSharingScope = "private" | "company" | "public_link";
export type CompanySkillListSort = "alphabetical" | "recent" | "installs" | "stars" | "agents" | "forks";
+export type CompanySkillListInclude = "lastEditor";
+
+export interface CompanySkillLastEditor {
+ kind: "user" | "agent";
+ id: string;
+ name: string | null;
+ imageUrl: string | null;
+}
+
export interface CompanySkillFileInventoryEntry {
path: string;
kind: "skill" | "markdown" | "reference" | "script" | "asset" | "other";
@@ -91,6 +103,7 @@ export interface CompanySkillListItem {
originHash: string | null;
packageName: string | null;
packageVersion: string | null;
+ lastEditor?: CompanySkillLastEditor | null;
}
export interface CompanySkillUsageAgent {
@@ -126,6 +139,7 @@ export interface CompanySkillListQuery {
sort?: CompanySkillListSort;
categories?: string[];
scope?: CompanySkillSharingScope;
+ include?: CompanySkillListInclude[];
}
export interface CompanySkillCategoryCount {
@@ -365,6 +379,187 @@ export interface CompanySkillFileUpdateRequest {
content: string;
}
+export interface CompanySkillFileDeleteRequest {
+ path: string;
+ target: "file" | "folder";
+}
+
+export interface CompanySkillFileDeleteResult {
+ skillId: string;
+ path: string;
+ target: "file" | "folder";
+ deletedPaths: string[];
+}
+
+export type CompanySkillTestRunStatus = "queued" | "running" | "succeeded" | "failed" | "cancelled";
+
+export interface CompanySkillTestInput {
+ id: string;
+ companyId: string;
+ skillId: string;
+ name: string;
+ content: string;
+ createdBy: string | null;
+ deletedAt: Date | null;
+ createdAt: Date;
+ updatedAt: Date;
+}
+
+export interface CompanySkillTestInputCreateRequest {
+ name: string;
+ content: string;
+}
+
+export interface CompanySkillTestInputUpdateRequest {
+ name?: string;
+ content?: string;
+}
+
+export interface CompanySkillTestRunTemplate {
+ id: string;
+ companyId: string;
+ name: string;
+ description: string | null;
+ body: string;
+ builtIn: boolean;
+ createdByAgentId: string | null;
+ createdByUserId: string | null;
+ updatedByAgentId: string | null;
+ updatedByUserId: string | null;
+ deletedAt: Date | null;
+ createdAt: Date;
+ updatedAt: Date;
+}
+
+export interface CompanySkillTestRunTemplateCreateRequest {
+ name: string;
+ description?: string | null;
+ body: string;
+}
+
+export interface CompanySkillTestRunTemplateUpdateRequest {
+ name?: string;
+ description?: string | null;
+ body?: string;
+}
+
+export interface CompanySkillTestRunTemplateSnapshot {
+ templateId: string | null;
+ templateName: string | null;
+ templateBody: string | null;
+}
+
+export interface CompanySkillTestRunCostSummary {
+ costCents: number;
+ inputTokens: number;
+ cachedInputTokens: number;
+ outputTokens: number;
+}
+
+export interface CompanySkillTestRun {
+ id: string;
+ companyId: string;
+ skillId: string;
+ inputId: string | null;
+ inputSnapshot: string;
+ skillVersionId: string;
+ agentId: string;
+ agentConfigSnapshot: Record<string, unknown>;
+ issueId: string;
+ templateId: string | null;
+ templateName: string | null;
+ templateBody: string | null;
+ renderedTemplateBody: string | null;
+ harnessIssueDescription: string;
+ status: CompanySkillTestRunStatus;
+ outputDocumentKey: string;
+ outputSnapshot: string;
+ error: string | null;
+ deletedAt: Date | null;
+ supersededAt: Date | null;
+ harnessIssueExpiresAt: Date | null;
+ harnessIssueDeletedAt: Date | null;
+ createdAt: Date;
+ updatedAt: Date;
+ cost: CompanySkillTestRunCostSummary;
+ taskExpired: boolean;
+}
+
+export interface CompanySkillTestRunCreateRequest {
+ inputId?: string | null;
+ content?: string | null;
+ agentId: string;
+ /**
+ * Omitted uses the built-in default template, null means "No template", and
+ * a string selects a built-in or custom template id.
+ */
+ templateId?: string | null;
+ /**
+ * Re-run can provide the viewed run's template body snapshot so the new run
+ * does not silently pick up later edits to the source template.
+ */
+ templateSnapshot?: CompanySkillTestRunTemplateSnapshot | null;
+ /**
+ * Pin a specific skill version for this run instead of the live head. Used by
+ * Re-run to reproduce the viewed run's `skillVersionId` snapshot.
+ */
+ skillVersionId?: string | null;
+}
+
+export interface CompanySkillTestRunListQuery {
+ inputId?: string;
+}
+
+export type CompanySkillTestRunHarnessContentUnavailableReason = "expired" | "deleted" | "missing";
+
+/**
+ * Rich renderable content hydrated from the run's own hidden harness issue.
+ * When the harness issue has expired or been deleted, `available` is false and
+ * the collections are empty; stored run snapshots (input/output/template)
+ * remain usable on the run itself.
+ */
+export interface CompanySkillTestRunHarnessContent {
+ available: boolean;
+ unavailableReason: CompanySkillTestRunHarnessContentUnavailableReason | null;
+ documents: IssueDocument[];
+ attachments: IssueAttachment[];
+ workProducts: IssueWorkProduct[];
+}
+
+export interface CompanySkillTestRunDetail extends CompanySkillTestRun {
+ skillVersion: CompanySkillVersion;
+ outputBody: string;
+ harnessContent: CompanySkillTestRunHarnessContent;
+ harnessIssue: {
+ id: string;
+ identifier: string | null;
+ title: string;
+ status: string;
+ hiddenAt: Date | null;
+ } | null;
+ documents: Array<{
+ key: string;
+ title: string | null;
+ updatedAt: Date;
+ body: string;
+ }>;
+ interactions: Array<{
+ id: string;
+ kind: string;
+ status: string;
+ title: string;
+ createdAt: Date;
+ updatedAt: Date;
+ }>;
+ artifacts: Array<{
+ id: string;
+ kind: "attachment" | "work_product";
+ title: string;
+ summary: string | null;
+ createdAt: Date;
+ }>;
+}
+
export type CatalogSkillKind = "bundled" | "optional";
export type CatalogSkillFileKind = CompanySkillFileInventoryEntry["kind"];
diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts
index 3ad6dc17ba..246c30f161 100644
--- a/packages/shared/src/types/index.ts
+++ b/packages/shared/src/types/index.ts
@@ -64,6 +64,8 @@ export type {
CompanySkillSourceBadge,
CompanySkillSharingScope,
CompanySkillListSort,
+ CompanySkillListInclude,
+ CompanySkillLastEditor,
CompanySkillFileInventoryEntry,
CompanySkillVersionFileInventoryEntry,
CompanySkill,
@@ -102,6 +104,23 @@ export type {
CompanySkillCreateRequest,
CompanySkillFileDetail,
CompanySkillFileUpdateRequest,
+ CompanySkillFileDeleteRequest,
+ CompanySkillFileDeleteResult,
+ CompanySkillTestRunStatus,
+ CompanySkillTestInput,
+ CompanySkillTestInputCreateRequest,
+ CompanySkillTestInputUpdateRequest,
+ CompanySkillTestRunTemplate,
+ CompanySkillTestRunTemplateCreateRequest,
+ CompanySkillTestRunTemplateUpdateRequest,
+ CompanySkillTestRunTemplateSnapshot,
+ CompanySkillTestRunCostSummary,
+ CompanySkillTestRun,
+ CompanySkillTestRunCreateRequest,
+ CompanySkillTestRunListQuery,
+ CompanySkillTestRunHarnessContentUnavailableReason,
+ CompanySkillTestRunHarnessContent,
+ CompanySkillTestRunDetail,
CatalogSkillKind,
CatalogSkillFileKind,
CatalogSkillFile,
diff --git a/packages/shared/src/types/instance.ts b/packages/shared/src/types/instance.ts
index f03ac7df6f..0a00c8cbe1 100644
--- a/packages/shared/src/types/instance.ts
+++ b/packages/shared/src/types/instance.ts
@@ -60,6 +60,13 @@ export interface InstanceExperimentalSettings {
autoRestartDevServerWhenIdle: boolean;
enableIssueGraphLivenessAutoRecovery: boolean;
enableWorkspaceBranchReconcileForward: boolean;
+ /**
+ * Worktree preview instances (`PAPERCLIP_IN_WORKTREE=true`) suppress the
+ * heartbeat run engine by default so previews never self-execute tasks. When
+ * this is enabled the worktree-instance scheduling suppression is lifted so
+ * runs actually execute inside the preview. Ignored outside a worktree.
+ */
+ enableWorktreeRunExecution: boolean;
issueGraphLivenessAutoRecoveryLookbackHours: number;
}
diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts
index 5bc6010b32..5be8c89cd0 100644
--- a/packages/shared/src/types/issue.ts
+++ b/packages/shared/src/types/issue.ts
@@ -13,6 +13,7 @@ import type {
IssueReferenceSourceKind,
IssueExecutionStageType,
IssueExecutionStateStatus,
+ IssueHarnessKind,
IssueOriginKind,
IssuePriority,
IssueRecoveryActionKind,
@@ -146,6 +147,7 @@ export interface AcceptedPlanDecompositionChild {
description?: string | null;
status: IssueStatus;
workMode: IssueWorkMode;
+ harnessKind?: IssueHarnessKind | null;
priority: IssuePriority;
assigneeAgentId?: string | null;
assigneeUserId?: string | null;
diff --git a/packages/shared/src/validators/agent.ts b/packages/shared/src/validators/agent.ts
index 65934b7e6d..5133896310 100644
--- a/packages/shared/src/validators/agent.ts
+++ b/packages/shared/src/validators/agent.ts
@@ -137,13 +137,20 @@ export const standardAgentKeyScopeSchema = z.object({
kind: z.literal("standard"),
}).strict();
+export const skillTestAgentKeyScopeSchema = z.object({
+ kind: z.literal("skill_test"),
+ issueId: z.string().uuid(),
+}).strict();
+
export const agentApiKeyScopeSchema = z.union([
standardAgentKeyScopeSchema,
taskBridgeAgentKeyScopeSchema,
+ skillTestAgentKeyScopeSchema,
]);
export type AgentApiKeyScope = z.infer<typeof agentApiKeyScopeSchema>;
export type TaskBridgeAgentKeyScope = z.infer<typeof taskBridgeAgentKeyScopeSchema>;
+export type SkillTestAgentKeyScope = z.infer<typeof skillTestAgentKeyScopeSchema>;
export function normalizeAgentApiKeyScope(value: unknown): AgentApiKeyScope {
const parsed = agentApiKeyScopeSchema.safeParse(value);
diff --git a/packages/shared/src/validators/company-skill.ts b/packages/shared/src/validators/company-skill.ts
index 793f5671a1..acf7cb4664 100644
--- a/packages/shared/src/validators/company-skill.ts
+++ b/packages/shared/src/validators/company-skill.ts
@@ -6,6 +6,7 @@ export const companySkillCompatibilitySchema = z.enum(["compatible", "unknown",
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 companySkillListIncludeSchema = z.enum(["lastEditor"]);
export const companySkillFileInventoryEntrySchema = z.object({
path: z.string().min(1),
@@ -59,6 +60,12 @@ export const companySkillListItemSchema = companySkillSchema.extend({
originHash: z.string().nullable(),
packageName: z.string().nullable(),
packageVersion: z.string().nullable(),
+ lastEditor: z.object({
+ kind: z.enum(["user", "agent"]),
+ id: z.string().min(1),
+ name: z.string().nullable(),
+ imageUrl: z.string().nullable(),
+ }).nullable().optional(),
});
export const companySkillUsageAgentSchema = z.object({
@@ -98,6 +105,7 @@ export const companySkillListQuerySchema = z.object({
sort: companySkillListSortSchema.optional(),
categories: z.array(z.string().min(1)).optional(),
scope: companySkillSharingScopeSchema.optional(),
+ include: z.array(companySkillListIncludeSchema).optional(),
});
export const companySkillCategoryCountSchema = z.object({
@@ -319,6 +327,132 @@ export const companySkillFileUpdateSchema = z.object({
content: z.string(),
});
+export const companySkillFileDeleteSchema = z.object({
+ path: z.string().min(1),
+ target: z.enum(["file", "folder"]),
+});
+
+export const companySkillTestRunStatusSchema = z.enum(["queued", "running", "succeeded", "failed", "cancelled"]);
+
+export const companySkillTestInputSchema = z.object({
+ id: z.string().uuid(),
+ companyId: z.string().uuid(),
+ skillId: z.string().uuid(),
+ name: z.string().min(1),
+ content: z.string(),
+ createdBy: z.string().nullable(),
+ deletedAt: z.coerce.date().nullable(),
+ createdAt: z.coerce.date(),
+ updatedAt: z.coerce.date(),
+});
+
+export const companySkillTestInputCreateSchema = z.object({
+ name: z.string().trim().min(1),
+ content: z.string().min(1),
+});
+
+export const companySkillTestInputUpdateSchema = z.object({
+ name: z.string().trim().min(1).optional(),
+ content: z.string().min(1).optional(),
+}).refine((value) => value.name !== undefined || value.content !== undefined, {
+ message: "At least one field is required",
+});
+
+export const companySkillTestRunTemplateSchema = z.object({
+ id: z.string().min(1),
+ companyId: z.string().uuid(),
+ name: z.string().min(1),
+ description: z.string().nullable(),
+ body: z.string().min(1),
+ builtIn: z.boolean(),
+ createdByAgentId: z.string().uuid().nullable(),
+ createdByUserId: z.string().nullable(),
+ updatedByAgentId: z.string().uuid().nullable(),
+ updatedByUserId: z.string().nullable(),
+ deletedAt: z.coerce.date().nullable(),
+ createdAt: z.coerce.date(),
+ updatedAt: z.coerce.date(),
+});
+
+export const companySkillTestRunTemplateCreateSchema = z.object({
+ name: z.string().trim().min(1).max(120),
+ description: z.string().trim().max(500).nullable().optional(),
+ body: z.string().min(1).max(20_000),
+});
+
+export const companySkillTestRunTemplateUpdateSchema = z.object({
+ name: z.string().trim().min(1).max(120).optional(),
+ description: z.string().trim().max(500).nullable().optional(),
+ body: z.string().min(1).max(20_000).optional(),
+}).refine(
+ (value) => value.name !== undefined || value.description !== undefined || value.body !== undefined,
+ { message: "At least one field is required" },
+);
+
+export const companySkillTestRunTemplateSnapshotSchema = z.object({
+ templateId: z.string().min(1).nullable(),
+ templateName: z.string().min(1).nullable(),
+ templateBody: z.string().min(1).max(20_000).nullable(),
+}).refine(
+ (value) =>
+ (value.templateId === null && value.templateName === null && value.templateBody === null)
+ || (value.templateId !== null && value.templateName !== null && value.templateBody !== null),
+ { message: "Template snapshot must be all null or include id, name, and body" },
+);
+
+export const companySkillTestRunCostSummarySchema = z.object({
+ costCents: z.number().int().nonnegative(),
+ inputTokens: z.number().int().nonnegative(),
+ cachedInputTokens: z.number().int().nonnegative(),
+ outputTokens: z.number().int().nonnegative(),
+});
+
+export const companySkillTestRunSchema = z.object({
+ id: z.string().uuid(),
+ companyId: z.string().uuid(),
+ skillId: z.string().uuid(),
+ inputId: z.string().uuid().nullable(),
+ inputSnapshot: z.string(),
+ skillVersionId: z.string().uuid(),
+ agentId: z.string().uuid(),
+ agentConfigSnapshot: z.record(z.string(), z.unknown()),
+ issueId: z.string().uuid(),
+ templateId: z.string().nullable(),
+ templateName: z.string().nullable(),
+ templateBody: z.string().nullable(),
+ renderedTemplateBody: z.string().nullable(),
+ harnessIssueDescription: z.string(),
+ status: companySkillTestRunStatusSchema,
+ outputDocumentKey: z.string().min(1),
+ outputSnapshot: z.string(),
+ error: z.string().nullable(),
+ deletedAt: z.coerce.date().nullable(),
+ supersededAt: z.coerce.date().nullable(),
+ harnessIssueExpiresAt: z.coerce.date().nullable(),
+ harnessIssueDeletedAt: z.coerce.date().nullable(),
+ createdAt: z.coerce.date(),
+ updatedAt: z.coerce.date(),
+ cost: companySkillTestRunCostSummarySchema,
+ taskExpired: z.boolean(),
+});
+
+export const companySkillTestRunCreateSchema = z.object({
+ inputId: z.string().uuid().nullable().optional(),
+ content: z.string().min(1).nullable().optional(),
+ agentId: z.string().uuid(),
+ templateId: z.string().min(1).nullable().optional(),
+ templateSnapshot: companySkillTestRunTemplateSnapshotSchema.nullable().optional(),
+ // Re-run pins the viewed run's skill version instead of the live head, so the
+ // new run reproduces the same snapshots (golden-path step 5).
+ skillVersionId: z.string().uuid().nullable().optional(),
+}).refine((value) => Boolean(value.inputId) || Boolean(value.content?.trim()), {
+ message: "inputId or content is required",
+});
+
+export const companySkillTestRunListQuerySchema = z.object({
+ inputId: z.string().uuid().optional(),
+});
+
export const catalogSkillKindSchema = z.enum(["bundled", "optional"]);
export const catalogSkillFileSchema = z.object({
@@ -397,6 +531,13 @@ 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 CompanySkillFileDelete = z.infer<typeof companySkillFileDeleteSchema>;
+export type CompanySkillTestInputCreate = z.infer<typeof companySkillTestInputCreateSchema>;
+export type CompanySkillTestInputUpdate = z.infer<typeof companySkillTestInputUpdateSchema>;
+export type CompanySkillTestRunTemplateCreate = z.infer<typeof companySkillTestRunTemplateCreateSchema>;
+export type CompanySkillTestRunTemplateUpdate = z.infer<typeof companySkillTestRunTemplateUpdateSchema>;
+export type CompanySkillTestRunCreate = z.infer<typeof companySkillTestRunCreateSchema>;
+export type CompanySkillTestRunListQuery = z.infer<typeof companySkillTestRunListQuerySchema>;
export type CompanySkillVersionCreate = z.infer<typeof companySkillVersionCreateSchema>;
export type CompanySkillCommentCreate = z.infer<typeof companySkillCommentCreateSchema>;
export type CompanySkillCommentUpdate = z.infer<typeof companySkillCommentUpdateSchema>;
diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts
index 1d3d3b4284..b76d6dee12 100644
--- a/packages/shared/src/validators/index.ts
+++ b/packages/shared/src/validators/index.ts
@@ -104,6 +104,7 @@ export {
companySkillSourceBadgeSchema,
companySkillSharingScopeSchema,
companySkillListSortSchema,
+ companySkillListIncludeSchema,
companySkillFileInventoryEntrySchema,
companySkillVersionFileInventoryEntrySchema,
companySkillSchema,
@@ -136,6 +137,19 @@ export {
companySkillCreateSchema,
companySkillFileDetailSchema,
companySkillFileUpdateSchema,
+ companySkillFileDeleteSchema,
+ companySkillTestRunStatusSchema,
+ companySkillTestInputSchema,
+ companySkillTestInputCreateSchema,
+ companySkillTestInputUpdateSchema,
+ companySkillTestRunTemplateSchema,
+ companySkillTestRunTemplateCreateSchema,
+ companySkillTestRunTemplateUpdateSchema,
+ companySkillTestRunTemplateSnapshotSchema,
+ companySkillTestRunCostSummarySchema,
+ companySkillTestRunSchema,
+ companySkillTestRunCreateSchema,
+ companySkillTestRunListQuerySchema,
catalogSkillKindSchema,
catalogSkillFileSchema,
catalogSkillGitHubSourceSchema,
@@ -152,6 +166,12 @@ export {
type CompanySkillProjectScan,
type CompanySkillCreate,
type CompanySkillFileUpdate,
+ type CompanySkillTestInputCreate,
+ type CompanySkillTestInputUpdate,
+ type CompanySkillTestRunTemplateCreate,
+ type CompanySkillTestRunTemplateUpdate,
+ type CompanySkillTestRunCreate,
+ type CompanySkillTestRunListQuery,
type CompanySkillVersionCreate,
type CompanySkillCommentCreate,
type CompanySkillCommentUpdate,
@@ -238,6 +258,7 @@ export {
normalizeAgentApiKeyScope,
standardAgentKeyScopeSchema,
taskBridgeAgentKeyScopeSchema,
+ skillTestAgentKeyScopeSchema,
createAgentKeySchema,
agentMineInboxQuerySchema,
wakeAgentSchema,
@@ -253,6 +274,7 @@ export {
type UpdateAgentInstructionsPath,
type AgentApiKeyScope,
type TaskBridgeAgentKeyScope,
+ type SkillTestAgentKeyScope,
type CreateAgentKey,
type AgentMineInboxQuery,
type WakeAgent,
diff --git a/packages/shared/src/validators/instance.test.ts b/packages/shared/src/validators/instance.test.ts
index d77a00bcfb..34e6174894 100644
--- a/packages/shared/src/validators/instance.test.ts
+++ b/packages/shared/src/validators/instance.test.ts
@@ -23,6 +23,22 @@ describe("instance experimental settings validators", () => {
expect(settings.enableGoalsSidebarLink).toBe(false);
});
+ it("defaults worktree run execution off", () => {
+ const settings = instanceExperimentalSettingsSchema.parse({});
+
+ expect(settings.enableWorktreeRunExecution).toBe(false);
+ });
+
+ it("accepts worktree run execution patches", () => {
+ expect(
+ patchInstanceExperimentalSettingsSchema.parse({
+ enableWorktreeRunExecution: true,
+ }),
+ ).toEqual({
+ enableWorktreeRunExecution: true,
+ });
+ });
+
it("accepts server info debug view patches", () => {
expect(
patchInstanceExperimentalSettingsSchema.parse({
diff --git a/packages/shared/src/validators/instance.ts b/packages/shared/src/validators/instance.ts
index 18ea416118..158edeffe7 100644
--- a/packages/shared/src/validators/instance.ts
+++ b/packages/shared/src/validators/instance.ts
@@ -54,6 +54,7 @@ export const instanceExperimentalSettingsSchema = z.object({
autoRestartDevServerWhenIdle: z.boolean().default(false),
enableIssueGraphLivenessAutoRecovery: z.boolean().default(false),
enableWorkspaceBranchReconcileForward: z.boolean().default(false),
+ enableWorktreeRunExecution: z.boolean().default(false),
issueGraphLivenessAutoRecoveryLookbackHours: z
.number()
.int()
diff --git a/packages/shared/src/validators/issue.test.ts b/packages/shared/src/validators/issue.test.ts
index 8834dcb0bb..f766dd7890 100644
--- a/packages/shared/src/validators/issue.test.ts
+++ b/packages/shared/src/validators/issue.test.ts
@@ -245,12 +245,18 @@ describe("issue validators", () => {
}).status).toBe("backlog");
});
- it("defaults issue work mode to standard and accepts ask and planning", () => {
+ it("defaults issue work mode to standard and accepts ask, planning, and skill_test", () => {
expect(createIssueSchema.parse({ title: "Plan first" }).workMode).toBe("standard");
expect(createIssueSchema.parse({ title: "Ask first", workMode: "ask" }).workMode).toBe("ask");
expect(createIssueSchema.parse({ title: "Plan first", workMode: "planning" }).workMode).toBe("planning");
+ expect(createIssueSchema.parse({
+ title: "Harness test",
+ workMode: "skill_test",
+ harnessKind: "skill_test",
+ })).toMatchObject({ workMode: "skill_test", harnessKind: "skill_test" });
expect(updateIssueSchema.parse({ workMode: "ask" }).workMode).toBe("ask");
expect(updateIssueSchema.parse({ workMode: "planning" }).workMode).toBe("planning");
+ expect(updateIssueSchema.parse({ workMode: "skill_test" }).workMode).toBe("skill_test");
expect(suggestedTaskDraftSchema.parse({
clientKey: "ask-child",
title: "Ask child",
@@ -261,6 +267,11 @@ describe("issue validators", () => {
title: "Plan child",
workMode: "planning",
}).workMode).toBe("planning");
+ expect(suggestedTaskDraftSchema.parse({
+ clientKey: "skill-test-child",
+ title: "Test child",
+ workMode: "skill_test",
+ }).workMode).toBe("skill_test");
});
it("validates blocked inbox attention payloads and requires redacted secret fields", () => {
diff --git a/packages/shared/src/validators/issue.ts b/packages/shared/src/validators/issue.ts
index 449f05ad90..0b94aa8aee 100644
--- a/packages/shared/src/validators/issue.ts
+++ b/packages/shared/src/validators/issue.ts
@@ -12,6 +12,7 @@ import {
ISSUE_COMMENT_METADATA_ROW_TYPES,
ISSUE_COMMENT_PRESENTATION_KINDS,
ISSUE_COMMENT_PRESENTATION_TONES,
+ ISSUE_HARNESS_KINDS,
ISSUE_MONITOR_SCHEDULED_BY,
ISSUE_PRIORITIES,
ISSUE_RECOVERY_ACTION_KINDS,
@@ -384,6 +385,7 @@ const createIssueBaseSchema = z.object({
description: multilineTextSchema.optional().nullable(),
status: z.enum(ISSUE_STATUSES),
workMode: z.enum(ISSUE_WORK_MODES).optional().default("standard"),
+ harnessKind: z.enum(ISSUE_HARNESS_KINDS).optional().nullable(),
priority: z.enum(ISSUE_PRIORITIES).optional().default("medium"),
assigneeAgentId: z.string().uuid().optional().nullable(),
assigneeUserId: z.string().optional().nullable(),
diff --git a/scripts/screenshot-fork-flow.mjs b/scripts/screenshot-fork-flow.mjs
new file mode 100644
index 0000000000..6cea613789
--- /dev/null
+++ b/scripts/screenshot-fork-flow.mjs
@@ -0,0 +1,47 @@
+#!/usr/bin/env node
+// Screenshot the PAP-13112 "Edit a copy" fork-flow stories.
+import fs from "node:fs/promises";
+import path from "node:path";
+import { chromium } from "@playwright/test";
+
+const OUT = process.argv[2] || "screenshots/pap-13112";
+const BASE = "http://localhost:6006/iframe.html";
+await fs.mkdir(path.resolve(OUT), { recursive: true });
+
+const shots = [
+ { id: "skill-studio-editacopy--read-only-banner-cta", name: "01-readonly-banner-cta", w: 560, h: 260 },
+ { id: "skill-studio-editacopy--fork-dialog-agents-switch-on", name: "02-fork-dialog-switch-on", w: 720, h: 640 },
+ { id: "skill-studio-editacopy--fork-dialog-agents-switch-on", name: "03-fork-dialog-switch-off", w: 720, h: 640, toggleOff: true },
+ { id: "skill-studio-editacopy--fork-dialog-no-agents", name: "04-fork-dialog-no-agents", w: 720, h: 560 },
+ { id: "skill-studio-editacopy--fork-dialog-existing-copy", name: "05-fork-dialog-existing-copy", w: 720, h: 700 },
+ { id: "skill-studio-editacopy--forked-skill-header", name: "06-lineage-chip", w: 720, h: 200 },
+ { id: "skill-studio-editacopy--project-scan-source-notice", name: "07-project-scan-notice", w: 620, h: 200 },
+];
+
+const browser = await chromium.launch({
+ headless: true,
+ executablePath: process.env.CHROME_PATH || undefined,
+ args: ["--no-sandbox", "--disable-dev-shm-usage"],
+});
+try {
+ for (const shot of shots) {
+ const ctx = await browser.newContext({
+ viewport: { width: shot.w, height: shot.h },
+ deviceScaleFactor: 2,
+ });
+ const page = await ctx.newPage();
+ await page.goto(`${BASE}?id=${shot.id}&viewMode=story`, { waitUntil: "networkidle" });
+ await page.waitForTimeout(1200);
+ if (shot.toggleOff) {
+ const toggle = page.locator('button[aria-label="Switch these agents to the copy"]');
+ await toggle.click();
+ await page.waitForTimeout(400);
+ }
+ const out = path.join(OUT, `${shot.name}.png`);
+ await page.screenshot({ path: out, fullPage: false });
+ console.log(`Wrote ${out}`);
+ await ctx.close();
+ }
+} finally {
+ await browser.close();
+}
diff --git a/server/src/__tests__/agent-auth-jwt.test.ts b/server/src/__tests__/agent-auth-jwt.test.ts
index c5fe3f8b95..7d809ce3d3 100644
--- a/server/src/__tests__/agent-auth-jwt.test.ts
+++ b/server/src/__tests__/agent-auth-jwt.test.ts
@@ -67,6 +67,18 @@ describe("agent local JWT", () => {
});
});
+ it("round-trips a skill_test run scope", () => {
+ vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
+ const issueId = "11111111-1111-4111-8111-111111111111";
+ const token = createLocalAgentJwt("agent-1", "company-1", "claude_local", "run-1", "user-1", {
+ kind: "skill_test",
+ issueId,
+ });
+
+ const claims = verifyLocalAgentJwt(token!);
+ expect(claims?.key_scope).toEqual({ kind: "skill_test", issueId });
+ });
+
it("returns null when secret is missing", () => {
process.env[secretEnv] = "";
const token = createLocalAgentJwt("agent-1", "company-1", "claude_local", "run-1");
diff --git a/server/src/__tests__/agent-auth-middleware.test.ts b/server/src/__tests__/agent-auth-middleware.test.ts
index 54c4fe150b..ff27e685b7 100644
--- a/server/src/__tests__/agent-auth-middleware.test.ts
+++ b/server/src/__tests__/agent-auth-middleware.test.ts
@@ -197,6 +197,35 @@ describe("agent auth middleware", () => {
});
});
+ it("preserves signed skill_test JWT scope on the request actor", async () => {
+ const companyId = randomUUID();
+ const agentId = randomUUID();
+ const runId = randomUUID();
+ const issueId = randomUUID();
+ const { db } = createDbState({
+ agent: { id: agentId, companyId },
+ run: { id: runId, companyId, agentId, responsibleUserId: "user-claim" },
+ });
+ const token = createLocalAgentJwt(agentId, companyId, "codex_local", runId, "user-claim", {
+ kind: "skill_test",
+ issueId,
+ });
+
+ const res = await request(createApp(db))
+ .get("/actor")
+ .set("Authorization", `Bearer ${token}`)
+ .set("X-Paperclip-Run-Id", runId);
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({
+ type: "agent",
+ agentId,
+ companyId,
+ keyScope: { kind: "skill_test", issueId },
+ source: "agent_jwt",
+ });
+ });
+
it("rejects mismatched run headers for agent JWTs and audits the spoof attempt", async () => {
const companyId = randomUUID();
const agentId = randomUUID();
diff --git a/server/src/__tests__/agent-skills-routes.test.ts b/server/src/__tests__/agent-skills-routes.test.ts
index 323d2ddd1f..e1f02e7170 100644
--- a/server/src/__tests__/agent-skills-routes.test.ts
+++ b/server/src/__tests__/agent-skills-routes.test.ts
@@ -275,11 +275,13 @@ describe.sequential("agent skill routes", () => {
),
);
mockCompanySkillService.resolveRequestedSkillEntries.mockImplementation(
- async (_companyId: string, requested: Array<{ key: string; versionId?: string | null }>) =>
- requested.map((entry) => ({
+ async (_companyId: string, requested: Array<{ key: string; versionId?: string | null }>) => ({
+ resolved: requested.map((entry) => ({
key: entry.key === "paperclip" ? "paperclipai/paperclip/paperclip" : entry.key,
versionId: entry.versionId ?? null,
})),
+ unresolved: [],
+ }),
);
mockAdapter.listSkills.mockResolvedValue({
adapterType: "claude_local",
@@ -493,6 +495,61 @@ describe.sequential("agent skill routes", () => {
);
});
+ it("preserves stale desired keys instead of 422-ing when syncing (PAP-13222)", async () => {
+ mockAgentService.getById.mockResolvedValue(makeAgent("acpx_local"));
+ // The agent already carries a stale desired key that no longer resolves to a
+ // company-library skill. Toggling a resolvable skill must still succeed and
+ // keep the stale key so it stays visible/removable in the UI.
+ mockCompanySkillService.resolveRequestedSkillEntries.mockImplementationOnce(
+ async (
+ _companyId: string,
+ requested: Array<{ key: string; versionId?: string | null }>,
+ options?: { tolerateUnknownReferences?: boolean },
+ ) => {
+ expect(options?.tolerateUnknownReferences).toBe(true);
+ const resolved: Array<{ key: string; versionId: string | null }> = [];
+ const unresolved: string[] = [];
+ for (const entry of requested) {
+ if (entry.key === "stale/removed/skill") {
+ unresolved.push(entry.key);
+ } else {
+ resolved.push({
+ key: entry.key === "paperclip" ? "paperclipai/paperclip/paperclip" : entry.key,
+ versionId: entry.versionId ?? null,
+ });
+ }
+ }
+ return { resolved, unresolved };
+ },
+ );
+
+ const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
+ .post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
+ .send({ desiredSkills: ["paperclip", "stale/removed/skill"] }));
+
+ expect(res.status, JSON.stringify(res.body)).toBe(200);
+ // Stale key preserved in the persisted config alongside the resolved skill.
+ expect(mockAgentService.update).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ adapterConfig: expect.objectContaining({
+ paperclipSkillSync: expect.objectContaining({
+ desiredSkills: ["paperclipai/paperclip/paperclip", "stale/removed/skill"],
+ }),
+ }),
+ }),
+ expect.any(Object),
+ );
+ // Runtime version selection only considers resolvable keys.
+ expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith(
+ "company-1",
+ expect.objectContaining({ versionSelections: expect.any(Map) }),
+ );
+ const versionSelections = mockCompanySkillService.listRuntimeSkillEntries.mock.calls.at(-1)?.[1]
+ ?.versionSelections as Map<string, unknown> | undefined;
+ expect(versionSelections?.has("stale/removed/skill")).toBe(false);
+ });
+
it("skips runtime materialization when listing persistent skill adapters", async () => {
mockAgentService.getById.mockResolvedValue(makeAgent("cursor"));
mockAdapter.listSkills.mockResolvedValue({
diff --git a/server/src/__tests__/authorization-service.test.ts b/server/src/__tests__/authorization-service.test.ts
index de0484939e..213b192e47 100644
--- a/server/src/__tests__/authorization-service.test.ts
+++ b/server/src/__tests__/authorization-service.test.ts
@@ -1521,4 +1521,72 @@ describeEmbeddedPostgres("authorization service", () => {
reason: "deny_scope",
});
});
+
+ it("scopes skill-test keys to their own issue only", async () => {
+ const company = await createCompany(db, "SkillTest");
+ const skillTestAgent = await createAgent(db, company.id);
+ const ownIssue = await createIssue(db, company.id, { assigneeAgentId: skillTestAgent.id });
+ const otherIssue = await createIssue(db, company.id);
+ const actor = {
+ type: "agent" as const,
+ agentId: skillTestAgent.id,
+ companyId: company.id,
+ source: "agent_key" as const,
+ keyScope: {
+ kind: "skill_test" as const,
+ issueId: ownIssue.id,
+ },
+ };
+ const authz = authorizationService(db);
+
+ for (const action of ["issue:read", "issue:comment", "issue:mutate"] as const) {
+ await expect(authz.decide({
+ actor,
+ action,
+ resource: {
+ type: "issue",
+ companyId: company.id,
+ issueId: ownIssue.id,
+ },
+ })).resolves.toMatchObject({
+ allowed: true,
+ });
+ }
+
+ await expect(authz.decide({
+ actor,
+ action: "issue:mutate",
+ resource: {
+ type: "issue",
+ companyId: company.id,
+ issueId: otherIssue.id,
+ },
+ })).resolves.toMatchObject({
+ allowed: false,
+ reason: "deny_scope",
+ });
+
+ await expect(authz.decide({
+ actor,
+ action: "company_scope:read",
+ resource: { type: "company", companyId: company.id },
+ })).resolves.toMatchObject({
+ allowed: false,
+ reason: "deny_scope",
+ });
+
+ await expect(authz.decide({
+ actor,
+ action: "tasks:assign",
+ resource: {
+ type: "issue",
+ companyId: company.id,
+ parentIssueId: ownIssue.id,
+ assigneeAgentId: skillTestAgent.id,
+ },
+ })).resolves.toMatchObject({
+ allowed: false,
+ reason: "deny_scope",
+ });
+ });
});
diff --git a/server/src/__tests__/company-search-service.test.ts b/server/src/__tests__/company-search-service.test.ts
index 940f4c0c92..d4edf955eb 100644
--- a/server/src/__tests__/company-search-service.test.ts
+++ b/server/src/__tests__/company-search-service.test.ts
@@ -267,6 +267,11 @@ describeEmbeddedPostgres("companySearchService", () => {
title: "Hidden needle",
hiddenAt: new Date(),
});
+ await createIssue(companyId, {
+ identifier: "HAR-1",
+ title: "Harness needle",
+ harnessKind: "skill_test",
+ });
await createIssue(otherCompanyId, {
identifier: "OTH-1",
title: "Other company needle",
diff --git a/server/src/__tests__/company-skill-test-runs-service.test.ts b/server/src/__tests__/company-skill-test-runs-service.test.ts
new file mode 100644
index 0000000000..a0948639bd
--- /dev/null
+++ b/server/src/__tests__/company-skill-test-runs-service.test.ts
@@ -0,0 +1,753 @@
+import { randomUUID } from "node:crypto";
+import os from "node:os";
+import path from "node:path";
+import { promises as fs } from "node:fs";
+import { eq } from "drizzle-orm";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import {
+ agents,
+ assets,
+ companies,
+ companySkillTestRunTemplates,
+ companySkillTestRuns,
+ companySkills,
+ createDb,
+ documents,
+ issueAttachments,
+ issueDocuments,
+ issueWorkProducts,
+ issues,
+} from "@paperclipai/db";
+import {
+ getEmbeddedPostgresTestSupport,
+ startEmbeddedPostgresTestDatabase,
+} from "./helpers/embedded-postgres.js";
+import { companySkillService } from "../services/company-skills.js";
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
+
+if (!embeddedPostgresSupport.supported) {
+ console.warn(
+ `Skipping embedded Postgres company skill test run tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
+ );
+}
+
+describeEmbeddedPostgres("companySkillService skill test runs", () => {
+ let db!: ReturnType<typeof createDb>;
+ let svc!: ReturnType<typeof companySkillService>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+ const cleanupDirs = new Set<string>();
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-company-skill-test-runs-");
+ db = createDb(tempDb.connectionString);
+ svc = companySkillService(db);
+ }, 20_000);
+
+ afterEach(async () => {
+ await db.delete(issueAttachments);
+ await db.delete(issueWorkProducts);
+ await db.delete(assets);
+ await db.delete(issueDocuments);
+ await db.delete(documents);
+ await db.delete(companySkillTestRuns);
+ await db.delete(companySkillTestRunTemplates);
+ await db.delete(issues);
+ await db.delete(agents);
+ await db.delete(companySkills);
+ await db.delete(companies);
+ await Promise.all(Array.from(cleanupDirs, (dir) => fs.rm(dir, { recursive: true, force: true })));
+ cleanupDirs.clear();
+ });
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ async function seedSkillAndAgent() {
+ const companyId = randomUUID();
+ const skillId = randomUUID();
+ const agentId = randomUUID();
+ const skillDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-skill-test-run-"));
+ cleanupDirs.add(skillDir);
+ await fs.writeFile(path.join(skillDir, "SKILL.md"), "# Review 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(agents).values({
+ id: agentId,
+ companyId,
+ name: "Tester",
+ role: "engineer",
+ status: "idle",
+ adapterType: "codex_local",
+ adapterConfig: { model: "gpt-5.4" },
+ });
+ await db.insert(companySkills).values({
+ id: skillId,
+ companyId,
+ key: `company/${companyId}/review`,
+ slug: "review",
+ name: "Review Skill",
+ description: null,
+ markdown: "# Review Skill\n",
+ sourceType: "local_path",
+ sourceLocator: skillDir,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ metadata: { sourceKind: "managed_local" },
+ });
+ return { companyId, skillId, agentId };
+ }
+
+ const runDeps = (companyId: string) => ({
+ createHarnessIssue: async (issue: Parameters<Parameters<typeof svc.createTestRun>[4]["createHarnessIssue"]>[0]) => {
+ await db.insert(issues).values({ ...issue, companyId, priority: "medium" });
+ return { id: issue.id };
+ },
+ wakeHarnessIssue: async () => null,
+ retentionDays: 7,
+ });
+
+ it("cleans up the harness issue if persisting the test run fails", async () => {
+ const { companyId, skillId, agentId } = await seedSkillAndAgent();
+ const cleanedIssueIds: string[] = [];
+ let createdIssueId: string | null = null;
+ let wakeCalls = 0;
+
+ await expect(
+ svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "test this skill", agentId },
+ { type: "user", userId: "local-board" },
+ {
+ createHarnessIssue: async (issue) => {
+ createdIssueId = issue.id;
+ await db.insert(issues).values({ ...issue, companyId, priority: "medium" });
+ return { id: issue.id };
+ },
+ wakeHarnessIssue: async () => {
+ wakeCalls += 1;
+ },
+ cleanupHarnessIssue: async (issueId) => {
+ cleanedIssueIds.push(issueId);
+ await db
+ .update(issues)
+ .set({ status: "cancelled", hiddenAt: new Date() })
+ .where(eq(issues.id, issueId));
+ },
+ retentionDays: Number.NaN,
+ },
+ ),
+ ).rejects.toThrow();
+
+ expect(createdIssueId).toBeTruthy();
+ expect(cleanedIssueIds).toEqual([createdIssueId]);
+ expect(wakeCalls).toBe(0);
+ const issue = await db
+ .select({ status: issues.status, hiddenAt: issues.hiddenAt })
+ .from(issues)
+ .where(eq(issues.id, createdIssueId!))
+ .then((rows) => rows[0] ?? null);
+ expect(issue?.status).toBe("cancelled");
+ expect(issue?.hiddenAt).toBeInstanceOf(Date);
+ });
+
+ it("appends the built-in default template while keeping the input snapshot clean", async () => {
+ const { companyId, skillId, agentId } = await seedSkillAndAgent();
+ const run = await svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "test this skill", agentId },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ );
+
+ expect(run.inputSnapshot).toBe("test this skill");
+ expect(run.templateId).toBe("built-in:default-test-template");
+ expect(run.templateName).toBe("Default test template");
+ expect(run.templateBody).toContain("{{skillName}}");
+ expect(run.renderedTemplateBody).toContain("Skills Studio test for `Review Skill`");
+ expect(run.renderedTemplateBody).toContain(`company/${companyId}/review`);
+ expect(run.renderedTemplateBody).toContain("issue document `output`");
+ expect(run.harnessIssueDescription).toBe(`test this skill\n\n---\n\n${run.renderedTemplateBody}`);
+
+ const issue = await db
+ .select({ description: issues.description })
+ .from(issues)
+ .where(eq(issues.id, run.issueId))
+ .then((rows) => rows[0] ?? null);
+ expect(issue?.description).toBe(run.harnessIssueDescription);
+ });
+
+ it("honors No template without weakening the clean run snapshot", async () => {
+ const { companyId, skillId, agentId } = await seedSkillAndAgent();
+ const run = await svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "test this skill", agentId, templateId: null },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ );
+
+ expect(run.inputSnapshot).toBe("test this skill");
+ expect(run.templateId).toBeNull();
+ expect(run.templateName).toBeNull();
+ expect(run.templateBody).toBeNull();
+ expect(run.renderedTemplateBody).toBeNull();
+ expect(run.harnessIssueDescription).toBe("test this skill");
+
+ const issue = await db
+ .select({ description: issues.description })
+ .from(issues)
+ .where(eq(issues.id, run.issueId))
+ .then((rows) => rows[0] ?? null);
+ expect(issue?.description).toBe("test this skill");
+ });
+
+ it("manages custom templates and renders only explicit placeholders", async () => {
+ const { companyId, skillId, agentId } = await seedSkillAndAgent();
+ const template = await svc.createTestRunTemplate(companyId, {
+ name: "Focused smoke",
+ description: "Short run",
+ body: "Run {{skillName}} v{{skillVersion}} for {{runId}} on {{issueId}} into {{outputDocumentKey}}.",
+ }, { type: "user", userId: "local-board" });
+
+ const listed = await svc.listTestRunTemplates(companyId);
+ expect(listed.map((entry) => entry.id)).toEqual(["built-in:default-test-template", template.id]);
+ expect(listed[0]?.builtIn).toBe(true);
+
+ const run = await svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "custom template run", agentId, templateId: template.id },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ );
+ expect(run.templateId).toBe(template.id);
+ expect(run.templateName).toBe("Focused smoke");
+ expect(run.renderedTemplateBody).toContain("Run Review Skill v1");
+ expect(run.renderedTemplateBody).toContain(run.id);
+ expect(run.renderedTemplateBody).toContain(run.issueId);
+ expect(run.renderedTemplateBody).toContain("into output");
+
+ await expect(
+ svc.createTestRunTemplate(companyId, {
+ name: "Bad template",
+ body: "Use {{unknownPlaceholder}}.",
+ }, { type: "user", userId: "local-board" }),
+ ).rejects.toThrow(/unknown template placeholder/i);
+
+ const updated = await svc.updateTestRunTemplate(companyId, template.id, {
+ name: "Focused smoke v2",
+ body: "Use {{skillKey}}.",
+ }, { type: "user", userId: "local-board" });
+ expect(updated?.name).toBe("Focused smoke v2");
+ expect(updated?.body).toBe("Use {{skillKey}}.");
+
+ await expect(
+ svc.updateTestRunTemplate(companyId, "built-in:default-test-template", { name: "Changed" }),
+ ).rejects.toThrow(/read-only/i);
+
+ const deleted = await svc.deleteTestRunTemplate(companyId, template.id);
+ expect(deleted?.deletedAt).toBeInstanceOf(Date);
+ expect((await svc.listTestRunTemplates(companyId)).map((entry) => entry.id)).toEqual([
+ "built-in:default-test-template",
+ ]);
+ });
+
+ it("rejects unknown or cross-company template ids", async () => {
+ const first = await seedSkillAndAgent();
+ const second = await seedSkillAndAgent();
+ const otherTemplate = await svc.createTestRunTemplate(second.companyId, {
+ name: "Other company",
+ body: "Other {{skillName}}.",
+ }, { type: "user", userId: "local-board" });
+
+ await expect(
+ svc.createTestRun(
+ first.companyId,
+ first.skillId,
+ { content: "test", agentId: first.agentId, templateId: randomUUID() },
+ { type: "user", userId: "local-board" },
+ runDeps(first.companyId),
+ ),
+ ).rejects.toThrow(/test run template not found/i);
+
+ await expect(
+ svc.createTestRun(
+ first.companyId,
+ first.skillId,
+ { content: "test", agentId: first.agentId, templateId: otherTemplate.id },
+ { type: "user", userId: "local-board" },
+ runDeps(first.companyId),
+ ),
+ ).rejects.toThrow(/test run template not found/i);
+ });
+
+ it("re-run can use the viewed template body snapshot after source template edits", async () => {
+ const { companyId, skillId, agentId } = await seedSkillAndAgent();
+ const template = await svc.createTestRunTemplate(companyId, {
+ name: "Snapshot me",
+ body: "Original {{skillName}}.",
+ }, { type: "user", userId: "local-board" });
+ const first = await svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "repeatable", agentId, templateId: template.id },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ );
+
+ await svc.updateTestRunTemplate(companyId, template.id, {
+ body: "Edited {{skillName}}.",
+ }, { type: "user", userId: "local-board" });
+
+ const reRun = await svc.createTestRun(
+ companyId,
+ skillId,
+ {
+ content: first.inputSnapshot,
+ agentId: first.agentId,
+ skillVersionId: first.skillVersionId,
+ templateSnapshot: {
+ templateId: first.templateId,
+ templateName: first.templateName,
+ templateBody: first.templateBody,
+ },
+ },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ );
+ expect(reRun.skillVersionId).toBe(first.skillVersionId);
+ expect(reRun.templateId).toBe(template.id);
+ expect(reRun.templateBody).toBe("Original {{skillName}}.");
+ expect(reRun.renderedTemplateBody).toBe("Original Review Skill.");
+ expect(reRun.harnessIssueDescription).toContain("Original Review Skill.");
+ expect(reRun.harnessIssueDescription).not.toContain("Edited Review Skill.");
+ });
+
+ it("only deletes terminal runs and soft-deletes them out of history", async () => {
+ const { companyId, skillId, agentId } = await seedSkillAndAgent();
+ const run = await svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "test this skill", agentId },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ );
+
+ // In-flight run must be cancelled first.
+ await expect(
+ svc.deleteTestRun(companyId, skillId, run.id, { hideHarnessIssue: async () => null }),
+ ).rejects.toThrow(/cancel the run/i);
+
+ await svc.completeTestRunForIssue({ companyId, issueId: run.issueId, outcome: "succeeded" });
+
+ const hidden: string[] = [];
+ const deleted = await svc.deleteTestRun(companyId, skillId, run.id, {
+ hideHarnessIssue: async (issueId) => {
+ hidden.push(issueId);
+ },
+ });
+ expect(deleted?.id).toBe(run.id);
+ expect(deleted?.harnessIssueDeletedAt).toBeInstanceOf(Date);
+ expect(deleted?.taskExpired).toBe(true);
+ expect(hidden).toEqual([run.issueId]);
+
+ // Gone from listings and detail.
+ expect(await svc.listTestRuns(companyId, skillId)).toHaveLength(0);
+ expect(await svc.getTestRunDetail(companyId, skillId, run.id)).toBeNull();
+
+ // Deleting again is a no-op 404 (returns null).
+ expect(
+ await svc.deleteTestRun(companyId, skillId, run.id, { hideHarnessIssue: async () => null }),
+ ).toBeNull();
+ });
+
+ it("re-run pins an explicit skill version instead of the live head", async () => {
+ const { companyId, skillId, agentId } = await seedSkillAndAgent();
+ const first = await svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "first run", agentId },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ );
+ const pinnedVersionId = first.skillVersionId;
+
+ const reRun = await svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "first run", agentId, skillVersionId: pinnedVersionId },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ );
+ expect(reRun.skillVersionId).toBe(pinnedVersionId);
+
+ // A bogus version id is rejected rather than silently falling back to head.
+ await expect(
+ svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "first run", agentId, skillVersionId: randomUUID() },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ ),
+ ).rejects.toThrow(/skill version not found/i);
+ });
+
+ it("ignores superseded test harness issue transitions", async () => {
+ const { companyId, skillId, agentId } = await seedSkillAndAgent();
+ const first = await svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "first run", agentId },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ );
+ const replacement = await svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "replacement run", agentId },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ );
+
+ const listed = await svc.listTestRuns(companyId, skillId);
+ expect(listed.map((run) => run.id)).toEqual([replacement.id, first.id]);
+ expect(listed.find((run) => run.id === first.id)?.supersededAt).toBeInstanceOf(Date);
+ expect(await svc.getTestRunDetail(companyId, skillId, first.id)).not.toBeNull();
+ expect(await svc.markTestRunRunning(companyId, first.issueId)).toBeNull();
+ expect(await svc.completeTestRunForIssue({
+ companyId,
+ issueId: first.issueId,
+ outcome: "succeeded",
+ })).toBeNull();
+ const cancelledIssueIds: string[] = [];
+ expect(await svc.cancelTestRun(companyId, skillId, first.id, {
+ cancelHarnessIssue: async (issueId) => {
+ cancelledIssueIds.push(issueId);
+ },
+ })).toBeNull();
+ expect(cancelledIssueIds).toEqual([]);
+
+ const firstRow = await db
+ .select({
+ status: companySkillTestRuns.status,
+ error: companySkillTestRuns.error,
+ supersededAt: companySkillTestRuns.supersededAt,
+ outputSnapshot: companySkillTestRuns.outputSnapshot,
+ })
+ .from(companySkillTestRuns)
+ .where(eq(companySkillTestRuns.id, first.id))
+ .then((rows) => rows[0] ?? null);
+ expect(firstRow?.status).toBe("cancelled");
+ expect(firstRow?.error).toBe("Superseded by newer run");
+ expect(firstRow?.supersededAt).toBeInstanceOf(Date);
+ expect(firstRow?.outputSnapshot).toBe("");
+
+ const hiddenIssueIds: string[] = [];
+ const deletedFirst = await svc.deleteTestRun(companyId, skillId, first.id, {
+ hideHarnessIssue: async (issueId) => {
+ hiddenIssueIds.push(issueId);
+ },
+ });
+ expect(deletedFirst?.id).toBe(first.id);
+ expect(hiddenIssueIds).toEqual([first.issueId]);
+ expect((await svc.listTestRuns(companyId, skillId)).map((run) => run.id)).toEqual([replacement.id]);
+
+ const runningReplacement = await svc.markTestRunRunning(companyId, replacement.issueId);
+ expect(runningReplacement?.status).toBe("running");
+ });
+
+ it("snapshots output and keeps run history after harness issue retention", async () => {
+ const companyId = randomUUID();
+ const skillId = randomUUID();
+ const agentId = randomUUID();
+ const skillDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-skill-test-run-"));
+ cleanupDirs.add(skillDir);
+ await fs.writeFile(path.join(skillDir, "SKILL.md"), "# Review 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(agents).values({
+ id: agentId,
+ companyId,
+ name: "Tester",
+ role: "engineer",
+ status: "idle",
+ adapterType: "codex_local",
+ adapterConfig: {
+ model: "gpt-5.4",
+ paperclipSkillSync: { desiredSkills: [`company/${companyId}/review`] },
+ instructionsFilePath: "/tmp/AGENTS.md",
+ },
+ });
+ await db.insert(companySkills).values({
+ id: skillId,
+ companyId,
+ key: `company/${companyId}/review`,
+ slug: "review",
+ name: "Review Skill",
+ description: null,
+ markdown: "# Review Skill\n",
+ sourceType: "local_path",
+ sourceLocator: skillDir,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ metadata: { sourceKind: "managed_local" },
+ });
+
+ const input = await svc.createTestInput(companyId, skillId, {
+ name: "cases/simple",
+ content: "Try the review skill",
+ }, { type: "user", userId: "local-board" });
+ const run = await svc.createTestRun(companyId, skillId, {
+ inputId: input.id,
+ agentId,
+ }, { type: "user", userId: "local-board" }, {
+ createHarnessIssue: async (issue) => {
+ await db.insert(issues).values({
+ ...issue,
+ companyId,
+ priority: "medium",
+ });
+ return { id: issue.id };
+ },
+ wakeHarnessIssue: async () => null,
+ retentionDays: 0,
+ });
+
+ expect(run.skillVersionId).toMatch(/[0-9a-f-]{36}/);
+ expect(run.inputSnapshot).toBe("Try the review skill");
+ expect(run.agentConfigSnapshot).toEqual(expect.objectContaining({
+ adapterType: "codex_local",
+ model: "gpt-5.4",
+ instructionsRef: "/tmp/AGENTS.md",
+ }));
+
+ const documentId = randomUUID();
+ await db.insert(documents).values({
+ id: documentId,
+ companyId,
+ title: "Output",
+ format: "markdown",
+ latestBody: "## Result\n\nThe skill responded.",
+ createdByAgentId: agentId,
+ updatedByAgentId: agentId,
+ });
+ await db.insert(issueDocuments).values({
+ companyId,
+ issueId: run.issueId,
+ documentId,
+ key: "output",
+ });
+
+ const completed = await svc.completeTestRunForIssue({
+ companyId,
+ issueId: run.issueId,
+ outcome: "succeeded",
+ });
+ expect(completed?.status).toBe("succeeded");
+ expect(completed?.outputSnapshot).toBe("## Result\n\nThe skill responded.");
+
+ await db
+ .update(companySkillTestRuns)
+ .set({ harnessIssueExpiresAt: new Date(Date.now() - 60_000) })
+ .where(eq(companySkillTestRuns.id, run.id));
+
+ const pruned = await svc.pruneExpiredTestHarnessIssues(companyId);
+ expect(pruned.pruned).toBe(1);
+ const detail = await svc.getTestRunDetail(companyId, skillId, run.id);
+ expect(detail?.taskExpired).toBe(true);
+ expect(detail?.harnessIssue).toBeNull();
+ expect(detail?.outputSnapshot).toBe("## Result\n\nThe skill responded.");
+ expect(detail?.outputBody).toBe("## Result\n\nThe skill responded.");
+ expect(detail?.harnessContent).toEqual({
+ available: false,
+ unavailableReason: "expired",
+ documents: [],
+ attachments: [],
+ workProducts: [],
+ });
+ });
+
+ it("hydrates rich documents, attachments, and work products scoped to the run's harness issue", async () => {
+ const { companyId, skillId, agentId } = await seedSkillAndAgent();
+ const run = await svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "produce rich output", agentId },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ );
+ // Sibling run in the same company whose content must not leak into `run`'s detail.
+ const otherRun = await svc.createTestRun(
+ companyId,
+ skillId,
+ { content: "unrelated run", agentId },
+ { type: "user", userId: "local-board" },
+ runDeps(companyId),
+ );
+
+ async function seedIssueContent(issueId: string, marker: string) {
+ const documentId = randomUUID();
+ await db.insert(documents).values({
+ id: documentId,
+ companyId,
+ title: `Output ${marker}`,
+ format: "markdown",
+ latestBody: `## Result ${marker}`,
+ createdByAgentId: agentId,
+ updatedByAgentId: agentId,
+ });
+ await db.insert(issueDocuments).values({ companyId, issueId, documentId, key: "output" });
+ const assetId = randomUUID();
+ await db.insert(assets).values({
+ id: assetId,
+ companyId,
+ provider: "local",
+ objectKey: `skill-tests/${marker}.png`,
+ contentType: "image/png",
+ byteSize: 2048,
+ sha256: marker.repeat(8).slice(0, 64).padEnd(64, "0"),
+ originalFilename: `${marker}.png`,
+ createdByAgentId: agentId,
+ });
+ const attachmentId = randomUUID();
+ await db.insert(issueAttachments).values({ id: attachmentId, companyId, issueId, assetId });
+ const workProductId = randomUUID();
+ await db.insert(issueWorkProducts).values({
+ id: workProductId,
+ companyId,
+ issueId,
+ type: "artifact",
+ provider: "paperclip",
+ title: `Artifact ${marker}`,
+ status: "active",
+ summary: `Generated ${marker}`,
+ metadata: {
+ attachmentId,
+ contentType: "image/png",
+ byteSize: 2048,
+ contentPath: `/api/attachments/${attachmentId}/content`,
+ originalFilename: `${marker}.png`,
+ },
+ });
+ return { documentId, attachmentId, workProductId };
+ }
+
+ const mine = await seedIssueContent(run.issueId, "mine");
+ await seedIssueContent(otherRun.issueId, "other");
+
+ const detail = await svc.getTestRunDetail(companyId, skillId, run.id);
+ expect(detail).not.toBeNull();
+ expect(detail?.harnessContent.available).toBe(true);
+ expect(detail?.harnessContent.unavailableReason).toBeNull();
+
+ expect(detail?.harnessContent.documents).toHaveLength(1);
+ const doc = detail!.harnessContent.documents[0]!;
+ expect(doc).toEqual(expect.objectContaining({
+ id: mine.documentId,
+ companyId,
+ issueId: run.issueId,
+ key: "output",
+ title: "Output mine",
+ format: "markdown",
+ body: "## Result mine",
+ createdByAgentId: agentId,
+ }));
+ expect(typeof doc.latestRevisionNumber).toBe("number");
+ expect(doc.createdAt).toBeInstanceOf(Date);
+ expect(doc.updatedAt).toBeInstanceOf(Date);
+ expect("sourceTrust" in doc).toBe(true);
+
+ expect(detail?.harnessContent.attachments).toHaveLength(1);
+ const attachment = detail!.harnessContent.attachments[0]!;
+ expect(attachment).toEqual(expect.objectContaining({
+ id: mine.attachmentId,
+ companyId,
+ issueId: run.issueId,
+ contentType: "image/png",
+ byteSize: 2048,
+ originalFilename: "mine.png",
+ contentPath: `/api/attachments/${mine.attachmentId}/content`,
+ openPath: `/api/attachments/${mine.attachmentId}/content`,
+ downloadPath: `/api/attachments/${mine.attachmentId}/content?download=1`,
+ }));
+
+ expect(detail?.harnessContent.workProducts).toHaveLength(1);
+ const workProduct = detail!.harnessContent.workProducts[0]!;
+ expect(workProduct).toEqual(expect.objectContaining({
+ id: mine.workProductId,
+ companyId,
+ issueId: run.issueId,
+ type: "artifact",
+ provider: "paperclip",
+ title: "Artifact mine",
+ summary: "Generated mine",
+ }));
+ expect(workProduct.metadata).toEqual(expect.objectContaining({
+ attachmentId: mine.attachmentId,
+ contentType: "image/png",
+ byteSize: 2048,
+ originalFilename: "mine.png",
+ }));
+
+ // Compatibility summaries stay in sync with the rich collections.
+ expect(detail?.documents).toEqual([
+ expect.objectContaining({ key: "output", title: "Output mine", body: "## Result mine" }),
+ ]);
+ expect(detail?.artifacts).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: mine.attachmentId, kind: "attachment", title: "mine.png" }),
+ expect.objectContaining({ id: mine.workProductId, kind: "work_product", title: "Artifact mine" }),
+ ]));
+ expect(detail?.artifacts).toHaveLength(2);
+ });
+
+ it("keeps hydration company-scoped and reports a deleted harness issue", async () => {
+ const first = await seedSkillAndAgent();
+ const second = await seedSkillAndAgent();
+ const run = await svc.createTestRun(
+ first.companyId,
+ first.skillId,
+ { content: "scoped run", agentId: first.agentId },
+ { type: "user", userId: "local-board" },
+ runDeps(first.companyId),
+ );
+
+ // Cross-company access never resolves another company's run.
+ expect(await svc.getTestRunDetail(second.companyId, first.skillId, run.id)).toBeNull();
+ expect(await svc.getTestRunDetail(second.companyId, second.skillId, run.id)).toBeNull();
+
+ // Harness issue marked deleted outside the retention path -> clear "deleted"
+ // state, while stored run snapshots stay usable.
+ await db
+ .update(companySkillTestRuns)
+ .set({ harnessIssueDeletedAt: new Date() })
+ .where(eq(companySkillTestRuns.id, run.id));
+ const detail = await svc.getTestRunDetail(first.companyId, first.skillId, run.id);
+ expect(detail).not.toBeNull();
+ expect(detail?.harnessIssue).toBeNull();
+ expect(detail?.inputSnapshot).toBe("scoped run");
+ expect(detail?.harnessContent).toEqual({
+ available: false,
+ unavailableReason: "deleted",
+ documents: [],
+ attachments: [],
+ workProducts: [],
+ });
+ });
+});
diff --git a/server/src/__tests__/company-skills-routes.test.ts b/server/src/__tests__/company-skills-routes.test.ts
index c964c4b15e..8b64c3551c 100644
--- a/server/src/__tests__/company-skills-routes.test.ts
+++ b/server/src/__tests__/company-skills-routes.test.ts
@@ -31,12 +31,38 @@ const mockCompanySkillService = vi.hoisted(() => ({
createLocalSkill: vi.fn(),
updateSkill: vi.fn(),
updateFile: vi.fn(),
+ deleteFile: vi.fn(),
scanProjectWorkspaces: vi.fn(),
deleteSkill: vi.fn(),
auditSkill: vi.fn(),
getById: vi.fn(),
installUpdate: vi.fn(),
resetSkill: vi.fn(),
+ listTestInputs: vi.fn(),
+ createTestInput: vi.fn(),
+ updateTestInput: vi.fn(),
+ deleteTestInput: vi.fn(),
+ listTestRunTemplates: vi.fn(),
+ createTestRunTemplate: vi.fn(),
+ updateTestRunTemplate: vi.fn(),
+ deleteTestRunTemplate: vi.fn(),
+ createTestRun: vi.fn(),
+ listTestRuns: vi.fn(),
+ getTestRunDetail: vi.fn(),
+ cancelTestRun: vi.fn(),
+ deleteTestRun: vi.fn(),
+ pruneExpiredTestHarnessIssues: vi.fn(),
+}));
+
+const mockIssueService = vi.hoisted(() => ({
+ create: vi.fn(),
+ getById: vi.fn(),
+ update: vi.fn(),
+}));
+
+const mockHeartbeatService = vi.hoisted(() => ({
+ wakeup: vi.fn(),
+ cancelRun: vi.fn(),
}));
const mockCatalogService = vi.hoisted(() => ({
@@ -83,6 +109,8 @@ function registerModuleMocks() {
accessService: () => mockAccessService,
agentService: () => mockAgentService,
companySkillService: () => mockCompanySkillService,
+ issueService: () => mockIssueService,
+ heartbeatService: () => mockHeartbeatService,
logActivity: mockLogActivity,
}));
}
@@ -338,6 +366,12 @@ describe("company skill mutation permissions", () => {
markdown: true,
editable: true,
});
+ mockCompanySkillService.deleteFile.mockResolvedValue({
+ skillId: "skill-1",
+ path: "references",
+ target: "folder",
+ deletedPaths: ["references/example.md"],
+ });
mockCompanySkillService.scanProjectWorkspaces.mockResolvedValue({
scannedProjects: 0,
scannedWorkspaces: 0,
@@ -381,6 +415,150 @@ describe("company skill mutation permissions", () => {
sourceRef: "sha256:def",
metadata: { originHash: "sha256:def" },
});
+ mockCompanySkillService.pruneExpiredTestHarnessIssues.mockResolvedValue({ pruned: 0 });
+ mockCompanySkillService.listTestInputs.mockResolvedValue([]);
+ mockCompanySkillService.createTestInput.mockResolvedValue({
+ id: "11111111-1111-4111-8111-111111111111",
+ companyId: "company-1",
+ skillId: "skill-1",
+ name: "smoke/input",
+ content: "Try the skill",
+ createdBy: "board",
+ deletedAt: null,
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:00:00.000Z"),
+ });
+ mockCompanySkillService.updateTestInput.mockResolvedValue({
+ id: "11111111-1111-4111-8111-111111111111",
+ companyId: "company-1",
+ skillId: "skill-1",
+ name: "smoke/renamed",
+ content: "Try the skill again",
+ createdBy: "board",
+ deletedAt: null,
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:01:00.000Z"),
+ });
+ mockCompanySkillService.deleteTestInput.mockResolvedValue({
+ id: "11111111-1111-4111-8111-111111111111",
+ companyId: "company-1",
+ skillId: "skill-1",
+ name: "smoke/renamed",
+ content: "Try the skill again",
+ createdBy: "board",
+ deletedAt: new Date("2026-05-26T00:02:00.000Z"),
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:02:00.000Z"),
+ });
+ const templateResponse = {
+ id: "66666666-6666-4666-8666-666666666666",
+ companyId: "company-1",
+ name: "Custom template",
+ description: "Custom run guidance",
+ body: "Run {{skillName}} into {{outputDocumentKey}}.",
+ builtIn: false,
+ createdByAgentId: null,
+ createdByUserId: "local-board",
+ updatedByAgentId: null,
+ updatedByUserId: "local-board",
+ deletedAt: null,
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:00:00.000Z"),
+ };
+ mockCompanySkillService.listTestRunTemplates.mockResolvedValue([{
+ ...templateResponse,
+ id: "built-in:default-test-template",
+ name: "Default test template",
+ description: "Paperclip default",
+ body: "Default {{skillName}}",
+ builtIn: true,
+ createdByUserId: null,
+ updatedByUserId: null,
+ }, templateResponse]);
+ mockCompanySkillService.createTestRunTemplate.mockResolvedValue(templateResponse);
+ mockCompanySkillService.updateTestRunTemplate.mockResolvedValue({
+ ...templateResponse,
+ name: "Renamed template",
+ updatedAt: new Date("2026-05-26T00:01:00.000Z"),
+ });
+ mockCompanySkillService.deleteTestRunTemplate.mockResolvedValue({
+ ...templateResponse,
+ deletedAt: new Date("2026-05-26T00:02:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:02:00.000Z"),
+ });
+ mockCompanySkillService.listTestRuns.mockResolvedValue([]);
+ mockCompanySkillService.getTestRunDetail.mockResolvedValue(null);
+ mockCompanySkillService.createTestRun.mockResolvedValue({
+ id: "22222222-2222-4222-8222-222222222222",
+ companyId: "company-1",
+ skillId: "skill-1",
+ inputId: "11111111-1111-4111-8111-111111111111",
+ inputSnapshot: "Try the skill",
+ skillVersionId: "33333333-3333-4333-8333-333333333333",
+ agentId: "55555555-5555-4555-8555-555555555555",
+ agentConfigSnapshot: { adapterType: "codex_local" },
+ issueId: "44444444-4444-4444-8444-444444444444",
+ templateId: "built-in:default-test-template",
+ templateName: "Default test template",
+ templateBody: "Default {{skillName}}",
+ renderedTemplateBody: "Default Review",
+ harnessIssueDescription: "Try the skill\n\n---\n\nDefault Review",
+ status: "queued",
+ outputDocumentKey: "output",
+ outputSnapshot: "",
+ error: null,
+ deletedAt: null,
+ supersededAt: null,
+ harnessIssueExpiresAt: null,
+ harnessIssueDeletedAt: null,
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:00:00.000Z"),
+ cost: { costCents: 0, inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 },
+ taskExpired: false,
+ });
+ mockCompanySkillService.cancelTestRun.mockResolvedValue({
+ id: "22222222-2222-4222-8222-222222222222",
+ companyId: "company-1",
+ skillId: "skill-1",
+ inputId: "11111111-1111-4111-8111-111111111111",
+ inputSnapshot: "Try the skill",
+ skillVersionId: "33333333-3333-4333-8333-333333333333",
+ agentId: "55555555-5555-4555-8555-555555555555",
+ agentConfigSnapshot: { adapterType: "codex_local" },
+ issueId: "44444444-4444-4444-8444-444444444444",
+ templateId: "built-in:default-test-template",
+ templateName: "Default test template",
+ templateBody: "Default {{skillName}}",
+ renderedTemplateBody: "Default Review",
+ harnessIssueDescription: "Try the skill\n\n---\n\nDefault Review",
+ status: "cancelled",
+ outputDocumentKey: "output",
+ outputSnapshot: "",
+ error: "Cancelled by operator",
+ deletedAt: null,
+ supersededAt: null,
+ harnessIssueExpiresAt: null,
+ harnessIssueDeletedAt: null,
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:01:00.000Z"),
+ cost: { costCents: 0, inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 },
+ taskExpired: false,
+ });
+ mockIssueService.create.mockResolvedValue({
+ id: "44444444-4444-4444-8444-444444444444",
+ companyId: "company-1",
+ identifier: "PAP-999",
+ title: "Skill test: Review",
+ });
+ mockIssueService.getById.mockResolvedValue({
+ id: "44444444-4444-4444-8444-444444444444",
+ companyId: "company-1",
+ status: "in_progress",
+ executionRunId: "run-1",
+ });
+ mockIssueService.update.mockResolvedValue({});
+ mockHeartbeatService.wakeup.mockResolvedValue({});
+ mockHeartbeatService.cancelRun.mockResolvedValue({});
mockCatalogService.listCatalogSkillsOrEmpty.mockReturnValue([]);
mockCatalogService.getCatalogSkillOrThrow.mockReturnValue({
id: "paperclipai:bundled:software-development:review",
@@ -743,14 +921,14 @@ describe("company skill mutation permissions", () => {
it("blocks same-company agents with skill creation disabled from mutating company skills", async () => {
mockAgentService.getById.mockResolvedValue({
- id: "agent-1",
+ id: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
permissions: { canCreateSkills: false },
});
const res = await request(await createApp({
type: "agent",
- agentId: "agent-1",
+ agentId: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
runId: "run-1",
}))
@@ -759,21 +937,21 @@ describe("company skill mutation permissions", () => {
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toBe("Missing permission: skills:create");
- expect(mockAccessService.hasPermission).toHaveBeenCalledWith("company-1", "agent", "agent-1", "skills:create");
- expect(mockAccessService.hasPermission).not.toHaveBeenCalledWith("company-1", "agent", "agent-1", "agents:create");
+ expect(mockAccessService.hasPermission).toHaveBeenCalledWith("company-1", "agent", "55555555-5555-4555-8555-555555555555", "skills:create");
+ expect(mockAccessService.hasPermission).not.toHaveBeenCalledWith("company-1", "agent", "55555555-5555-4555-8555-555555555555", "agents:create");
expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
});
it("blocks agent catalog installs for other companies", async () => {
mockAgentService.getById.mockResolvedValue({
- id: "agent-1",
+ id: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
permissions: { canCreateSkills: true },
});
const res = await request(await createApp({
type: "agent",
- agentId: "agent-1",
+ agentId: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
runId: "run-1",
}))
@@ -788,13 +966,14 @@ describe("company skill mutation permissions", () => {
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")
+ .get("/api/companies/company-1/skills?sort=stars&categories[]=memory&category=git&scope=company&q=review&include=lastEditor")
.expect(200);
expect(mockCompanySkillService.list).toHaveBeenCalledWith("company-1", {
q: "review",
sort: "stars",
categories: ["git", "memory"],
scope: "company",
+ include: ["lastEditor"],
});
await request(app).get("/api/companies/company-1/skills/categories").expect(200);
@@ -852,6 +1031,34 @@ describe("company skill mutation permissions", () => {
}));
});
+ it("deletes skill files and logs the mutation", async () => {
+ const app = await createApp({ type: "board", source: "local_implicit", userId: "user-1" });
+
+ const res = await request(app)
+ .delete("/api/companies/company-1/skills/skill-1/files")
+ .send({ path: "references", target: "folder" });
+
+ expect(res.status, JSON.stringify(res.body)).toBe(200);
+
+ expect(mockCompanySkillService.deleteFile).toHaveBeenCalledWith("company-1", "skill-1", {
+ path: "references",
+ target: "folder",
+ }, {
+ type: "user",
+ userId: "user-1",
+ });
+ expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ action: "company.skill_file_deleted",
+ entityType: "company_skill",
+ entityId: "skill-1",
+ details: {
+ path: "references",
+ target: "folder",
+ deletedPaths: ["references/example.md"],
+ },
+ }));
+ });
+
it("stars, forks, and comments on skills through company-scoped endpoints", async () => {
const app = await createApp({ type: "board", source: "local_implicit", userId: "user-1" });
@@ -919,14 +1126,14 @@ describe("company skill mutation permissions", () => {
it("allows agents with canCreateSkills to mutate company skills", async () => {
mockAgentService.getById.mockResolvedValue({
- id: "agent-1",
+ id: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
permissions: { canCreateSkills: true },
});
const res = await request(await createApp({
type: "agent",
- agentId: "agent-1",
+ agentId: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
runId: "run-1",
}))
@@ -942,14 +1149,14 @@ describe("company skill mutation permissions", () => {
it("allows same-company agents with missing skill creation permission to mutate company skills", async () => {
mockAgentService.getById.mockResolvedValue({
- id: "agent-1",
+ id: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
permissions: {},
});
const res = await request(await createApp({
type: "agent",
- agentId: "agent-1",
+ agentId: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
runId: "run-1",
}))
@@ -965,7 +1172,7 @@ describe("company skill mutation permissions", () => {
it("allows agents with explicit skills:create grants to mutate company skills", async () => {
mockAgentService.getById.mockResolvedValue({
- id: "agent-1",
+ id: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
permissions: { canCreateSkills: false },
});
@@ -980,7 +1187,7 @@ describe("company skill mutation permissions", () => {
const res = await request(await createApp({
type: "agent",
- agentId: "agent-1",
+ agentId: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
runId: "run-1",
}))
@@ -988,7 +1195,7 @@ describe("company skill mutation permissions", () => {
.send({ source: "https://github.com/vercel-labs/agent-browser" });
expect(res.status, JSON.stringify(res.body)).toBe(201);
- expect(mockAccessService.hasPermission).toHaveBeenCalledWith("company-1", "agent", "agent-1", "skills:create");
+ expect(mockAccessService.hasPermission).toHaveBeenCalledWith("company-1", "agent", "55555555-5555-4555-8555-555555555555", "skills:create");
expect(mockCompanySkillService.importFromSource).toHaveBeenCalledWith(
"company-1",
"https://github.com/vercel-labs/agent-browser",
@@ -997,7 +1204,7 @@ describe("company skill mutation permissions", () => {
it("does not allow explicit agents:create grants to mutate company skills", async () => {
mockAgentService.getById.mockResolvedValue({
- id: "agent-1",
+ id: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
permissions: { canCreateSkills: false },
});
@@ -1012,7 +1219,7 @@ describe("company skill mutation permissions", () => {
const res = await request(await createApp({
type: "agent",
- agentId: "agent-1",
+ agentId: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
runId: "run-1",
}))
@@ -1021,10 +1228,329 @@ describe("company skill mutation permissions", () => {
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toBe("Missing permission: skills:create");
- expect(mockAccessService.hasPermission).toHaveBeenCalledWith("company-1", "agent", "agent-1", "skills:create");
+ expect(mockAccessService.hasPermission).toHaveBeenCalledWith("company-1", "agent", "55555555-5555-4555-8555-555555555555", "skills:create");
expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
});
+ it("routes skill test input CRUD through skills mutation permissions", async () => {
+ const app = await createApp({
+ type: "board",
+ userId: "local-board",
+ companyIds: ["company-1"],
+ source: "local_implicit",
+ isInstanceAdmin: false,
+ });
+
+ const created = await request(app)
+ .post("/api/companies/company-1/skills/skill-1/test-inputs")
+ .send({ name: "smoke/input", content: "Try the skill" });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ expect(mockCompanySkillService.createTestInput).toHaveBeenCalledWith(
+ "company-1",
+ "skill-1",
+ { name: "smoke/input", content: "Try the skill" },
+ { type: "user", userId: "local-board" },
+ );
+
+ const updated = await request(app)
+ .patch("/api/companies/company-1/skills/skill-1/test-inputs/11111111-1111-4111-8111-111111111111")
+ .send({ name: "smoke/renamed", content: "Try the skill again" });
+ expect(updated.status, JSON.stringify(updated.body)).toBe(200);
+ expect(mockCompanySkillService.updateTestInput).toHaveBeenCalledWith(
+ "company-1",
+ "skill-1",
+ "11111111-1111-4111-8111-111111111111",
+ { name: "smoke/renamed", content: "Try the skill again" },
+ );
+
+ const removed = await request(app)
+ .delete("/api/companies/company-1/skills/skill-1/test-inputs/11111111-1111-4111-8111-111111111111");
+ expect(removed.status, JSON.stringify(removed.body)).toBe(200);
+ expect(mockCompanySkillService.deleteTestInput).toHaveBeenCalledWith(
+ "company-1",
+ "skill-1",
+ "11111111-1111-4111-8111-111111111111",
+ );
+ });
+
+ it("routes skill test run template CRUD through skills mutation permissions", async () => {
+ const app = await createApp({
+ type: "board",
+ userId: "local-board",
+ companyIds: ["company-1"],
+ source: "local_implicit",
+ isInstanceAdmin: false,
+ });
+
+ const listed = await request(app).get("/api/companies/company-1/skill-test-run-templates");
+ expect(listed.status, JSON.stringify(listed.body)).toBe(200);
+ expect(mockCompanySkillService.listTestRunTemplates).toHaveBeenCalledWith("company-1");
+
+ const created = await request(app)
+ .post("/api/companies/company-1/skill-test-run-templates")
+ .send({ name: "Custom template", description: "Custom run guidance", body: "Run {{skillName}}." });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ expect(mockCompanySkillService.createTestRunTemplate).toHaveBeenCalledWith(
+ "company-1",
+ { name: "Custom template", description: "Custom run guidance", body: "Run {{skillName}}." },
+ { type: "user", userId: "local-board" },
+ );
+
+ const updated = await request(app)
+ .patch("/api/companies/company-1/skill-test-run-templates/66666666-6666-4666-8666-666666666666")
+ .send({ name: "Renamed template" });
+ expect(updated.status, JSON.stringify(updated.body)).toBe(200);
+ expect(mockCompanySkillService.updateTestRunTemplate).toHaveBeenCalledWith(
+ "company-1",
+ "66666666-6666-4666-8666-666666666666",
+ { name: "Renamed template" },
+ { type: "user", userId: "local-board" },
+ );
+
+ const removed = await request(app)
+ .delete("/api/companies/company-1/skill-test-run-templates/66666666-6666-4666-8666-666666666666");
+ expect(removed.status, JSON.stringify(removed.body)).toBe(200);
+ expect(mockCompanySkillService.deleteTestRunTemplate).toHaveBeenCalledWith(
+ "company-1",
+ "66666666-6666-4666-8666-666666666666",
+ );
+ });
+
+ it("creates and cancels skill test runs through hidden issue orchestration", async () => {
+ mockCompanySkillService.createTestRun.mockImplementationOnce(async (
+ _companyId: string,
+ _skillId: string,
+ _body: unknown,
+ _actor: unknown,
+ deps: {
+ createHarnessIssue: (input: Record<string, unknown>) => Promise<unknown>;
+ wakeHarnessIssue: (issueId: string, agentId: string) => Promise<unknown>;
+ },
+ ) => {
+ await deps.createHarnessIssue({
+ id: "44444444-4444-4444-8444-444444444444",
+ title: "Skill test: Review",
+ description: "Try the skill",
+ assigneeAgentId: "55555555-5555-4555-8555-555555555555",
+ harnessKind: "skill_test",
+ workMode: "skill_test",
+ status: "todo",
+ originKind: "skill_test",
+ originId: "22222222-2222-4222-8222-222222222222",
+ originFingerprint: "skill_test:22222222-2222-4222-8222-222222222222",
+ });
+ await deps.wakeHarnessIssue("44444444-4444-4444-8444-444444444444", "55555555-5555-4555-8555-555555555555");
+ return {
+ id: "22222222-2222-4222-8222-222222222222",
+ companyId: "company-1",
+ skillId: "skill-1",
+ inputId: "11111111-1111-4111-8111-111111111111",
+ inputSnapshot: "Try the skill",
+ skillVersionId: "33333333-3333-4333-8333-333333333333",
+ agentId: "55555555-5555-4555-8555-555555555555",
+ agentConfigSnapshot: { adapterType: "codex_local" },
+ issueId: "44444444-4444-4444-8444-444444444444",
+ templateId: "built-in:default-test-template",
+ templateName: "Default test template",
+ templateBody: "Default {{skillName}}",
+ renderedTemplateBody: "Default Review",
+ harnessIssueDescription: "Try the skill\n\n---\n\nDefault Review",
+ status: "queued",
+ outputDocumentKey: "output",
+ outputSnapshot: "",
+ error: null,
+ deletedAt: null,
+ supersededAt: null,
+ harnessIssueExpiresAt: null,
+ harnessIssueDeletedAt: null,
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:00:00.000Z"),
+ cost: { costCents: 0, inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 },
+ taskExpired: false,
+ };
+ });
+ mockCompanySkillService.cancelTestRun.mockImplementationOnce(async (
+ _companyId: string,
+ _skillId: string,
+ _runId: string,
+ deps: { cancelHarnessIssue: (issueId: string) => Promise<unknown> },
+ ) => {
+ await deps.cancelHarnessIssue("44444444-4444-4444-8444-444444444444");
+ return {
+ id: "22222222-2222-4222-8222-222222222222",
+ companyId: "company-1",
+ skillId: "skill-1",
+ inputId: "11111111-1111-4111-8111-111111111111",
+ inputSnapshot: "Try the skill",
+ skillVersionId: "33333333-3333-4333-8333-333333333333",
+ agentId: "55555555-5555-4555-8555-555555555555",
+ agentConfigSnapshot: { adapterType: "codex_local" },
+ issueId: "44444444-4444-4444-8444-444444444444",
+ templateId: "built-in:default-test-template",
+ templateName: "Default test template",
+ templateBody: "Default {{skillName}}",
+ renderedTemplateBody: "Default Review",
+ harnessIssueDescription: "Try the skill\n\n---\n\nDefault Review",
+ status: "cancelled",
+ outputDocumentKey: "output",
+ outputSnapshot: "",
+ error: "Cancelled by operator",
+ deletedAt: null,
+ supersededAt: null,
+ harnessIssueExpiresAt: null,
+ harnessIssueDeletedAt: null,
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:01:00.000Z"),
+ cost: { costCents: 0, inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 },
+ taskExpired: false,
+ };
+ });
+
+ const app = await createApp({
+ type: "board",
+ userId: "local-board",
+ companyIds: ["company-1"],
+ source: "local_implicit",
+ isInstanceAdmin: false,
+ });
+
+ const created = await request(app)
+ .post("/api/companies/company-1/skills/skill-1/test-runs")
+ .send({ inputId: "11111111-1111-4111-8111-111111111111", agentId: "55555555-5555-4555-8555-555555555555" });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ expect(mockIssueService.create).toHaveBeenCalledWith("company-1", expect.objectContaining({
+ harnessKind: "skill_test",
+ workMode: "skill_test",
+ assigneeAgentId: "55555555-5555-4555-8555-555555555555",
+ description: "Try the skill",
+ }));
+ expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith("55555555-5555-4555-8555-555555555555", expect.objectContaining({
+ reason: "skill_test_run_created",
+ payload: expect.objectContaining({ issueId: "44444444-4444-4444-8444-444444444444", skillId: "skill-1" }),
+ }));
+
+ const cancelled = await request(app)
+ .post("/api/companies/company-1/skills/skill-1/test-runs/22222222-2222-4222-8222-222222222222/cancel")
+ .send({});
+ expect(cancelled.status, JSON.stringify(cancelled.body)).toBe(200);
+ expect(mockHeartbeatService.cancelRun).toHaveBeenCalledWith("run-1", "Cancelled by skill test run request");
+ expect(mockIssueService.update).toHaveBeenCalledWith("44444444-4444-4444-8444-444444444444", expect.objectContaining({
+ status: "cancelled",
+ actorUserId: "local-board",
+ }));
+ });
+
+ it("does not prune expired harness issues from test run reads", async () => {
+ mockCompanySkillService.listTestRuns.mockResolvedValueOnce([]);
+ mockCompanySkillService.getTestRunDetail.mockResolvedValueOnce({
+ id: "22222222-2222-4222-8222-222222222222",
+ companyId: "company-1",
+ skillId: "skill-1",
+ status: "succeeded",
+ harnessContent: { available: false, unavailableReason: "expired", documents: [], attachments: [], workProducts: [] },
+ });
+
+ const app = await createApp({
+ type: "board",
+ userId: "local-board",
+ companyIds: ["company-1"],
+ source: "local_implicit",
+ isInstanceAdmin: false,
+ });
+
+ const listed = await request(app)
+ .get("/api/companies/company-1/skills/skill-1/test-runs");
+ expect(listed.status, JSON.stringify(listed.body)).toBe(200);
+
+ const detail = await request(app)
+ .get("/api/companies/company-1/skills/skill-1/test-runs/22222222-2222-4222-8222-222222222222");
+ expect(detail.status, JSON.stringify(detail.body)).toBe(200);
+
+ expect(mockCompanySkillService.listTestRuns).toHaveBeenCalledWith("company-1", "skill-1", {});
+ expect(mockCompanySkillService.getTestRunDetail).toHaveBeenCalledWith(
+ "company-1",
+ "skill-1",
+ "22222222-2222-4222-8222-222222222222",
+ );
+ expect(mockCompanySkillService.pruneExpiredTestHarnessIssues).not.toHaveBeenCalled();
+ });
+
+ it("deletes a terminal test run and hides its harness task", async () => {
+ mockIssueService.getById.mockResolvedValueOnce({
+ id: "44444444-4444-4444-8444-444444444444",
+ companyId: "company-1",
+ status: "done",
+ executionRunId: null,
+ });
+ mockCompanySkillService.deleteTestRun.mockImplementationOnce(async (
+ _companyId: string,
+ _skillId: string,
+ _runId: string,
+ deps: { hideHarnessIssue: (issueId: string) => Promise<unknown> },
+ ) => {
+ await deps.hideHarnessIssue("44444444-4444-4444-8444-444444444444");
+ return {
+ id: "22222222-2222-4222-8222-222222222222",
+ companyId: "company-1",
+ skillId: "skill-1",
+ inputId: null,
+ inputSnapshot: "Try the skill",
+ skillVersionId: "33333333-3333-4333-8333-333333333333",
+ agentId: "55555555-5555-4555-8555-555555555555",
+ agentConfigSnapshot: { adapterType: "codex_local" },
+ issueId: "44444444-4444-4444-8444-444444444444",
+ templateId: "built-in:default-test-template",
+ templateName: "Default test template",
+ templateBody: "Default {{skillName}}",
+ renderedTemplateBody: "Default Review",
+ harnessIssueDescription: "Try the skill\n\n---\n\nDefault Review",
+ status: "succeeded",
+ outputDocumentKey: "output",
+ outputSnapshot: "",
+ error: null,
+ deletedAt: new Date("2026-05-26T00:02:00.000Z"),
+ supersededAt: null,
+ harnessIssueExpiresAt: null,
+ harnessIssueDeletedAt: null,
+ createdAt: new Date("2026-05-26T00:00:00.000Z"),
+ updatedAt: new Date("2026-05-26T00:02:00.000Z"),
+ cost: { costCents: 0, inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 },
+ taskExpired: false,
+ };
+ });
+
+ const app = await createApp({
+ type: "board",
+ userId: "local-board",
+ companyIds: ["company-1"],
+ source: "local_implicit",
+ isInstanceAdmin: false,
+ });
+
+ const deleted = await request(app)
+ .delete("/api/companies/company-1/skills/skill-1/test-runs/22222222-2222-4222-8222-222222222222");
+ expect(deleted.status, JSON.stringify(deleted.body)).toBe(200);
+ expect(mockCompanySkillService.deleteTestRun).toHaveBeenCalled();
+ expect(mockIssueService.update).toHaveBeenCalledWith(
+ "44444444-4444-4444-8444-444444444444",
+ expect.objectContaining({ hiddenAt: expect.any(Date) }),
+ );
+ });
+
+ it("returns 404 when deleting a missing test run", async () => {
+ mockCompanySkillService.deleteTestRun.mockResolvedValueOnce(null);
+ const app = await createApp({
+ type: "board",
+ userId: "local-board",
+ companyIds: ["company-1"],
+ source: "local_implicit",
+ isInstanceAdmin: false,
+ });
+ const res = await request(app)
+ .delete("/api/companies/company-1/skills/skill-1/test-runs/22222222-2222-4222-8222-222222222222");
+ expect(res.status).toBe(404);
+ });
+
it("returns a blocking error when attempting to delete a skill still used by agents", async () => {
const { unprocessable } = await import("../errors.js");
mockCompanySkillService.deleteSkill.mockImplementationOnce(async () => {
diff --git a/server/src/__tests__/company-skills-service.test.ts b/server/src/__tests__/company-skills-service.test.ts
index e4a01860c0..532abac3de 100644
--- a/server/src/__tests__/company-skills-service.test.ts
+++ b/server/src/__tests__/company-skills-service.test.ts
@@ -4,7 +4,7 @@ import path from "node:path";
import { promises as fs } from "node:fs";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { eq } from "drizzle-orm";
-import { agents, companies, companySkills, createDb } from "@paperclipai/db";
+import { agents, authUsers, companies, companySkillVersions, companySkills, createDb } from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
@@ -41,6 +41,7 @@ describeEmbeddedPostgres("companySkillService.list", () => {
await db.delete(agents);
await db.delete(companySkills);
await db.delete(companies);
+ await db.delete(authUsers);
await Promise.all(Array.from(cleanupDirs, (dir) => fs.rm(dir, { recursive: true, force: true })));
cleanupDirs.clear();
});
@@ -102,6 +103,168 @@ describeEmbeddedPostgres("companySkillService.list", () => {
});
});
+ it("optionally enriches list items with latest version editor identities", async () => {
+ const companyId = randomUUID();
+ const userSkillId = randomUUID();
+ const agentSkillId = randomUUID();
+ const unattributedSkillId = randomUUID();
+ const versionlessSkillId = randomUUID();
+ const agentId = randomUUID();
+ const userId = "board-editor";
+ const now = new Date();
+ async function writeTrackedSkillDir(slug: string, name: string) {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), `paperclip-${slug}-`));
+ cleanupDirs.add(dir);
+ await fs.writeFile(path.join(dir, "SKILL.md"), `---\nname: ${name}\n---\n\n# ${name}\n`, "utf8");
+ return dir;
+ }
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(authUsers).values({
+ id: userId,
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ emailVerified: true,
+ image: "https://example.com/ada.png",
+ createdAt: now,
+ updatedAt: now,
+ });
+ await db.insert(agents).values({
+ id: agentId,
+ companyId,
+ name: "CodexCoder",
+ role: "engineer",
+ adapterType: "codex_local",
+ adapterConfig: {},
+ });
+ await db.insert(companySkills).values([
+ {
+ id: userSkillId,
+ companyId,
+ key: `company/${companyId}/user-edited-skill`,
+ slug: "user-edited-skill",
+ name: "User Edited Skill",
+ description: null,
+ markdown: "# User Edited Skill",
+ sourceType: "local_path",
+ sourceLocator: await writeTrackedSkillDir("user-edited-skill", "User Edited Skill"),
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ },
+ {
+ id: agentSkillId,
+ companyId,
+ key: `company/${companyId}/agent-edited-skill`,
+ slug: "agent-edited-skill",
+ name: "Agent Edited Skill",
+ description: null,
+ markdown: "# Agent Edited Skill",
+ sourceType: "local_path",
+ sourceLocator: await writeTrackedSkillDir("agent-edited-skill", "Agent Edited Skill"),
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ },
+ {
+ id: unattributedSkillId,
+ companyId,
+ key: `company/${companyId}/unattributed-skill`,
+ slug: "unattributed-skill",
+ name: "Unattributed Skill",
+ description: null,
+ markdown: "# Unattributed Skill",
+ sourceType: "local_path",
+ sourceLocator: await writeTrackedSkillDir("unattributed-skill", "Unattributed Skill"),
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ },
+ {
+ id: versionlessSkillId,
+ companyId,
+ key: `company/${companyId}/versionless-skill`,
+ slug: "versionless-skill",
+ name: "Versionless Skill",
+ description: null,
+ markdown: "# Versionless Skill",
+ sourceType: "local_path",
+ sourceLocator: await writeTrackedSkillDir("versionless-skill", "Versionless Skill"),
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ },
+ ]);
+ await db.insert(companySkillVersions).values([
+ {
+ id: randomUUID(),
+ companyId,
+ companySkillId: userSkillId,
+ revisionNumber: 1,
+ fileInventory: [],
+ createdAt: new Date("2026-01-01T00:00:00.000Z"),
+ },
+ {
+ id: randomUUID(),
+ companyId,
+ companySkillId: userSkillId,
+ revisionNumber: 2,
+ fileInventory: [],
+ authorUserId: userId,
+ createdAt: new Date("2026-01-02T00:00:00.000Z"),
+ },
+ {
+ id: randomUUID(),
+ companyId,
+ companySkillId: agentSkillId,
+ revisionNumber: 1,
+ fileInventory: [],
+ authorAgentId: agentId,
+ createdAt: new Date("2026-01-03T00:00:00.000Z"),
+ },
+ {
+ id: randomUUID(),
+ companyId,
+ companySkillId: unattributedSkillId,
+ revisionNumber: 1,
+ fileInventory: [],
+ createdAt: new Date("2026-01-04T00:00:00.000Z"),
+ },
+ ]);
+
+ const defaultList = await svc.list(companyId);
+ expect(defaultList.find((skill) => skill.id === userSkillId)).not.toHaveProperty("lastEditor");
+
+ const enriched = await svc.list(companyId, { include: ["lastEditor"] });
+ expect(enriched.find((skill) => skill.id === userSkillId)).toMatchObject({
+ lastEditor: {
+ kind: "user",
+ id: userId,
+ name: "Ada Lovelace",
+ imageUrl: "https://example.com/ada.png",
+ },
+ });
+ expect(enriched.find((skill) => skill.id === agentSkillId)).toMatchObject({
+ lastEditor: {
+ kind: "agent",
+ id: agentId,
+ name: "CodexCoder",
+ imageUrl: null,
+ },
+ });
+ expect(enriched.find((skill) => skill.id === unattributedSkillId)).toMatchObject({
+ lastEditor: null,
+ });
+ expect(enriched.find((skill) => skill.id === versionlessSkillId)).toMatchObject({
+ lastEditor: null,
+ });
+ });
+
it("rejects skill inventory refresh for a missing company", async () => {
await expect(svc.list(randomUUID())).rejects.toMatchObject({
status: 404,
@@ -109,6 +272,159 @@ describeEmbeddedPostgres("companySkillService.list", () => {
});
});
+ it("does not retouch unchanged bundled skills during list refresh", async () => {
+ const companyId = randomUUID();
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+
+ const initialList = await svc.list(companyId, { sort: "recent" });
+ const bundledSkill = initialList.find((skill) => skill.key.startsWith("paperclipai/paperclip/"));
+ expect(bundledSkill).toBeDefined();
+ if (!bundledSkill) throw new Error("Expected bundled Paperclip skills fixture");
+
+ const preservedUpdatedAt = new Date("2026-01-01T00:00:00.000Z");
+ await db
+ .update(companySkills)
+ .set({ updatedAt: preservedUpdatedAt })
+ .where(eq(companySkills.id, bundledSkill.id));
+
+ const refreshedList = await svc.list(companyId, { sort: "recent" });
+ const refreshedSkill = refreshedList.find((skill) => skill.id === bundledSkill.id);
+
+ expect(refreshedSkill?.updatedAt.toISOString()).toBe(preservedUpdatedAt.toISOString());
+ });
+
+ it("does not retouch bundled skills with stale missing-source metadata during list refresh", async () => {
+ const companyId = randomUUID();
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+
+ const initialList = await svc.list(companyId, { sort: "recent" });
+ const bundledSkill = initialList.find((skill) => skill.key.startsWith("paperclipai/paperclip/"));
+ expect(bundledSkill).toBeDefined();
+ if (!bundledSkill) throw new Error("Expected bundled Paperclip skills fixture");
+
+ const preservedUpdatedAt = new Date("2026-01-04T00:00:00.000Z");
+ await db
+ .update(companySkills)
+ .set({
+ metadata: {
+ skillKey: bundledSkill.key,
+ sourceKind: "paperclip_bundled",
+ missingSource: {
+ reason: "local_source_missing",
+ detectedAt: "2026-01-01T00:00:00.000Z",
+ sourcePath: bundledSkill.sourceLocator,
+ sourceType: "local_path",
+ sourceLocator: bundledSkill.sourceLocator,
+ },
+ },
+ updatedAt: preservedUpdatedAt,
+ })
+ .where(eq(companySkills.id, bundledSkill.id));
+
+ const refreshedList = await svc.list(companyId, { sort: "recent" });
+ const refreshedSkill = refreshedList.find((skill) => skill.id === bundledSkill.id);
+ const stored = await svc.getById(companyId, bundledSkill.id);
+
+ expect(refreshedSkill?.updatedAt.toISOString()).toBe(preservedUpdatedAt.toISOString());
+ expect(stored?.metadata?.missingSource).toMatchObject({
+ reason: "local_source_missing",
+ sourceLocator: bundledSkill.sourceLocator,
+ });
+ });
+
+ it("does not retouch unchanged local-path imports", async () => {
+ const companyId = randomUUID();
+ const skillDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-idempotent-import-skill-"));
+ cleanupDirs.add(skillDir);
+ await fs.writeFile(
+ path.join(skillDir, "SKILL.md"),
+ "---\nname: Idempotent Import Skill\n---\n\n# Idempotent Import Skill\n",
+ "utf8",
+ );
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+
+ const imported = await svc.importFromSource(companyId, skillDir);
+ const skillId = imported.imported[0]?.id;
+ expect(skillId).toEqual(expect.any(String));
+ if (!skillId) throw new Error("Expected imported skill id");
+
+ const preservedUpdatedAt = new Date("2026-01-02T00:00:00.000Z");
+ await db
+ .update(companySkills)
+ .set({ updatedAt: preservedUpdatedAt })
+ .where(eq(companySkills.id, skillId));
+
+ await svc.importFromSource(companyId, skillDir);
+ const stored = await svc.getById(companyId, skillId);
+
+ expect(stored?.updatedAt.toISOString()).toBe(preservedUpdatedAt.toISOString());
+ });
+
+ it("refreshes local-path imports with legacy null metadata fields", async () => {
+ const companyId = randomUUID();
+ const skillDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-null-metadata-import-skill-"));
+ cleanupDirs.add(skillDir);
+ await fs.writeFile(
+ path.join(skillDir, "SKILL.md"),
+ "---\nname: Null Metadata Import Skill\n---\n\n# Null Metadata Import Skill\n",
+ "utf8",
+ );
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+
+ const imported = await svc.importFromSource(companyId, skillDir);
+ const skillId = imported.imported[0]?.id;
+ const skillKey = imported.imported[0]?.key;
+ expect(skillId).toEqual(expect.any(String));
+ expect(skillKey).toEqual(expect.any(String));
+ if (!skillId || !skillKey) throw new Error("Expected imported skill id and key");
+
+ const preservedUpdatedAt = new Date("2026-01-03T00:00:00.000Z");
+ await db
+ .update(companySkills)
+ .set({
+ metadata: {
+ sourceKind: "local_path",
+ skillKey,
+ owner: null,
+ repo: null,
+ ref: null,
+ trackingRef: null,
+ repoSkillDir: null,
+ },
+ updatedAt: preservedUpdatedAt,
+ })
+ .where(eq(companySkills.id, skillId));
+
+ await svc.importFromSource(companyId, skillDir);
+ const stored = await svc.getById(companyId, skillId);
+
+ expect(stored?.updatedAt.toISOString()).not.toBe(preservedUpdatedAt.toISOString());
+ expect(stored?.metadata).toMatchObject({ sourceKind: "local_path", skillKey });
+ expect(stored?.metadata).not.toHaveProperty("owner");
+ expect(stored?.metadata).not.toHaveProperty("repo");
+ expect(stored?.metadata).not.toHaveProperty("ref");
+ });
+
it("does not persist audit failures for remote-source skills", async () => {
const companyId = randomUUID();
const skillId = randomUUID();
@@ -304,7 +620,7 @@ describeEmbeddedPostgres("companySkillService.list", () => {
});
});
- it("updates categories, normalizes values, and reflects them in list filters and counts", async () => {
+ it("updates categories, allows spaces, and reflects them in list filters and counts", async () => {
const companyId = randomUUID();
await db.insert(companies).values({
id: companyId,
@@ -320,20 +636,23 @@ describeEmbeddedPostgres("companySkillService.list", () => {
});
const updated = await svc.updateSkill(companyId, skill.id, {
- categories: ["Memory", "review", "memory", " "],
+ categories: ["Memory Tools", "review", "memory tools", " "],
});
- expect(updated.categories).toEqual(["memory", "review"]);
+ expect(updated.categories).toEqual(["Memory Tools", "review"]);
await expect(svc.detail(companyId, skill.id)).resolves.toMatchObject({
id: skill.id,
- categories: ["memory", "review"],
+ categories: ["Memory Tools", "review"],
});
await expect(svc.list(companyId, { categories: ["review"] })).resolves.toEqual([
- expect.objectContaining({ id: skill.id, categories: ["memory", "review"] }),
+ expect.objectContaining({ id: skill.id, categories: ["Memory Tools", "review"] }),
+ ]);
+ await expect(svc.list(companyId, { categories: ["memory tools"] })).resolves.toEqual([
+ expect.objectContaining({ id: skill.id, categories: ["Memory Tools", "review"] }),
]);
await expect(svc.list(companyId, { categories: ["engineering"] })).resolves.toEqual([]);
await expect(svc.categoryCounts(companyId)).resolves.toEqual([
- { slug: "memory", count: 1 },
+ { slug: "Memory Tools", count: 1 },
{ slug: "review", count: 1 },
]);
@@ -344,6 +663,72 @@ describeEmbeddedPostgres("companySkillService.list", () => {
await expect(svc.categoryCounts(companyId)).resolves.toEqual([]);
});
+ it("resolves detail by unique skill slug for Studio deep links", 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: "Paperclip Blog Cover Image",
+ slug: "paperclip-blog-cover-image",
+ markdown: "# Paperclip Blog Cover Image\n",
+ });
+
+ await expect(svc.detail(companyId, "paperclip-blog-cover-image")).resolves.toMatchObject({
+ id: skill.id,
+ slug: "paperclip-blog-cover-image",
+ name: "Paperclip Blog Cover Image",
+ });
+ });
+
+ it("does not resolve ambiguous skill slugs", async () => {
+ const companyId = randomUUID();
+ const skillA = randomUUID();
+ const skillB = 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: skillA,
+ companyId,
+ key: `company/${companyId}/duplicate-a`,
+ slug: "duplicate",
+ name: "Duplicate A",
+ markdown: "# Duplicate A\n",
+ sourceType: "local_path",
+ sourceLocator: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ metadata: { sourceKind: "local_path" },
+ },
+ {
+ id: skillB,
+ companyId,
+ key: `company/${companyId}/duplicate-b`,
+ slug: "duplicate",
+ name: "Duplicate B",
+ markdown: "# Duplicate B\n",
+ sourceType: "local_path",
+ sourceLocator: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ metadata: { sourceKind: "local_path" },
+ },
+ ]);
+
+ await expect(svc.detail(companyId, "duplicate")).resolves.toBeNull();
+ });
+
it("creates a fork from the creation flow with copied files and lineage", async () => {
const companyId = randomUUID();
const sourceSkillId = randomUUID();
@@ -672,24 +1057,110 @@ describeEmbeddedPostgres("companySkillService.list", () => {
await expect(svc.resolveRequestedSkillEntries(companyId, [
"pinned-skill",
- ])).resolves.toEqual([
- { key: `company/${companyId}/pinned-skill`, versionId: null },
- ]);
+ ])).resolves.toEqual({
+ resolved: [{ key: `company/${companyId}/pinned-skill`, versionId: null }],
+ unresolved: [],
+ });
await expect(svc.resolveRequestedSkillEntries(companyId, [
{ key: "pinned-skill", versionId: null },
- ])).resolves.toEqual([
- { key: `company/${companyId}/pinned-skill`, versionId: null },
- ]);
+ ])).resolves.toEqual({
+ resolved: [{ key: `company/${companyId}/pinned-skill`, versionId: null }],
+ unresolved: [],
+ });
await expect(svc.resolveRequestedSkillEntries(companyId, [
{ key: "pinned-skill", versionId: version.id },
- ])).resolves.toEqual([
- { key: `company/${companyId}/pinned-skill`, versionId: version.id },
- ]);
+ ])).resolves.toEqual({
+ resolved: [{ key: `company/${companyId}/pinned-skill`, versionId: version.id }],
+ unresolved: [],
+ });
await expect(svc.resolveRequestedSkillEntries(companyId, [
{ key: "other-skill", versionId: version.id },
])).rejects.toMatchObject({ status: 422 });
});
+ it("rejects unknown desired keys by default but preserves them when tolerating (PAP-13222)", async () => {
+ const companyId = randomUUID();
+ const skillId = randomUUID();
+ const skillDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-tolerant-skill-"));
+ cleanupDirs.add(skillDir);
+ await fs.writeFile(path.join(skillDir, "SKILL.md"), "# Real 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}/real-skill`,
+ slug: "real-skill",
+ name: "Real Skill",
+ description: null,
+ markdown: "# Real Skill",
+ sourceType: "local_path",
+ sourceLocator: skillDir,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ });
+
+ // Strict (default): a stale/unknown key is a hard 422.
+ await expect(svc.resolveRequestedSkillEntries(companyId, [
+ "real-skill",
+ "stale/removed/skill",
+ ])).rejects.toMatchObject({ status: 422 });
+
+ // Tolerant: the resolvable key resolves, and the stale key is preserved
+ // (not thrown) so callers can keep it visible/removable.
+ await expect(svc.resolveRequestedSkillEntries(
+ companyId,
+ ["real-skill", "stale/removed/skill"],
+ { tolerateUnknownReferences: true },
+ )).resolves.toEqual({
+ resolved: [{ key: `company/${companyId}/real-skill`, versionId: null }],
+ unresolved: ["stale/removed/skill"],
+ });
+
+ // Ambiguity is still fatal even when tolerating unknown references. Two
+ // library skills sharing a slug make a bare-slug reference ambiguous.
+ const otherId = randomUUID();
+ await db.insert(companySkills).values({
+ id: otherId,
+ companyId,
+ key: `company/${companyId}/dup-a`,
+ slug: "dup",
+ name: "Dup A",
+ description: null,
+ markdown: "# Dup A",
+ sourceType: "local_path",
+ sourceLocator: skillDir,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ });
+ const otherId2 = randomUUID();
+ await db.insert(companySkills).values({
+ id: otherId2,
+ companyId,
+ key: `company/${companyId}/dup-b`,
+ slug: "dup",
+ name: "Dup B",
+ description: null,
+ markdown: "# Dup B",
+ sourceType: "local_path",
+ sourceLocator: skillDir,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ });
+ await expect(svc.resolveRequestedSkillEntries(
+ companyId,
+ ["dup"],
+ { tolerateUnknownReferences: true },
+ )).rejects.toMatchObject({ status: 422 });
+ });
+
it("preserves missing local-path skills that active agents still desire", async () => {
const companyId = randomUUID();
const skillId = randomUUID();
@@ -755,6 +1226,21 @@ describeEmbeddedPostgres("companySkillService.list", () => {
sourcePath: missingSkillDir,
});
expect(Number.isNaN(Date.parse(String((marker as Record<string, unknown>).detectedAt)))).toBe(false);
+
+ const preservedUpdatedAt = new Date("2026-01-05T00:00:00.000Z");
+ await db
+ .update(companySkills)
+ .set({ updatedAt: preservedUpdatedAt })
+ .where(eq(companySkills.id, skillId));
+
+ await svc.list(companyId);
+ const stableStored = await svc.getById(companyId, skillId);
+
+ expect(stableStored?.updatedAt.toISOString()).toBe(preservedUpdatedAt.toISOString());
+ expect(stableStored?.metadata?.missingSource).toMatchObject({
+ detectedAt: (marker as Record<string, unknown>).detectedAt,
+ sourceLocator: missingSkillDir,
+ });
});
it("continues pruning missing local-path skills that no active agent desires", async () => {
diff --git a/server/src/__tests__/costs-service.test.ts b/server/src/__tests__/costs-service.test.ts
index c8d9bda461..1effd44490 100644
--- a/server/src/__tests__/costs-service.test.ts
+++ b/server/src/__tests__/costs-service.test.ts
@@ -513,6 +513,7 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {
const rootIssueId = randomUUID();
const childIssueId = randomUUID();
const grandchildIssueId = randomUUID();
+ const harnessIssueId = randomUUID();
const siblingIssueId = randomUUID();
await db.insert(companies).values({
@@ -562,6 +563,18 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {
issueNumber: 3,
identifier: "TST-3",
},
+ {
+ id: harnessIssueId,
+ companyId,
+ parentId: rootIssueId,
+ title: "Hidden skill test harness",
+ status: "done",
+ priority: "medium",
+ issueNumber: 5,
+ identifier: "TST-5",
+ workMode: "skill_test",
+ harnessKind: "skill_test",
+ },
{
id: siblingIssueId,
companyId,
@@ -652,6 +665,7 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {
const rootIssueId = randomUUID();
const childIssueId = randomUUID();
const grandchildIssueId = randomUUID();
+ const harnessIssueId = randomUUID();
const siblingIssueId = randomUUID();
await db.insert(companies).values({
@@ -710,11 +724,24 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {
issueNumber: 4,
identifier: "TST-4",
},
+ {
+ id: harnessIssueId,
+ companyId,
+ parentId: rootIssueId,
+ title: "Harness child",
+ status: "done",
+ priority: "medium",
+ workMode: "skill_test",
+ harnessKind: "skill_test",
+ issueNumber: 5,
+ identifier: "TST-5",
+ },
]);
const linkedViaContextRunId = randomUUID();
const linkedViaActivityRunId = randomUUID();
const grandchildRunId = randomUUID();
+ const harnessRunId = randomUUID();
const siblingRunId = randomUUID();
const livePartialRunId = randomUUID();
@@ -751,6 +778,17 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {
finishedAt: new Date("2026-04-10T00:10:30.000Z"),
contextSnapshot: { issueId: grandchildIssueId },
},
+ // 45s harness run under root - should be excluded from visible issue tree rollups
+ {
+ id: harnessRunId,
+ companyId,
+ agentId,
+ invocationSource: "on_demand",
+ status: "completed",
+ startedAt: new Date("2026-04-10T00:15:00.000Z"),
+ finishedAt: new Date("2026-04-10T00:15:45.000Z"),
+ contextSnapshot: { issueId: harnessIssueId },
+ },
// sibling run NOT under root – should be excluded
{
id: siblingRunId,
diff --git a/server/src/__tests__/document-annotation-routes.test.ts b/server/src/__tests__/document-annotation-routes.test.ts
index 1fd64e02dc..450d7fbfdd 100644
--- a/server/src/__tests__/document-annotation-routes.test.ts
+++ b/server/src/__tests__/document-annotation-routes.test.ts
@@ -120,6 +120,9 @@ function registerModuleMocks() {
hasPermission: vi.fn(async () => false),
}),
agentService: () => ({ getById: vi.fn(), list: vi.fn(async () => []) }),
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
companyService: () => ({ getById: vi.fn(async () => ({ id: companyId, attachmentMaxBytes: 10_000_000 })) }),
documentAnnotationService: () => mockAnnotationService,
documentService: () => mockDocumentService,
diff --git a/server/src/__tests__/environment-selection-route-guards.test.ts b/server/src/__tests__/environment-selection-route-guards.test.ts
index e65edb0687..468afa571f 100644
--- a/server/src/__tests__/environment-selection-route-guards.test.ts
+++ b/server/src/__tests__/environment-selection-route-guards.test.ts
@@ -67,6 +67,9 @@ vi.mock("../services/index.js", () => ({
agentService: () => ({
getById: vi.fn(),
}),
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
executionWorkspaceService: () => ({}),
goalService: () => ({
getById: vi.fn(),
diff --git a/server/src/__tests__/external-object-routes.test.ts b/server/src/__tests__/external-object-routes.test.ts
index 24e8064336..96a6d30e3f 100644
--- a/server/src/__tests__/external-object-routes.test.ts
+++ b/server/src/__tests__/external-object-routes.test.ts
@@ -50,6 +50,7 @@ function registerRouteMocks() {
vi.doMock("../services/index.js", () => ({
accessService: () => mockAccessService,
agentService: () => mockAgentService,
+ companySkillService: () => ({}),
companyService: () => ({
getById: vi.fn(async () => null),
}),
@@ -103,13 +104,20 @@ async function createApp(actor: Express.Request["actor"]) {
vi.importActual<typeof import("../middleware/index.js")>("../middleware/index.js"),
vi.importActual<typeof import("../routes/issues.js")>("../routes/issues.js"),
]);
+ const routeDb = {
+ select: vi.fn(() => ({
+ from: vi.fn(() => ({
+ where: vi.fn(async () => [makeIssue()]),
+ })),
+ })),
+ };
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = actor;
next();
});
- app.use("/api", issueRoutes({} as any, { provider: "local_disk" } as any));
+ app.use("/api", issueRoutes(routeDb as any, { provider: "local_disk" } as any));
app.use(errorHandler);
return app;
}
@@ -161,7 +169,7 @@ describe("external object routes", () => {
mockIssueService.assertCheckoutOwner.mockResolvedValue({ adoptedFromRunId: null });
mockAccessService.hasPermission.mockResolvedValue(false);
mockAccessService.decide.mockImplementation(async ({ action }: { action: string }) => ({
- allowed: action === "issue:mutate",
+ allowed: action === "issue:read" || action === "issue:mutate",
explanation: "Denied by test mock",
}));
mockAgentService.list.mockResolvedValue([
@@ -169,9 +177,9 @@ describe("external object routes", () => {
{ id: peerAgentId, companyId, reportsTo: null, permissions: { canCreateAgents: false } },
]);
mockExternalObjectsService.getIssueSummary.mockResolvedValue({ total: 1, objects: [] });
- mockExternalObjectsService.getIssueSummaries.mockResolvedValue(new Map([
- [issueId, { total: 1, objects: [] }],
- ]));
+ mockExternalObjectsService.getIssueSummaries.mockImplementation(async (_companyId: string, issueIds: string[]) =>
+ new Map(issueIds.map((id) => [id, { total: 1, objects: [] }])),
+ );
mockExternalObjectsService.listForIssue.mockResolvedValue([]);
mockExternalObjectsService.refreshIssueObjects.mockResolvedValue([
{ object: { id: "77777777-7777-4777-8777-777777777777" }, refreshed: false, reason: "no_resolver" },
@@ -200,6 +208,22 @@ describe("external object routes", () => {
expect(mockExternalObjectsService.getIssueSummary).toHaveBeenCalledWith(issueId);
});
+ it("requires issue read access before reading issue external objects", async () => {
+ mockAccessService.decide.mockResolvedValue({
+ allowed: false,
+ explanation: "Denied by test mock",
+ });
+ const app = await createApp(ownerActor());
+
+ const summary = await request(app).get(`/api/issues/${issueId}/external-object-summary`);
+ expect(summary.status).toBe(403);
+ expect(mockExternalObjectsService.getIssueSummary).not.toHaveBeenCalled();
+
+ const list = await request(app).get(`/api/issues/${issueId}/external-objects`);
+ expect(list.status).toBe(403);
+ expect(mockExternalObjectsService.listForIssue).not.toHaveBeenCalled();
+ });
+
it("allows board users to fetch company-scoped external object summaries in bulk", async () => {
const app = await createApp(boardActor());
@@ -212,6 +236,22 @@ describe("external object routes", () => {
expect(mockExternalObjectsService.getIssueSummaries).toHaveBeenCalledWith(companyId, [issueId]);
});
+ it("filters bulk external object summaries through issue read access", async () => {
+ mockAccessService.decide.mockResolvedValue({
+ allowed: false,
+ explanation: "Denied by test mock",
+ });
+ const app = await createApp(ownerActor());
+
+ const res = await request(app)
+ .post(`/api/companies/${companyId}/issues/external-object-summaries`)
+ .send({ issueIds: [issueId] });
+
+ expect(res.status).toBe(200);
+ expect(res.body.summaries).toEqual({});
+ expect(mockExternalObjectsService.getIssueSummaries).toHaveBeenCalledWith(companyId, []);
+ });
+
it("enforces company access on bulk external object summaries", async () => {
const app = await createApp({ ...ownerActor(), companyId: "other-company" });
diff --git a/server/src/__tests__/heartbeat-context-summary.test.ts b/server/src/__tests__/heartbeat-context-summary.test.ts
index 4463640d97..8d696e335f 100644
--- a/server/src/__tests__/heartbeat-context-summary.test.ts
+++ b/server/src/__tests__/heartbeat-context-summary.test.ts
@@ -90,6 +90,23 @@ describe("buildPaperclipTaskMarkdown", () => {
expect(assignment).toContain("do not produce an implementation plan");
});
+ it("adds dry-run containment guidance for skill-test issues", () => {
+ const assignment = buildPaperclipTaskMarkdown({
+ issue: {
+ id: "issue-skill-test",
+ identifier: "PAP-417",
+ title: "Test skill draft",
+ workMode: "skill_test",
+ description: null,
+ },
+ });
+
+ expect(assignment).toContain("- Work mode: \"skill_test\"");
+ expect(assignment).toContain("Skill test mode directive:");
+ expect(assignment).toContain("Make no durable changes outside this issue.");
+ expect(assignment).toContain("Write your final output as issue document `output`");
+ });
+
it("prefers ordinary comment planning guidance over stale accepted confirmation state", () => {
const commentWake = buildPaperclipTaskMarkdown({
issue: {
diff --git a/server/src/__tests__/heartbeat-scheduling-suppression.test.ts b/server/src/__tests__/heartbeat-scheduling-suppression.test.ts
index 4fb35931fb..f583e60fb8 100644
--- a/server/src/__tests__/heartbeat-scheduling-suppression.test.ts
+++ b/server/src/__tests__/heartbeat-scheduling-suppression.test.ts
@@ -1,5 +1,8 @@
import { describe, expect, it } from "vitest";
-import { resolveHeartbeatSchedulingSuppression } from "../services/heartbeat.ts";
+import {
+ resolveHeartbeatSchedulingSuppression,
+ resolveSkillTestRunCompletionForHeartbeatOutcome,
+} from "../services/heartbeat.ts";
describe("heartbeat scheduling suppression", () => {
it("suppresses heartbeat scheduling for worktree runtimes", () => {
@@ -26,4 +29,50 @@ describe("heartbeat scheduling suppression", () => {
reason: null,
});
});
+
+ it("lifts worktree suppression when run execution is explicitly allowed", () => {
+ expect(
+ resolveHeartbeatSchedulingSuppression(
+ { PAPERCLIP_IN_WORKTREE: "true" },
+ { allowWorktreeRunExecution: true },
+ ),
+ ).toEqual({
+ suppressed: false,
+ reason: null,
+ });
+ });
+
+ it("still suppresses database restore even when worktree run execution is allowed", () => {
+ expect(
+ resolveHeartbeatSchedulingSuppression(
+ {
+ PAPERCLIP_IN_WORKTREE: "true",
+ PAPERCLIP_DATABASE_RESTORE_IN_PROGRESS: "1",
+ },
+ { allowWorktreeRunExecution: true },
+ ),
+ ).toEqual({
+ suppressed: true,
+ reason: "database_restore_in_progress",
+ });
+ });
+
+ it("maps unsuccessful heartbeat outcomes to terminal skill test run outcomes", () => {
+ expect(resolveSkillTestRunCompletionForHeartbeatOutcome("succeeded", null)).toBeNull();
+ expect(resolveSkillTestRunCompletionForHeartbeatOutcome("cancelled", null)).toEqual({
+ outcome: "cancelled",
+ error: "Harness run was cancelled",
+ heartbeatOutcome: "cancelled",
+ });
+ expect(resolveSkillTestRunCompletionForHeartbeatOutcome("timed_out", null)).toEqual({
+ outcome: "failed",
+ error: "Timed out",
+ heartbeatOutcome: "timed_out",
+ });
+ expect(resolveSkillTestRunCompletionForHeartbeatOutcome("failed", "Adapter crashed")).toEqual({
+ outcome: "failed",
+ error: "Adapter crashed",
+ heartbeatOutcome: "failed",
+ });
+ });
});
diff --git a/server/src/__tests__/heartbeat-worktree-suppression.test.ts b/server/src/__tests__/heartbeat-worktree-suppression.test.ts
index bb1e23c944..58daa176c5 100644
--- a/server/src/__tests__/heartbeat-worktree-suppression.test.ts
+++ b/server/src/__tests__/heartbeat-worktree-suppression.test.ts
@@ -13,6 +13,7 @@ import {
documents,
heartbeatRunEvents,
heartbeatRuns,
+ instanceSettings,
issueComments,
issueDocuments,
issues,
@@ -22,6 +23,7 @@ import {
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { heartbeatService, resolveHeartbeatSchedulingSuppression } from "../services/heartbeat.ts";
+import { instanceSettingsService } from "../services/instance-settings.ts";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
@@ -72,6 +74,7 @@ describeEmbeddedPostgres("heartbeat worktree suppression", () => {
await db.delete(companySkills);
await db.delete(agents);
await db.delete(companies);
+ await db.delete(instanceSettings);
});
afterAll(async () => {
diff --git a/server/src/__tests__/instance-settings-service.test.ts b/server/src/__tests__/instance-settings-service.test.ts
index 3fbed144ba..5f2ca06995 100644
--- a/server/src/__tests__/instance-settings-service.test.ts
+++ b/server/src/__tests__/instance-settings-service.test.ts
@@ -33,6 +33,7 @@ describe("instance settings service", () => {
autoRestartDevServerWhenIdle: true,
enableIssueGraphLivenessAutoRecovery: true,
enableWorkspaceBranchReconcileForward: true,
+ enableWorktreeRunExecution: false,
issueGraphLivenessAutoRecoveryLookbackHours: 48,
});
});
diff --git a/server/src/__tests__/issue-activity-events-routes.test.ts b/server/src/__tests__/issue-activity-events-routes.test.ts
index 9b6daa189b..550acc57c4 100644
--- a/server/src/__tests__/issue-activity-events-routes.test.ts
+++ b/server/src/__tests__/issue-activity-events-routes.test.ts
@@ -82,6 +82,9 @@ function registerModuleMocks() {
agentService: () => ({
getById: vi.fn(async () => null),
}),
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({}),
executionWorkspaceService: () => ({}),
diff --git a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts
index 0e5ea769ed..821a5c37f0 100644
--- a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts
+++ b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts
@@ -179,6 +179,9 @@ function registerRouteMocks() {
accessService: () => mockAccessService,
agentService: () => mockAgentService,
clampIssueListLimit: (value: number) => Math.min(Math.max(value, 1), 500),
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
companyService: () => mockCompanyService,
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => mockDocumentService,
diff --git a/server/src/__tests__/issue-assigned-backlog-contract-routes.test.ts b/server/src/__tests__/issue-assigned-backlog-contract-routes.test.ts
index 13d8c727ea..52e8224fc2 100644
--- a/server/src/__tests__/issue-assigned-backlog-contract-routes.test.ts
+++ b/server/src/__tests__/issue-assigned-backlog-contract-routes.test.ts
@@ -42,6 +42,9 @@ vi.mock("../services/index.js", () => ({
},
})),
}),
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
companyService: () => ({
getById: vi.fn(async () => ({ id: "company-1", attachmentMaxBytes: 10 * 1024 * 1024 })),
}),
diff --git a/server/src/__tests__/issue-attachment-routes.test.ts b/server/src/__tests__/issue-attachment-routes.test.ts
index b7f6fb7379..42a9423392 100644
--- a/server/src/__tests__/issue-attachment-routes.test.ts
+++ b/server/src/__tests__/issue-attachment-routes.test.ts
@@ -19,6 +19,14 @@ const mockWorkProductService = vi.hoisted(() => ({
getById: vi.fn(),
update: vi.fn(),
}));
+const mockAccessService = vi.hoisted(() => ({
+ decide: vi.fn(async () => ({
+ allowed: true,
+ explanation: "Allowed by test mock",
+ })),
+ canUser: vi.fn(),
+ hasPermission: vi.fn(),
+}));
const mockLogActivity = vi.hoisted(() => vi.fn(async () => undefined));
@@ -41,13 +49,11 @@ function registerRouteMocks() {
}));
vi.doMock("../services/index.js", () => ({
- accessService: () => ({
- canUser: vi.fn(),
- hasPermission: vi.fn(),
- }),
+ accessService: () => mockAccessService,
agentService: () => ({
getById: vi.fn(),
}),
+ companySkillService: () => ({}),
companyService: () => mockCompanyService,
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({}),
@@ -232,7 +238,21 @@ describe("issue attachment routes", () => {
vi.doUnmock("../middleware/index.js");
registerRouteMocks();
vi.clearAllMocks();
+ mockAccessService.decide.mockResolvedValue({
+ allowed: true,
+ explanation: "Allowed by test mock",
+ });
mockLogActivity.mockResolvedValue(undefined);
+ mockIssueService.getById.mockResolvedValue({
+ id: "11111111-1111-4111-8111-111111111111",
+ companyId: "company-1",
+ projectId: null,
+ parentId: null,
+ status: "todo",
+ assigneeAgentId: null,
+ assigneeUserId: null,
+ identifier: "PAP-1",
+ });
mockCompanyService.getById.mockResolvedValue({
id: "company-1",
attachmentMaxBytes: 1024 * 1024 * 1024,
@@ -503,6 +523,21 @@ describe("issue attachment routes", () => {
expect(storage.getObject).not.toHaveBeenCalled();
});
+ it("rejects same-company attachment content reads outside the parent issue boundary", async () => {
+ const storage = createStorageService();
+ mockIssueService.getAttachmentById.mockResolvedValue(makeAttachment("video/mp4", "clip.mp4"));
+ mockAccessService.decide.mockResolvedValue({
+ allowed: false,
+ explanation: "Denied by test mock",
+ });
+
+ const app = await createApp(storage);
+ const res = await request(app).get("/api/attachments/attachment-1/content");
+
+ expect(res.status).toBe(403);
+ expect(storage.getObject).not.toHaveBeenCalled();
+ });
+
it("canonicalizes paperclip artifact metadata before creating a work product", async () => {
const storage = createStorageService();
const issue = {
diff --git a/server/src/__tests__/issue-closed-workspace-routes.test.ts b/server/src/__tests__/issue-closed-workspace-routes.test.ts
index fd322bc898..d9c82cd7d0 100644
--- a/server/src/__tests__/issue-closed-workspace-routes.test.ts
+++ b/server/src/__tests__/issue-closed-workspace-routes.test.ts
@@ -81,6 +81,9 @@ function registerServiceMocks() {
agentService: () => ({
getById: vi.fn(async () => null),
}),
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({}),
executionWorkspaceService: () => mockExecutionWorkspaceService,
diff --git a/server/src/__tests__/issue-comment-cancel-routes.test.ts b/server/src/__tests__/issue-comment-cancel-routes.test.ts
index bd46a12ce3..a85e648c3a 100644
--- a/server/src/__tests__/issue-comment-cancel-routes.test.ts
+++ b/server/src/__tests__/issue-comment-cancel-routes.test.ts
@@ -120,6 +120,9 @@ function registerModuleMocks() {
}),
accessService: () => mockAccessService,
agentService: () => ({ getById: vi.fn(async () => null) }),
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => mockDocumentAnnotationService,
documentService: () => ({}),
executionWorkspaceService: () => ({}),
diff --git a/server/src/__tests__/issue-comment-reopen-routes.test.ts b/server/src/__tests__/issue-comment-reopen-routes.test.ts
index 22ef7d7fa7..3a0b090748 100644
--- a/server/src/__tests__/issue-comment-reopen-routes.test.ts
+++ b/server/src/__tests__/issue-comment-reopen-routes.test.ts
@@ -131,6 +131,9 @@ vi.mock("../services/index.js", () => ({
}),
accessService: () => mockAccessService,
agentService: () => mockAgentService,
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({}),
executionWorkspaceService: () => ({}),
diff --git a/server/src/__tests__/issue-dependency-wakeups-routes.test.ts b/server/src/__tests__/issue-dependency-wakeups-routes.test.ts
index 38c16f7e43..da27484dbf 100644
--- a/server/src/__tests__/issue-dependency-wakeups-routes.test.ts
+++ b/server/src/__tests__/issue-dependency-wakeups-routes.test.ts
@@ -29,6 +29,9 @@ vi.mock("../services/index.js", () => ({
agentService: () => ({
getById: vi.fn(),
}),
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({
getIssueDocumentPayload: vi.fn(async () => ({})),
diff --git a/server/src/__tests__/issue-document-restore-routes.test.ts b/server/src/__tests__/issue-document-restore-routes.test.ts
index d0fe8df9ba..7b528f084c 100644
--- a/server/src/__tests__/issue-document-restore-routes.test.ts
+++ b/server/src/__tests__/issue-document-restore-routes.test.ts
@@ -115,6 +115,9 @@ function registerModuleMocks() {
}),
accessService: () => mockAccessService,
agentService: () => mockAgentService,
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => mockDocumentsService,
executionWorkspaceService: () => ({}),
diff --git a/server/src/__tests__/issue-execution-policy-routes.test.ts b/server/src/__tests__/issue-execution-policy-routes.test.ts
index cce87c1b4e..2c2e494632 100644
--- a/server/src/__tests__/issue-execution-policy-routes.test.ts
+++ b/server/src/__tests__/issue-execution-policy-routes.test.ts
@@ -75,6 +75,9 @@ function registerModuleMocks() {
},
})),
}),
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({}),
executionWorkspaceService: () => ({}),
diff --git a/server/src/__tests__/issue-feedback-routes.test.ts b/server/src/__tests__/issue-feedback-routes.test.ts
index 7e4107d6d8..727b36f7f2 100644
--- a/server/src/__tests__/issue-feedback-routes.test.ts
+++ b/server/src/__tests__/issue-feedback-routes.test.ts
@@ -87,6 +87,9 @@ function registerModuleMocks() {
}),
accessService: () => mockAccessService,
agentService: () => mockAgentService,
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({}),
executionWorkspaceService: () => mockExecutionWorkspaceService,
diff --git a/server/src/__tests__/issue-telemetry-routes.test.ts b/server/src/__tests__/issue-telemetry-routes.test.ts
index 9c97818d83..55a105ee24 100644
--- a/server/src/__tests__/issue-telemetry-routes.test.ts
+++ b/server/src/__tests__/issue-telemetry-routes.test.ts
@@ -50,6 +50,9 @@ function registerModuleMocks() {
hasPermission: vi.fn(),
}),
agentService: () => mockAgentService,
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({}),
executionWorkspaceService: () => ({}),
diff --git a/server/src/__tests__/issue-thread-interaction-routes.test.ts b/server/src/__tests__/issue-thread-interaction-routes.test.ts
index 0c08bcb0d2..c0ab044906 100644
--- a/server/src/__tests__/issue-thread-interaction-routes.test.ts
+++ b/server/src/__tests__/issue-thread-interaction-routes.test.ts
@@ -71,6 +71,9 @@ function registerModuleMocks() {
})),
}),
clampIssueListLimit: (value: number) => value,
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
ISSUE_LIST_DEFAULT_LIMIT: 500,
ISSUE_LIST_MAX_LIMIT: 1000,
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
diff --git a/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts b/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts
index 41b8c76a28..4fb46c0dc3 100644
--- a/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts
+++ b/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts
@@ -50,6 +50,9 @@ vi.mock("../services/index.js", () => ({
agent: { id: raw },
})),
}),
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({}),
executionWorkspaceService: () => ({}),
@@ -119,6 +122,9 @@ function registerModuleMocks() {
agent: { id: raw },
})),
}),
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({}),
executionWorkspaceService: () => ({}),
diff --git a/server/src/__tests__/issue-workspace-command-authz.test.ts b/server/src/__tests__/issue-workspace-command-authz.test.ts
index 18494d1a49..1240af41c3 100644
--- a/server/src/__tests__/issue-workspace-command-authz.test.ts
+++ b/server/src/__tests__/issue-workspace-command-authz.test.ts
@@ -109,6 +109,9 @@ function registerRouteMocks() {
}),
accessService: () => mockAccessService,
agentService: () => mockAgentService,
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({}),
executionWorkspaceService: () => mockExecutionWorkspaceService,
diff --git a/server/src/__tests__/issues-goal-context-routes.test.ts b/server/src/__tests__/issues-goal-context-routes.test.ts
index ac755efb7f..14a011886b 100644
--- a/server/src/__tests__/issues-goal-context-routes.test.ts
+++ b/server/src/__tests__/issues-goal-context-routes.test.ts
@@ -104,6 +104,9 @@ vi.mock("../services/index.js", () => ({
}),
accessService: () => mockAccessService,
agentService: () => mockAgentService,
+ companySkillService: () => ({
+ completeTestRunForIssue: vi.fn(async () => null),
+ }),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => mockDocumentsService,
environmentService: () => mockEnvironmentService,
diff --git a/server/src/__tests__/low-trust-red-team-routes.test.ts b/server/src/__tests__/low-trust-red-team-routes.test.ts
index 53a5f47a08..d8a893f171 100644
--- a/server/src/__tests__/low-trust-red-team-routes.test.ts
+++ b/server/src/__tests__/low-trust-red-team-routes.test.ts
@@ -11,13 +11,19 @@ import {
agentRuntimeState,
agents,
approvals,
+ assets,
companies,
companySkills,
createDb,
+ documentAnnotationComments,
+ documentAnnotationThreads,
documentRevisions,
documents,
+ externalObjectMentions,
+ externalObjects,
heartbeatRunEvents,
heartbeatRuns,
+ issueAttachments,
issueApprovals,
issueComments,
issueDocuments,
@@ -68,6 +74,7 @@ async function deleteHeartbeatRunsAndWakeupsAfterActivityLogDrains(db: Db) {
await db.delete(activityLog);
await db.delete(heartbeatRunEvents);
try {
+ await db.delete(heartbeatRunEvents);
await db.delete(heartbeatRuns);
await db.delete(agentWakeupRequests);
return;
@@ -94,6 +101,17 @@ function agentActor(fixture: Fixture, agentId = fixture.agents.lowTrust.id): Exp
};
}
+function skillTestActor(fixture: Fixture, issueId = fixture.issues.assignedReview.id): Express.Request["actor"] {
+ return {
+ type: "agent",
+ agentId: fixture.agents.standard.id,
+ companyId: fixture.company.id,
+ runId: fixture.runs.standard.id,
+ source: "agent_jwt",
+ keyScope: { kind: "skill_test", issueId },
+ };
+}
+
function boardActor(fixture: Fixture): Express.Request["actor"] {
return {
type: "board",
@@ -309,6 +327,9 @@ async function seedLowTrustFixture(db: Db) {
issueSibling: canary("FLAG-ISSUE-SIBLING-7R4G"),
commentSibling: canary("FLAG-COMMENT-SIBLING-7R4G"),
documentSibling: canary("FLAG-DOC-SIBLING-7R4G"),
+ annotationSibling: canary("FLAG-ANNOTATION-SIBLING-7R4G"),
+ attachmentSibling: canary("FLAG-ATTACHMENT-SIBLING-7R4G"),
+ externalObjectSibling: canary("FLAG-EXTERNAL-OBJECT-SIBLING-7R4G"),
workProductSibling: canary("FLAG-WP-SIBLING-7R4G"),
approval: canary("FLAG-APPROVAL-7R4G"),
agentConfig: canary("FLAG-AGENTCFG-7R4G"),
@@ -479,6 +500,76 @@ async function seedLowTrustFixture(db: Db) {
documentId: siblingDoc!.id,
key: "canary",
});
+ const [siblingAnnotationThread] = await db.insert(documentAnnotationThreads).values({
+ companyId: company!.id,
+ issueId: siblingOutOfScope!.id,
+ documentId: siblingDoc!.id,
+ documentKey: "canary",
+ originalRevisionId: siblingRevision!.id,
+ originalRevisionNumber: 1,
+ currentRevisionId: siblingRevision!.id,
+ currentRevisionNumber: 1,
+ selectedText: "Sibling",
+ prefixText: "",
+ suffixText: " doc",
+ normalizedStart: 0,
+ normalizedEnd: 7,
+ markdownStart: 0,
+ markdownEnd: 7,
+ anchorSelector: {
+ quote: { exact: "Sibling", prefix: "", suffix: " doc" },
+ position: { normalizedStart: 0, normalizedEnd: 7, markdownStart: 0, markdownEnd: 7 },
+ },
+ createdByAgentId: standard!.id,
+ }).returning();
+ await db.insert(documentAnnotationComments).values({
+ companyId: company!.id,
+ threadId: siblingAnnotationThread!.id,
+ issueId: siblingOutOfScope!.id,
+ documentId: siblingDoc!.id,
+ body: canaries.annotationSibling,
+ authorType: "agent",
+ authorAgentId: standard!.id,
+ });
+ const [siblingAttachmentAsset] = await db.insert(assets).values({
+ companyId: company!.id,
+ provider: "local_disk",
+ objectKey: `issues/${siblingOutOfScope!.id}/attachment-canary.txt`,
+ contentType: "text/plain",
+ byteSize: canaries.attachmentSibling.length,
+ sha256: `sha256-${nonce}`,
+ originalFilename: "attachment-canary.txt",
+ createdByAgentId: standard!.id,
+ }).returning();
+ const [siblingAttachment] = await db.insert(issueAttachments).values({
+ companyId: company!.id,
+ issueId: siblingOutOfScope!.id,
+ assetId: siblingAttachmentAsset!.id,
+ }).returning();
+ const [siblingExternalObject] = await db.insert(externalObjects).values({
+ companyId: company!.id,
+ providerKey: "url",
+ objectType: "link",
+ externalId: `external-${nonce}`,
+ sanitizedCanonicalUrl: "https://example.invalid/redacted",
+ canonicalIdentityHash: `external-hash-${nonce}`,
+ displayKey: "EXT-1",
+ displayTitle: canaries.externalObjectSibling,
+ data: { canary: canaries.externalObjectSibling },
+ }).returning();
+ await db.insert(externalObjectMentions).values({
+ companyId: company!.id,
+ sourceIssueId: siblingOutOfScope!.id,
+ sourceKind: "description",
+ matchedTextRedacted: canaries.externalObjectSibling,
+ sanitizedDisplayUrl: "https://example.invalid/redacted",
+ canonicalIdentityHash: `external-hash-${nonce}`,
+ canonicalIdentity: { url: "https://example.invalid/redacted" },
+ objectId: siblingExternalObject!.id,
+ providerKey: "url",
+ detectorKey: "test",
+ objectType: "link",
+ });
await db.insert(issueWorkProducts).values({
companyId: company!.id,
projectId: outOfScopeProject!.id,
@@ -502,6 +593,12 @@ async function seedLowTrustFixture(db: Db) {
approvalId: approval!.id,
linkedByAgentId: standard!.id,
});
+ await db.insert(issueApprovals).values({
+ companyId: company!.id,
+ issueId: siblingOutOfScope!.id,
+ approvalId: approval!.id,
+ linkedByAgentId: standard!.id,
+ });
return {
company: company!,
@@ -509,6 +606,10 @@ async function seedLowTrustFixture(db: Db) {
projects: { allowed: allowedProject!, outOfScope: outOfScopeProject! },
issues: { reviewRoot: reviewRoot!, assignedReview: assignedReview!, sameBoundaryChild: sameBoundaryChild!, siblingOutOfScope: siblingOutOfScope! },
approvals: { issueLinkedCanary: approval! },
+ sensitiveRows: {
+ siblingAnnotationThreadId: siblingAnnotationThread!.id,
+ siblingAttachmentId: siblingAttachment!.id,
+ },
runs: { lowTrust: lowTrustRun!, standard: standardRun! },
canaries,
};
@@ -528,6 +629,12 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>
await db.delete(issueApprovals);
await db.delete(approvals);
await db.delete(issueWorkProducts);
+ await db.delete(issueAttachments);
+ await db.delete(assets);
+ await db.delete(externalObjectMentions);
+ await db.delete(externalObjects);
+ await db.delete(documentAnnotationComments);
+ await db.delete(documentAnnotationThreads);
await db.delete(issueDocuments);
await db.delete(documentRevisions);
await db.delete(documents);
@@ -751,6 +858,45 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>
id: "LT-08",
req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/documents/canary`),
},
+ {
+ id: "LT-08 revisions",
+ req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/documents/canary/revisions`),
+ },
+ {
+ id: "LT-08 annotations",
+ req: () => request(app)
+ .get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/documents/canary/annotations`)
+ .query({ includeComments: "true" }),
+ },
+ {
+ id: "LT-08 annotation thread",
+ req: () => request(app)
+ .get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/documents/canary/annotations/${fixture.sensitiveRows.siblingAnnotationThreadId}`),
+ },
+ {
+ id: "LT recovery actions",
+ req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/recovery-actions`),
+ },
+ {
+ id: "LT external objects",
+ req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/external-objects`),
+ },
+ {
+ id: "LT external object summary",
+ req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/external-object-summary`),
+ },
+ {
+ id: "LT approvals",
+ req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/approvals`),
+ },
+ {
+ id: "LT attachments",
+ req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/attachments`),
+ },
+ {
+ id: "LT attachment content",
+ req: () => request(app).get(`/api/attachments/${fixture.sensitiveRows.siblingAttachmentId}/content`),
+ },
{
id: "LT-15/16",
req: () => request(app).get(`/api/agents/${fixture.agents.cto.id}`),
@@ -822,6 +968,88 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>
expect(after.wakeups.length, attempt.id).toBe(before.wakeups.length);
expect(after.runs.length, attempt.id).toBe(before.runs.length);
}
+
+ const beforeBulkSummary = await snapshot(db);
+ const bulkSummary = await request(app)
+ .post(`/api/companies/${fixture.company.id}/issues/external-object-summaries`)
+ .send({ issueIds: [fixture.issues.siblingOutOfScope.id] });
+ expect(bulkSummary.status, JSON.stringify(bulkSummary.body)).toBe(200);
+ expect(bulkSummary.body.summaries).toEqual({});
+ expectNoCanary(bulkSummary.body, ...forbiddenMarkers);
+ const afterBulkSummary = await snapshot(db);
+ expect(afterBulkSummary.issues.length).toBe(beforeBulkSummary.issues.length);
+ expect(afterBulkSummary.comments.length).toBe(beforeBulkSummary.comments.length);
+ expect(afterBulkSummary.documents.length).toBe(beforeBulkSummary.documents.length);
+ expect(afterBulkSummary.workProducts.length).toBe(beforeBulkSummary.workProducts.length);
+ expect(afterBulkSummary.approvals.length).toBe(beforeBulkSummary.approvals.length);
+ expect(afterBulkSummary.relations.length).toBe(beforeBulkSummary.relations.length);
+ expect(afterBulkSummary.interactions.length).toBe(beforeBulkSummary.interactions.length);
+ expect(afterBulkSummary.wakeups.length).toBe(beforeBulkSummary.wakeups.length);
+ expect(afterBulkSummary.runs.length).toBe(beforeBulkSummary.runs.length);
+ });
+
+ it("denies skill-test scoped tokens on foreign issue-adjacent reads", async () => {
+ const fixture = await seedLowTrustFixture(db);
+ const app = createApp(db, skillTestActor(fixture));
+ const forbiddenMarkers = Object.values(fixture.canaries);
+
+ const ownIssue = await request(app).get(`/api/issues/${fixture.issues.assignedReview.id}`);
+ expect(ownIssue.status, JSON.stringify(ownIssue.body)).toBe(200);
+
+ const attempts = [
+ {
+ id: "skill-test attachments",
+ req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/attachments`),
+ },
+ {
+ id: "skill-test attachment content",
+ req: () => request(app).get(`/api/attachments/${fixture.sensitiveRows.siblingAttachmentId}/content`),
+ },
+ {
+ id: "skill-test document revisions",
+ req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/documents/canary/revisions`),
+ },
+ {
+ id: "skill-test annotations",
+ req: () => request(app)
+ .get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/documents/canary/annotations`)
+ .query({ includeComments: "true" }),
+ },
+ {
+ id: "skill-test annotation thread",
+ req: () => request(app)
+ .get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/documents/canary/annotations/${fixture.sensitiveRows.siblingAnnotationThreadId}`),
+ },
+ {
+ id: "skill-test approvals",
+ req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/approvals`),
+ },
+ {
+ id: "skill-test recovery actions",
+ req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/recovery-actions`),
+ },
+ {
+ id: "skill-test external objects",
+ req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/external-objects`),
+ },
+ {
+ id: "skill-test external object summary",
+ req: () => request(app).get(`/api/issues/${fixture.issues.siblingOutOfScope.id}/external-object-summary`),
+ },
+ ];
+
+ for (const attempt of attempts) {
+ const res = await attempt.req();
+ expect(res.status, `${attempt.id}: ${JSON.stringify(res.body)}`).toBe(403);
+ expectNoCanary(res.body, ...forbiddenMarkers);
+ }
+
+ const bulkSummary = await request(app)
+ .post(`/api/companies/${fixture.company.id}/issues/external-object-summaries`)
+ .send({ issueIds: [fixture.issues.siblingOutOfScope.id] });
+ expect(bulkSummary.status, JSON.stringify(bulkSummary.body)).toBe(200);
+ expect(bulkSummary.body.summaries).toEqual({});
+ expectNoCanary(bulkSummary.body, ...forbiddenMarkers);
});
it("counts blocked inbox issues with the low-trust boundary applied in the database", async () => {
@@ -864,7 +1092,14 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>
const lowTrustApp = createApp(db, agentActor(fixture));
const standardApp = createApp(db, agentActor(fixture, fixture.agents.standard.id));
const gateway = await createControlledGatewayServer();
- const heartbeat = heartbeatService(db);
+ const heartbeat = heartbeatService(db, {
+ runtimeEnv: {
+ ...process.env,
+ PAPERCLIP_IN_WORKTREE: "false",
+ PAPERCLIP_DATABASE_RESTORE_IN_PROGRESS: "false",
+ PAPERCLIP_RESTORE_IN_PROGRESS: "false",
+ },
+ });
try {
const comment = await request(lowTrustApp)
@@ -931,6 +1166,10 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>
waitTimeoutMs: 2_000,
},
}).where(eq(agents.id, fixture.agents.standard.id));
+ await db.update(heartbeatRuns).set({
+ status: "succeeded",
+ finishedAt: new Date("2026-05-14T12:02:00.000Z"),
+ }).where(eq(heartbeatRuns.id, fixture.runs.standard.id));
const run = await heartbeat.wakeup(fixture.agents.standard.id, {
source: "automation",
diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts
index 96f59ecdf2..e4420e0bb6 100644
--- a/server/src/__tests__/server-startup-feedback-export.test.ts
+++ b/server/src/__tests__/server-startup-feedback-export.test.ts
@@ -29,7 +29,12 @@ const {
const createDbMock = vi.fn(() => ({}) as never);
const detectPortMock = vi.fn(async (port: number) => port);
const deriveAuthTrustedOriginsMock = vi.fn(() => []);
+ const resolveHeartbeatSchedulingSuppressionMock = vi.fn(() => ({
+ suppressed: false,
+ reason: null,
+ }));
const heartbeatServiceMock = {
+ resolveSchedulingSuppression: resolveHeartbeatSchedulingSuppressionMock,
reapOrphanedRuns: vi.fn(async () => ({ reaped: 0, runIds: [] })),
promoteDueScheduledRetries: vi.fn(async () => ({ promoted: 0, runIds: [] })),
resumeQueuedRuns: vi.fn(async () => undefined),
@@ -62,10 +67,6 @@ const {
tickScheduledTriggers: vi.fn(async () => ({ triggered: 0 })),
};
const routineServiceFactoryMock = vi.fn(() => routineServiceMock);
- const resolveHeartbeatSchedulingSuppressionMock = vi.fn(() => ({
- suppressed: false,
- reason: null,
- }));
const feedbackExportServiceMock = {
flushPendingFeedbackTraces: vi.fn(async () => ({ attempted: 0, sent: 0, failed: 0 })),
};
diff --git a/server/src/agent-auth-jwt.ts b/server/src/agent-auth-jwt.ts
index 4cb25e97ab..140bcfafe4 100644
--- a/server/src/agent-auth-jwt.ts
+++ b/server/src/agent-auth-jwt.ts
@@ -1,4 +1,5 @@
import { createHmac, timingSafeEqual } from "node:crypto";
+import { normalizeAgentApiKeyScope, type AgentApiKeyScope } from "@paperclipai/shared";
import { resolvePaperclipInstanceId } from "./home-paths.js";
interface JwtHeader {
@@ -12,6 +13,7 @@ export interface LocalAgentJwtClaims {
adapter_type: string;
run_id: string;
responsible_user_id?: string | null;
+ key_scope?: AgentApiKeyScope | null;
iat: number;
exp: number;
iss?: string;
@@ -117,6 +119,7 @@ export function createLocalAgentJwt(
adapterType: string,
runId: string,
responsibleUserId?: string | null,
+ keyScope: AgentApiKeyScope = { kind: "standard" },
) {
const config = jwtConfig();
if (!config) return null;
@@ -128,6 +131,7 @@ export function createLocalAgentJwt(
adapter_type: adapterType,
run_id: runId,
responsible_user_id: responsibleUserId?.trim() || null,
+ ...(keyScope.kind === "standard" ? {} : { key_scope: keyScope }),
iat: now,
exp: now + config.ttlSeconds,
iss: config.issuer,
@@ -203,6 +207,9 @@ export function verifyLocalAgentJwt(token: string): LocalAgentJwtClaims | null {
? claims.responsible_user_id.trim()
: null
: undefined;
+ const keyScopeClaim = Object.hasOwn(claims, "key_scope")
+ ? normalizeAgentApiKeyScope(claims.key_scope)
+ : undefined;
const iat = typeof claims.iat === "number" ? claims.iat : null;
const exp = typeof claims.exp === "number" ? claims.exp : null;
if (!sub || !adapterType || !runId || !iat || !exp) return null;
@@ -231,6 +238,7 @@ export function verifyLocalAgentJwt(token: string): LocalAgentJwtClaims | null {
adapter_type: adapterType,
run_id: runId,
...(responsibleUserClaim !== undefined ? { responsible_user_id: responsibleUserClaim } : {}),
+ ...(keyScopeClaim !== undefined ? { key_scope: keyScopeClaim } : {}),
iat,
exp,
...(issuer ? { iss: issuer } : {}),
diff --git a/server/src/index.ts b/server/src/index.ts
index b1fe7e6f48..3056d02b86 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -45,7 +45,6 @@ import {
reconcileCloudUpstreamRunsOnStartup,
reconcileCodexLocalManagedHomesOnStartup,
reconcilePersistedRuntimeServicesOnStartup,
- resolveHeartbeatSchedulingSuppression,
routineService,
} from "./services/index.js";
import {
@@ -825,7 +824,7 @@ export async function startServer(): Promise<StartedServer> {
drainHeartbeatRunsForShutdown = heartbeat.drainRunningRunsForShutdown;
const environmentCustomImages = environmentCustomImageService(db as any, { pluginWorkerManager });
const routines = routineService(db as any, { pluginWorkerManager });
- const heartbeatSchedulingSuppression = resolveHeartbeatSchedulingSuppression();
+ const heartbeatSchedulingSuppression = await heartbeat.resolveSchedulingSuppression();
// Reap orphaned runs before timer ticks start so wakeups cannot coalesce
// into a dead "running" row during startup recovery.
@@ -916,6 +915,10 @@ export async function startServer(): Promise<StartedServer> {
}
heartbeatSchedulerInterval = setInterval(() => {
+ // Async so the suppression checks below can honor the override-aware
+ // resolver (e.g. worktree run-execution opt-in). The gated work is still
+ // wrapped in trackHeartbeatSchedulerWork with its own error handling.
+ void (async () => {
if (heartbeatSchedulerStopped) return;
const sweptRuntimeStatuses = heartbeat.sweepExpiredRuntimeStatuses();
if (sweptRuntimeStatuses > 0) {
@@ -925,7 +928,7 @@ export async function startServer(): Promise<StartedServer> {
);
}
- if (!resolveHeartbeatSchedulingSuppression().suppressed) {
+ if (!(await heartbeat.resolveSchedulingSuppression()).suppressed) {
trackHeartbeatSchedulerWork(heartbeat
.tickTimers(new Date())
.then((result) => {
@@ -962,7 +965,7 @@ export async function startServer(): Promise<StartedServer> {
}));
if (heartbeatSchedulerStopped) return;
- if (!resolveHeartbeatSchedulingSuppression().suppressed) {
+ if (!(await heartbeat.resolveSchedulingSuppression()).suppressed) {
// Periodically reap orphaned runs (5-min staleness threshold) and make sure
// persisted queued work is still being driven forward.
trackHeartbeatSchedulerWork(heartbeat
@@ -1019,6 +1022,7 @@ export async function startServer(): Promise<StartedServer> {
logger.error({ err }, "periodic heartbeat recovery failed");
}));
}
+ })();
}, config.heartbeatSchedulerIntervalMs);
}
diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts
index e174d1319a..c1b75c8a91 100644
--- a/server/src/middleware/auth.ts
+++ b/server/src/middleware/auth.ts
@@ -314,6 +314,7 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
agentId: claims.sub,
companyId: claims.company_id,
keyId: undefined,
+ keyScope: normalizeAgentApiKeyScope(claims.key_scope),
runId: claims.run_id,
onBehalfOfUserId,
onBehalfOfMemberships,
diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts
index d43481375b..d3bbdcee52 100644
--- a/server/src/routes/agents.ts
+++ b/server/src/routes/agents.ts
@@ -1433,6 +1433,7 @@ export function agentRoutes(
adapterType: string,
adapterConfig: Record<string, unknown>,
requestedDesiredSkills: AgentDesiredSkillEntry[] | undefined,
+ options: { tolerateUnknownDesiredSkills?: boolean } = {},
) {
if (!requestedDesiredSkills) {
return {
@@ -1443,17 +1444,25 @@ export function agentRoutes(
};
}
- const resolvedRequestedSkillEntries = await companySkills.resolveRequestedSkillEntries(
- companyId,
- requestedDesiredSkills,
- );
+ const { resolved: resolvedRequestedSkillEntries, unresolved: unresolvedDesiredSkillKeys } =
+ await companySkills.resolveRequestedSkillEntries(companyId, requestedDesiredSkills, {
+ tolerateUnknownReferences: options.tolerateUnknownDesiredSkills,
+ });
+ // Runtime materialization + version selection only ever consider skills that
+ // actually resolve to the company library; stale keys can't be materialized.
const runtimeSkillEntries = await companySkills.listRuntimeSkillEntries(companyId, {
materializeMissing: shouldMaterializeRuntimeSkillsForAdapter(adapterType),
versionSelections: skillVersionSelectionMap(resolvedRequestedSkillEntries),
});
- const desiredSkillEntries = resolvedRequestedSkillEntries.filter(
+ const resolvedDesiredSkillEntries = resolvedRequestedSkillEntries.filter(
(entry, index, entries) => entries.findIndex((candidate) => candidate.key === entry.key) === index,
);
+ // Preserve stale/unresolvable keys in the persisted desired set so they stay
+ // visible (and explicitly removable) instead of vanishing on the next save.
+ const desiredSkillEntries: AgentDesiredSkillEntry[] = [
+ ...resolvedDesiredSkillEntries,
+ ...unresolvedDesiredSkillKeys.map((key) => ({ key, versionId: null })),
+ ];
const desiredSkills = desiredSkillEntries.map((entry) => entry.key);
return {
@@ -1725,6 +1734,10 @@ export function agentRoutes(
agent.adapterType,
agent.adapterConfig as Record<string, unknown>,
requestedSkills,
+ // Toggling a resolvable skill must not fail just because the agent
+ // already carries stale desired keys (e.g. a skill removed from the
+ // library). Preserve those keys so they remain visible/removable.
+ { tolerateUnknownDesiredSkills: true },
);
if (!desiredSkills || !desiredSkillEntries || !runtimeSkillEntries) {
throw unprocessable("Skill sync requires desiredSkills.");
diff --git a/server/src/routes/company-skills.ts b/server/src/routes/company-skills.ts
index 78111febfc..a5eb2545a9 100644
--- a/server/src/routes/company-skills.ts
+++ b/server/src/routes/company-skills.ts
@@ -5,6 +5,7 @@ import {
companySkillCommentCreateSchema,
companySkillCommentUpdateSchema,
companySkillCreateSchema,
+ companySkillFileDeleteSchema,
companySkillFileUpdateSchema,
companySkillForkSchema,
companySkillImportSchema,
@@ -13,12 +14,18 @@ import {
companySkillListQuerySchema,
companySkillProjectScanRequestSchema,
companySkillResetSchema,
+ companySkillTestInputCreateSchema,
+ companySkillTestInputUpdateSchema,
+ companySkillTestRunTemplateCreateSchema,
+ companySkillTestRunTemplateUpdateSchema,
+ companySkillTestRunCreateSchema,
+ companySkillTestRunListQuerySchema,
companySkillUpdateSchema,
companySkillVersionCreateSchema,
} from "@paperclipai/shared";
import { trackSkillImported } from "@paperclipai/shared/telemetry";
import { validate } from "../middleware/validate.js";
-import { accessService, agentService, companySkillService, logActivity } from "../services/index.js";
+import { accessService, agentService, companySkillService, heartbeatService, issueService, logActivity } from "../services/index.js";
import {
getCatalogSkillOrThrow,
listCatalogSkillsOrEmpty,
@@ -41,6 +48,8 @@ export function companySkillRoutes(db: Db) {
const agents = agentService(db);
const access = accessService(db);
const svc = companySkillService(db);
+ const issues = issueService(db);
+ const heartbeat = heartbeatService(db);
function canCreateSkills(agent: { permissions: Record<string, unknown> | null | undefined }) {
if (!agent.permissions || typeof agent.permissions !== "object") return true;
@@ -122,6 +131,32 @@ export function companySkillRoutes(db: Db) {
throw forbidden("Missing permission: skills:create");
}
+ async function assertCanStartSkillTestRuns(req: Request, companyId: string) {
+ assertCompanyAccess(req, companyId);
+
+ if (req.actor.type === "board") {
+ if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return;
+ const allowed = await access.canUser(companyId, req.actor.userId, "tasks:assign");
+ if (!allowed) {
+ throw forbidden("Missing permission: tasks:assign");
+ }
+ return;
+ }
+
+ if (!req.actor.agentId) {
+ throw forbidden("Agent authentication required");
+ }
+
+ const actorAgent = await agents.getById(req.actor.agentId);
+ if (!actorAgent || actorAgent.companyId !== companyId) {
+ throw forbidden("Agent key cannot access another company");
+ }
+ const allowedByGrant = await access.hasPermission(companyId, "agent", actorAgent.id, "tasks:assign");
+ if (!allowedByGrant) {
+ throw forbidden("Missing permission: tasks:assign");
+ }
+ }
+
router.get("/skills/catalog", async (req, res) => {
assertAuthenticated(req);
const query = catalogSkillListQuerySchema.parse({
@@ -157,6 +192,10 @@ export function companySkillRoutes(db: Db) {
...queryStringArray(req.query["categories[]"]),
],
scope: firstQueryString(req.query.scope),
+ include: [
+ ...queryStringArray(req.query.include),
+ ...queryStringArray(req.query["include[]"]),
+ ],
}));
res.json(result);
});
@@ -211,6 +250,358 @@ export function companySkillRoutes(db: Db) {
res.json(result);
});
+ router.get("/companies/:companyId/skills/:skillId/test-inputs", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ assertCompanyAccess(req, companyId);
+ res.json(await svc.listTestInputs(companyId, skillId));
+ });
+
+ router.post(
+ "/companies/:companyId/skills/:skillId/test-inputs",
+ validate(companySkillTestInputCreateSchema),
+ 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.createTestInput(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_test_input_created",
+ entityType: "company_skill_test_input",
+ entityId: result.id,
+ details: { skillId, name: result.name },
+ });
+ res.status(201).json(result);
+ },
+ );
+
+ router.patch(
+ "/companies/:companyId/skills/:skillId/test-inputs/:inputId",
+ validate(companySkillTestInputUpdateSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ const inputId = req.params.inputId as string;
+ await assertCanMutateCompanySkills(req, companyId);
+ const result = await svc.updateTestInput(companyId, skillId, inputId, req.body);
+ if (!result) {
+ res.status(404).json({ error: "Test input not found" });
+ return;
+ }
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_test_input_updated",
+ entityType: "company_skill_test_input",
+ entityId: result.id,
+ details: { skillId, changedKeys: Object.keys(req.body).sort() },
+ });
+ res.json(result);
+ },
+ );
+
+ router.delete("/companies/:companyId/skills/:skillId/test-inputs/:inputId", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ const inputId = req.params.inputId as string;
+ await assertCanMutateCompanySkills(req, companyId);
+ const result = await svc.deleteTestInput(companyId, skillId, inputId);
+ if (!result) {
+ res.status(404).json({ error: "Test input not found" });
+ return;
+ }
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_test_input_deleted",
+ entityType: "company_skill_test_input",
+ entityId: result.id,
+ details: { skillId, name: result.name },
+ });
+ res.json(result);
+ });
+
+ router.get("/companies/:companyId/skill-test-run-templates", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ assertCompanyAccess(req, companyId);
+ res.json(await svc.listTestRunTemplates(companyId));
+ });
+
+ router.post(
+ "/companies/:companyId/skill-test-run-templates",
+ validate(companySkillTestRunTemplateCreateSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ await assertCanMutateCompanySkills(req, companyId);
+ const result = await svc.createTestRunTemplate(companyId, 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_test_run_template_created",
+ entityType: "company_skill_test_run_template",
+ entityId: result.id,
+ details: { name: result.name },
+ });
+ res.status(201).json(result);
+ },
+ );
+
+ router.patch(
+ "/companies/:companyId/skill-test-run-templates/:templateId",
+ validate(companySkillTestRunTemplateUpdateSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const templateId = req.params.templateId as string;
+ await assertCanMutateCompanySkills(req, companyId);
+ const result = await svc.updateTestRunTemplate(companyId, templateId, req.body, skillActor(req));
+ if (!result) {
+ res.status(404).json({ error: "Test run template not found" });
+ return;
+ }
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_test_run_template_updated",
+ entityType: "company_skill_test_run_template",
+ entityId: result.id,
+ details: { changedKeys: Object.keys(req.body).sort() },
+ });
+ res.json(result);
+ },
+ );
+
+ router.delete("/companies/:companyId/skill-test-run-templates/:templateId", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const templateId = req.params.templateId as string;
+ await assertCanMutateCompanySkills(req, companyId);
+ const result = await svc.deleteTestRunTemplate(companyId, templateId);
+ if (!result) {
+ res.status(404).json({ error: "Test run template not found" });
+ return;
+ }
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_test_run_template_deleted",
+ entityType: "company_skill_test_run_template",
+ entityId: result.id,
+ details: { name: result.name },
+ });
+ res.json(result);
+ });
+
+ router.get("/companies/:companyId/skills/:skillId/test-runs", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ assertCompanyAccess(req, companyId);
+ const query = companySkillTestRunListQuerySchema.parse({
+ inputId: firstQueryString(req.query.inputId),
+ });
+ res.json(await svc.listTestRuns(companyId, skillId, query));
+ });
+
+ router.get("/companies/:companyId/skills/:skillId/test-runs/:runId", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ const runId = req.params.runId as string;
+ assertCompanyAccess(req, companyId);
+ const result = await svc.getTestRunDetail(companyId, skillId, runId);
+ if (!result) {
+ res.status(404).json({ error: "Test run not found" });
+ return;
+ }
+ res.json(result);
+ });
+
+ router.post(
+ "/companies/:companyId/skills/:skillId/test-runs",
+ validate(companySkillTestRunCreateSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ await assertCanStartSkillTestRuns(req, companyId);
+ const actor = getActorInfo(req);
+ const result = await svc.createTestRun(companyId, skillId, req.body, skillActor(req), {
+ createHarnessIssue: async (harnessIssue) => {
+ const created = await issues.create(companyId, {
+ ...harnessIssue,
+ priority: "medium",
+ createdByAgentId: actor.agentId,
+ createdByUserId: actor.actorType === "user" ? actor.actorId : null,
+ actorRunId: actor.runId,
+ });
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "issue.created",
+ entityType: "issue",
+ entityId: created.id,
+ details: {
+ title: created.title,
+ identifier: created.identifier,
+ harnessKind: "skill_test",
+ source: "company_skill_test_run",
+ skillId,
+ },
+ });
+ return { id: created.id };
+ },
+ wakeHarnessIssue: async (issueId, agentId) => heartbeat.wakeup(agentId, {
+ source: "assignment",
+ triggerDetail: "system",
+ reason: "skill_test_run_created",
+ payload: { issueId, skillId },
+ requestedByActorType: actor.actorType,
+ requestedByActorId: actor.actorId,
+ contextSnapshot: { issueId, source: "company.skill_test_run" },
+ }),
+ cleanupHarnessIssue: async (issueId) => {
+ const issue = await issues.getById(issueId);
+ if (!issue || issue.companyId !== companyId) return;
+ await issues.update(issueId, {
+ status: "cancelled",
+ hiddenAt: new Date(),
+ actorAgentId: actor.agentId ?? null,
+ actorUserId: actor.actorType === "user" ? actor.actorId : null,
+ });
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_test_harness_issue_cleaned_up",
+ entityType: "issue",
+ entityId: issueId,
+ details: { skillId },
+ });
+ },
+ });
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_test_run_created",
+ entityType: "company_skill_test_run",
+ entityId: result.id,
+ details: {
+ skillId,
+ inputId: result.inputId,
+ skillVersionId: result.skillVersionId,
+ agentId: result.agentId,
+ issueId: result.issueId,
+ },
+ });
+ res.status(201).json(result);
+ },
+ );
+
+ router.post("/companies/:companyId/skills/:skillId/test-runs/:runId/cancel", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ const runId = req.params.runId as string;
+ await assertCanStartSkillTestRuns(req, companyId);
+ const actor = getActorInfo(req);
+ const result = await svc.cancelTestRun(companyId, skillId, runId, {
+ cancelHarnessIssue: async (issueId) => {
+ const issue = await issues.getById(issueId);
+ if (!issue || issue.companyId !== companyId) return;
+ if (issue.executionRunId) {
+ await heartbeat.cancelRun(issue.executionRunId, "Cancelled by skill test run request");
+ }
+ if (issue.status !== "done" && issue.status !== "cancelled") {
+ await issues.update(issueId, {
+ status: "cancelled",
+ actorAgentId: actor.agentId ?? null,
+ actorUserId: actor.actorType === "user" ? actor.actorId : null,
+ });
+ }
+ },
+ });
+ if (!result) {
+ res.status(404).json({ error: "Test run not found" });
+ return;
+ }
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_test_run_cancelled",
+ entityType: "company_skill_test_run",
+ entityId: result.id,
+ details: { skillId, issueId: result.issueId },
+ });
+ res.json(result);
+ });
+
+ router.delete("/companies/:companyId/skills/:skillId/test-runs/:runId", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ const runId = req.params.runId as string;
+ await assertCanStartSkillTestRuns(req, companyId);
+ const actor = getActorInfo(req);
+ const result = await svc.deleteTestRun(companyId, skillId, runId, {
+ hideHarnessIssue: async (issueId) => {
+ const issue = await issues.getById(issueId);
+ if (!issue || issue.companyId !== companyId) return;
+ await issues.update(issueId, {
+ hiddenAt: new Date(),
+ actorAgentId: actor.agentId ?? null,
+ actorUserId: actor.actorType === "user" ? actor.actorId : null,
+ });
+ },
+ });
+ if (!result) {
+ res.status(404).json({ error: "Test run not found" });
+ return;
+ }
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_test_run_deleted",
+ entityType: "company_skill_test_run",
+ entityId: result.id,
+ details: { skillId, issueId: result.issueId },
+ });
+ res.json(result);
+ });
+
router.post(
"/companies/:companyId/skills/:skillId/versions",
validate(companySkillVersionCreateSchema),
@@ -503,6 +894,36 @@ export function companySkillRoutes(db: Db) {
},
);
+ router.delete(
+ "/companies/:companyId/skills/:skillId/files",
+ validate(companySkillFileDeleteSchema),
+ 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.deleteFile(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_file_deleted",
+ entityType: "company_skill",
+ entityId: skillId,
+ details: {
+ path: result.path,
+ target: result.target,
+ deletedPaths: result.deletedPaths,
+ },
+ });
+
+ res.json(result);
+ },
+ );
+
router.post(
"/companies/:companyId/skills/import",
validate(companySkillImportSchema),
diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts
index 4954b16142..a9ba840c58 100644
--- a/server/src/routes/issues.ts
+++ b/server/src/routes/issues.ts
@@ -92,6 +92,7 @@ import * as serviceIndex from "../services/index.js";
import {
accessService,
agentService,
+ companySkillService,
companyService,
companySearchService,
executionWorkspaceService,
@@ -2051,6 +2052,7 @@ export function issueRoutes(
const executionWorkspacesSvc = executionWorkspaceServiceDirect(db);
const workProductsSvc = workProductService(db);
const documentsSvc = documentService(db);
+ const companySkillsSvc = companySkillService(db);
const documentAnnotationsSvc = documentAnnotationService(db);
const issueReferencesSvc = issueReferenceService(db);
const issueThreadInteractionsSvc = issueThreadInteractionService(db);
@@ -2805,6 +2807,10 @@ export function issueRoutes(
return req.actor.type === "agent" && req.actor.source === "agent_key" && req.actor.keyScope?.kind === "task_bridge";
}
+ function isSkillTestScopedActor(req: Request) {
+ return req.actor.type === "agent" && req.actor.keyScope?.kind === "skill_test";
+ }
+
function taskBridgeOriginForActor(req: Request) {
return isTaskBridgeKeyActor(req) && req.actor.keyId
? { originKind: "task_bridge", originId: req.actor.keyId }
@@ -4814,6 +4820,7 @@ export function issueRoutes(
return;
}
assertCompanyAccess(req, issue.companyId);
+ if (!(await assertIssueReadAllowed(req, res, issue))) return;
const active = await revalidateActiveSourceRecoveryForRead({
issue,
trigger: "read_projection",
@@ -5015,6 +5022,7 @@ export function issueRoutes(
return;
}
assertCompanyAccess(req, issue.companyId);
+ if (!(await assertIssueReadAllowed(req, res, issue))) return;
const objects = await externalObjectsSvc.listForIssue(issue.id);
res.json(objects);
});
@@ -5027,6 +5035,7 @@ export function issueRoutes(
return;
}
assertCompanyAccess(req, issue.companyId);
+ if (!(await assertIssueReadAllowed(req, res, issue))) return;
const summary = await externalObjectsSvc.getIssueSummary(issue.id);
res.json(summary);
});
@@ -5034,7 +5043,23 @@ export function issueRoutes(
router.post("/companies/:companyId/issues/external-object-summaries", validate(externalObjectSummariesSchema), async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
- const summaries = await externalObjectsSvc.getIssueSummaries(companyId, req.body.issueIds);
+ const requestedIssueIds = [...new Set(req.body.issueIds as string[])];
+ const candidateIssues = requestedIssueIds.length > 0
+ ? await db
+ .select({
+ id: issueRows.id,
+ companyId: issueRows.companyId,
+ projectId: issueRows.projectId,
+ parentId: issueRows.parentId,
+ assigneeAgentId: issueRows.assigneeAgentId,
+ assigneeUserId: issueRows.assigneeUserId,
+ status: issueRows.status,
+ })
+ .from(issueRows)
+ .where(and(eq(issueRows.companyId, companyId), inArray(issueRows.id, requestedIssueIds)))
+ : [];
+ const readableIssueIds = (await filterIssuesForActor(req, candidateIssues)).map((issue) => issue.id);
+ const summaries = await externalObjectsSvc.getIssueSummaries(companyId, readableIssueIds);
res.json({ summaries: Object.fromEntries(summaries) });
});
@@ -5123,6 +5148,7 @@ export function issueRoutes(
return;
}
assertCompanyAccess(req, issue.companyId);
+ if (!(await assertIssueReadAllowed(req, res, issue))) return;
const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase());
if (!keyParsed.success) {
res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues });
@@ -5199,6 +5225,7 @@ export function issueRoutes(
return;
}
assertCompanyAccess(req, issue.companyId);
+ if (!(await assertIssueReadAllowed(req, res, issue))) return;
const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase());
if (!keyParsed.success) {
res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues });
@@ -5549,6 +5576,7 @@ export function issueRoutes(
return;
}
assertCompanyAccess(req, issue.companyId);
+ if (!(await assertIssueReadAllowed(req, res, issue))) return;
const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase());
if (!keyParsed.success) {
res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues });
@@ -6187,6 +6215,7 @@ export function issueRoutes(
}
assertCompanyAccess(req, issue.companyId);
if (await assertLowTrustControlPlaneDenied(req, res, issue.companyId, issue)) return;
+ if (!(await assertIssueReadAllowed(req, res, issue))) return;
const approvals = await issueApprovalsSvc.listApprovalsForIssue(id);
res.json(approvals);
});
@@ -6259,6 +6288,16 @@ export function issueRoutes(
router.post("/companies/:companyId/issues", applyCreateIssueStatusDefault, validate(createIssueSchema), async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
+ if (isSkillTestScopedActor(req)) {
+ res.status(403).json({
+ error: "Skill-test run tokens cannot create issues.",
+ details: {
+ scopedIssueId: req.actor.keyScope?.kind === "skill_test" ? req.actor.keyScope.issueId : null,
+ securityPrinciples: ["Least Privilege", "Complete Mediation", "Fail Securely"],
+ },
+ });
+ return;
+ }
if (await assertLowTrustControlPlaneDenied(req, res, companyId, null)) return;
assertNoAgentHostWorkspaceCommandMutation(req, collectIssueWorkspaceCommandPaths(req.body));
const sanitizedBody = await sanitizeIssueCreateAttribution(db, req, res, companyId, req.body, {
@@ -7629,6 +7668,36 @@ export function issueRoutes(
}
}
+ if (
+ issue.harnessKind === "skill_test" &&
+ existing.status !== issue.status &&
+ (issue.status === "done" || issue.status === "cancelled")
+ ) {
+ const completedRun = await companySkillsSvc.completeTestRunForIssue({
+ companyId: issue.companyId,
+ issueId: issue.id,
+ outcome: issue.status === "done" ? "succeeded" : "cancelled",
+ error: issue.status === "cancelled" ? "Harness issue was cancelled" : null,
+ });
+ if (completedRun) {
+ await logActivity(db, {
+ companyId: issue.companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_test_run_completed",
+ entityType: "company_skill_test_run",
+ entityId: completedRun.id,
+ details: {
+ issueId: issue.id,
+ status: completedRun.status,
+ outputDocumentKey: completedRun.outputDocumentKey,
+ },
+ });
+ }
+ }
+
let comment = null;
if (commentBody) {
const commentReferenceSummaryBefore = updateReferenceSummaryAfter
@@ -8118,6 +8187,9 @@ export function issueRoutes(
if (req.actor.type === "agent" && !checkoutRunId) return;
const updated = await svc.checkout(id, req.body.agentId, req.body.expectedStatuses, checkoutRunId);
const actor = getActorInfo(req);
+ if (updated?.harnessKind === "skill_test") {
+ await companySkillsSvc.markTestRunRunning(updated.companyId, updated.id);
+ }
await logActivity(db, {
companyId: issue.companyId,
@@ -9591,6 +9663,7 @@ export function issueRoutes(
return;
}
assertCompanyAccess(req, issue.companyId);
+ if (!(await assertIssueReadAllowed(req, res, issue))) return;
const attachments = await svc.listAttachments(issueId);
res.json(attachments.map(withContentPath));
});
@@ -9695,6 +9768,12 @@ export function issueRoutes(
return;
}
assertCompanyAccess(req, attachment.companyId);
+ const issue = await svc.getById(attachment.issueId);
+ if (!issue) {
+ res.status(404).json({ error: "Issue not found" });
+ return;
+ }
+ if (!(await assertIssueReadAllowed(req, res, issue))) return;
const contentLength = attachment.byteSize;
const range = parseAttachmentRangeHeader(
diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts
index b37ee0508f..8c34c562ed 100644
--- a/server/src/routes/openapi.ts
+++ b/server/src/routes/openapi.ts
@@ -89,9 +89,16 @@ import {
startEnvironmentCustomImageSetupSessionSchema,
// Company skills
companySkillCreateSchema,
+ companySkillFileDeleteSchema,
companySkillFileUpdateSchema,
companySkillImportSchema,
companySkillProjectScanRequestSchema,
+ companySkillTestInputCreateSchema,
+ companySkillTestInputUpdateSchema,
+ companySkillTestRunCreateSchema,
+ companySkillTestRunListQuerySchema,
+ companySkillTestRunTemplateCreateSchema,
+ companySkillTestRunTemplateUpdateSchema,
// Issue tree
createIssueTreeHoldSchema,
previewIssueTreeControlSchema,
@@ -3522,6 +3529,153 @@ registry.registerPath({
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },
});
+registry.registerPath({
+ method: "delete",
+ path: "/api/companies/{companyId}/skills/{skillId}/files",
+ tags: ["skills"],
+ summary: "Delete a skill file or folder",
+ request: {
+ params: z.object({ companyId: z.string(), skillId: z.string() }),
+ body: jsonBody(companySkillFileDeleteSchema),
+ },
+ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },
+});
+
+registry.registerPath({
+ method: "get",
+ path: "/api/companies/{companyId}/skills/{skillId}/test-inputs",
+ tags: ["skills"],
+ summary: "List skill test inputs",
+ request: { params: z.object({ companyId: z.string(), skillId: z.string() }) },
+ responses: { 200: r.ok(), 401: r.unauthorized },
+});
+
+registry.registerPath({
+ method: "post",
+ path: "/api/companies/{companyId}/skills/{skillId}/test-inputs",
+ tags: ["skills"],
+ summary: "Create a skill test input",
+ request: {
+ params: z.object({ companyId: z.string(), skillId: z.string() }),
+ body: jsonBody(companySkillTestInputCreateSchema),
+ },
+ responses: { 201: r.ok(), 400: r.badRequest, 401: r.unauthorized },
+});
+
+registry.registerPath({
+ method: "patch",
+ path: "/api/companies/{companyId}/skills/{skillId}/test-inputs/{inputId}",
+ tags: ["skills"],
+ summary: "Update a skill test input",
+ request: {
+ params: z.object({ companyId: z.string(), skillId: z.string(), inputId: z.string() }),
+ body: jsonBody(companySkillTestInputUpdateSchema),
+ },
+ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 404: r.notFound },
+});
+
+registry.registerPath({
+ method: "delete",
+ path: "/api/companies/{companyId}/skills/{skillId}/test-inputs/{inputId}",
+ tags: ["skills"],
+ summary: "Delete a skill test input",
+ request: { params: z.object({ companyId: z.string(), skillId: z.string(), inputId: z.string() }) },
+ responses: { 200: r.ok(), 401: r.unauthorized, 404: r.notFound },
+});
+
+registry.registerPath({
+ method: "get",
+ path: "/api/companies/{companyId}/skill-test-run-templates",
+ tags: ["skills"],
+ summary: "List skill test-run templates",
+ request: { params: z.object({ companyId: z.string() }) },
+ responses: { 200: r.ok(), 401: r.unauthorized },
+});
+
+registry.registerPath({
+ method: "post",
+ path: "/api/companies/{companyId}/skill-test-run-templates",
+ tags: ["skills"],
+ summary: "Create a skill test-run template",
+ request: {
+ params: z.object({ companyId: z.string() }),
+ body: jsonBody(companySkillTestRunTemplateCreateSchema),
+ },
+ responses: { 201: r.ok(), 400: r.badRequest, 401: r.unauthorized },
+});
+
+registry.registerPath({
+ method: "patch",
+ path: "/api/companies/{companyId}/skill-test-run-templates/{templateId}",
+ tags: ["skills"],
+ summary: "Update a skill test-run template",
+ request: {
+ params: z.object({ companyId: z.string(), templateId: z.string() }),
+ body: jsonBody(companySkillTestRunTemplateUpdateSchema),
+ },
+ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 404: r.notFound },
+});
+
+registry.registerPath({
+ method: "delete",
+ path: "/api/companies/{companyId}/skill-test-run-templates/{templateId}",
+ tags: ["skills"],
+ summary: "Delete a skill test-run template",
+ request: { params: z.object({ companyId: z.string(), templateId: z.string() }) },
+ responses: { 200: r.ok(), 401: r.unauthorized, 404: r.notFound },
+});
+
+registry.registerPath({
+ method: "get",
+ path: "/api/companies/{companyId}/skills/{skillId}/test-runs",
+ tags: ["skills"],
+ summary: "List skill test runs",
+ request: {
+ params: z.object({ companyId: z.string(), skillId: z.string() }),
+ query: companySkillTestRunListQuerySchema,
+ },
+ responses: { 200: r.ok(), 401: r.unauthorized, 422: r.unprocessable },
+});
+
+registry.registerPath({
+ method: "get",
+ path: "/api/companies/{companyId}/skills/{skillId}/test-runs/{runId}",
+ tags: ["skills"],
+ summary: "Get a skill test run",
+ request: { params: z.object({ companyId: z.string(), skillId: z.string(), runId: z.string() }) },
+ responses: { 200: r.ok(), 401: r.unauthorized, 404: r.notFound },
+});
+
+registry.registerPath({
+ method: "post",
+ path: "/api/companies/{companyId}/skills/{skillId}/test-runs",
+ tags: ["skills"],
+ summary: "Create a skill test run",
+ request: {
+ params: z.object({ companyId: z.string(), skillId: z.string() }),
+ body: jsonBody(companySkillTestRunCreateSchema),
+ },
+ responses: { 201: r.ok(), 400: r.badRequest, 401: r.unauthorized },
+});
+
+registry.registerPath({
+ method: "post",
+ path: "/api/companies/{companyId}/skills/{skillId}/test-runs/{runId}/cancel",
+ tags: ["skills"],
+ summary: "Cancel a skill test run",
+ request: { params: z.object({ companyId: z.string(), skillId: z.string(), runId: z.string() }) },
+ responses: { 200: r.ok(), 401: r.unauthorized, 404: r.notFound },
+});
+
+registry.registerPath({
+ method: "delete",
+ path: "/api/companies/{companyId}/skills/{skillId}/test-runs/{runId}",
+ tags: ["skills"],
+ summary: "Delete a skill test run",
+ request: { params: z.object({ companyId: z.string(), skillId: z.string(), runId: z.string() }) },
+ responses: { 200: r.ok(), 401: r.unauthorized, 404: r.notFound },
+});
+
registry.registerPath({
method: "post",
path: "/api/companies/{companyId}/skills/import",
diff --git a/server/src/routes/user-profiles.ts b/server/src/routes/user-profiles.ts
index 7b50e94a36..11d99273d9 100644
--- a/server/src/routes/user-profiles.ts
+++ b/server/src/routes/user-profiles.ts
@@ -17,6 +17,7 @@ import type {
UserProfileWindowStats,
} from "@paperclipai/shared";
import { notFound } from "../errors.js";
+import { visibleIssueCondition } from "../services/issue-visibility.js";
import { assertCompanyAccess } from "./authz.js";
type CompanyUserRow = {
@@ -147,7 +148,7 @@ async function loadWindowStats(
assignedOpenIssues: sql<number>`count(distinct case when ${issues.assigneeUserId} = ${userId} and ${issues.status} in (${sql.join(openStatuses.map((status) => sql`${status}`), sql`, `)}) then ${issues.id} end)::int`,
})
.from(issues)
- .where(and(eq(issues.companyId, companyId), isNull(issues.hiddenAt)));
+ .where(and(eq(issues.companyId, companyId), visibleIssueCondition()));
const commentConditions = [
eq(issueComments.companyId, companyId),
@@ -252,7 +253,7 @@ async function loadDailyStats(db: Db, companyId: string, userId: string): Promis
.where(
and(
eq(issues.companyId, companyId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
eq(issues.status, "done"),
gte(issues.completedAt, firstDay),
userIssueInvolvementSql(companyId, userId),
@@ -333,7 +334,7 @@ export function userProfileRoutes(db: Db) {
.where(
and(
eq(issues.companyId, companyId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
userIssueInvolvementSql(companyId, userId),
),
)
diff --git a/server/src/services/activity.ts b/server/src/services/activity.ts
index b7f80dca0d..a9c6f592dd 100644
--- a/server/src/services/activity.ts
+++ b/server/src/services/activity.ts
@@ -16,6 +16,7 @@ import {
} from "@paperclipai/db";
import { ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY } from "@paperclipai/shared";
import { logger } from "../middleware/logger.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
import { classifyRunLiveness } from "./run-liveness.js";
export interface ActivityFilters {
@@ -354,7 +355,7 @@ export function activityService(db: Db) {
...conditions,
or(
sql`${activityLog.entityType} != 'issue'`,
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
),
),
)
@@ -543,7 +544,7 @@ export function activityService(db: Db) {
eq(activityLog.companyId, run.companyId),
eq(activityLog.runId, runId),
eq(activityLog.entityType, "issue"),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
),
)
.orderBy(issueIdAsText);
@@ -569,7 +570,7 @@ export function activityService(db: Db) {
and(
eq(issues.companyId, run.companyId),
eq(issues.id, contextIssueId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
),
)
.then((rows) => rows[0] ?? null);
diff --git a/server/src/services/adapter-registry-bootstrap.reconcile.test.ts b/server/src/services/adapter-registry-bootstrap.reconcile.test.ts
index fb406926d0..1e32e3575f 100644
--- a/server/src/services/adapter-registry-bootstrap.reconcile.test.ts
+++ b/server/src/services/adapter-registry-bootstrap.reconcile.test.ts
@@ -12,6 +12,7 @@ vi.mock("../adapters/registry.js", async (orig) => ({
}));
vi.mock("./adapter-plugin-store.js", () => ({
+ listAdapterPlugins: () => [],
setAdapterDisabled: (type: string, disabled: boolean) => setAdapterDisabled(type, disabled),
}));
diff --git a/server/src/services/authorization.ts b/server/src/services/authorization.ts
index dccd0ea6c1..247b3d5cdc 100644
--- a/server/src/services/authorization.ts
+++ b/server/src/services/authorization.ts
@@ -11,7 +11,13 @@ import {
principalPermissionGrants,
projects,
} from "@paperclipai/db";
-import type { AgentApiKeyScope, PermissionKey, PrincipalType, TaskBridgeAgentKeyScope } from "@paperclipai/shared";
+import type {
+ AgentApiKeyScope,
+ PermissionKey,
+ PrincipalType,
+ SkillTestAgentKeyScope,
+ TaskBridgeAgentKeyScope,
+} from "@paperclipai/shared";
import { LOW_TRUST_REVIEW_PRESET, extractAgentMentionIds, type LowTrustBoundary } from "@paperclipai/shared";
import {
LOW_TRUST_ISSUE_ANCESTRY_MAX_DEPTH,
@@ -1070,6 +1076,48 @@ export function authorizationService(db: Db) {
return denyBridge("Task bridge key cannot use this API action.");
}
+ function decideSkillTestAccess(input: {
+ action: AuthorizationAction;
+ resource: AuthorizationResource;
+ scope: SkillTestAgentKeyScope;
+ }): AuthorizationDecision | null {
+ const denySkillTest = (explanation: string) =>
+ deny({
+ action: input.action,
+ reason: "deny_scope",
+ explanation,
+ });
+ const allowSkillTest = (explanation: string) =>
+ allow({
+ action: input.action,
+ reason: "allow_explicit_grant",
+ explanation,
+ });
+
+ if (
+ input.action === "company_scope:read" ||
+ input.action === "agent:read" ||
+ input.action === "agent:wake" ||
+ input.action === "project:read" ||
+ input.action === "runtime:manage" ||
+ input.action === "secrets:read" ||
+ input.action === "tasks:assign"
+ ) {
+ return denySkillTest("Skill-test run tokens cannot use company-wide, peer-agent, project, runtime, secret, or task-create APIs.");
+ }
+
+ if (input.action === "issue:read" || input.action === "issue:comment" || input.action === "issue:mutate") {
+ if (input.resource.type !== "issue") {
+ return denySkillTest("Skill-test issue access requires an issue resource.");
+ }
+ return input.resource.issueId === input.scope.issueId
+ ? allowSkillTest("Allowed for the scoped skill-test issue.")
+ : denySkillTest("Skill-test run token can only access its own harness issue.");
+ }
+
+ return denySkillTest("Skill-test run token cannot use this API action.");
+ }
+
async function assignmentTargetIsInCompany(resource: AuthorizationResource) {
if (resource.type !== "issue") return true;
if (resource.assigneeAgentId) {
@@ -1452,6 +1500,15 @@ export function authorizationService(db: Db) {
});
}
+ if (input.actor.keyScope?.kind === "skill_test") {
+ const skillTestDecision = decideSkillTestAccess({
+ action: input.action,
+ resource: input.resource,
+ scope: input.actor.keyScope,
+ });
+ if (skillTestDecision) return skillTestDecision;
+ }
+
if (input.actor.source === "agent_key" && input.actor.keyScope?.kind === "task_bridge") {
const keyId = input.actor.keyId ?? null;
if (!keyId) {
diff --git a/server/src/services/company-search.ts b/server/src/services/company-search.ts
index 6c2d9479e9..37401c550f 100644
--- a/server/src/services/company-search.ts
+++ b/server/src/services/company-search.ts
@@ -19,6 +19,7 @@ import {
type CompanySearchSnippet,
} from "@paperclipai/shared";
import { companyArtifactsService } from "./company-artifacts.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
const MIN_TOKEN_LENGTH = 2;
const MIN_FUZZY_QUERY_LENGTH = 4;
@@ -649,7 +650,7 @@ export function companySearchService(db: Db) {
.from(issues)
.where(and(
eq(issues.companyId, companyId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
issueSearchCondition(scope, { issueTextMatch, commentMatch, documentMatch, fuzzyMatch }),
))
.orderBy(desc(score), desc(issues.updatedAt), desc(issues.id))
diff --git a/server/src/services/company-skills.ts b/server/src/services/company-skills.ts
index 6d23e80861..4cdfb7da81 100644
--- a/server/src/services/company-skills.ts
+++ b/server/src/services/company-skills.ts
@@ -2,9 +2,28 @@ 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, desc, eq, isNull, sql } from "drizzle-orm";
+import { and, asc, desc, eq, inArray, isNull, lt, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
-import { agents as agentsTable, companies, companySkillComments, companySkillStars, companySkillVersions, companySkills } from "@paperclipai/db";
+import {
+ agents as agentsTable,
+ assets,
+ authUsers,
+ companies,
+ companySkillComments,
+ companySkillStars,
+ companySkillTestInputs,
+ companySkillTestRunTemplates,
+ companySkillTestRuns,
+ companySkillVersions,
+ companySkills,
+ costEvents,
+ documents,
+ issueAttachments,
+ issueDocuments,
+ issues,
+ issueThreadInteractions,
+ issueWorkProducts,
+} from "@paperclipai/db";
import { readPaperclipSkillSyncPreference, writePaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils";
import type { PaperclipDesiredSkillEntry, PaperclipSkillEntry } from "@paperclipai/adapter-utils/server-utils";
import type {
@@ -21,6 +40,8 @@ import type {
CompanySkillCreateRequest,
CompanySkillCompatibility,
CompanySkillDetail,
+ CompanySkillFileDeleteRequest,
+ CompanySkillFileDeleteResult,
CompanySkillFileDetail,
CompanySkillFileInventoryEntry,
CompanySkillForkPrecheckResult,
@@ -33,6 +54,7 @@ import type {
CompanySkillInstallCatalogResult,
CompanySkillListQuery,
CompanySkillListItem,
+ CompanySkillLastEditor,
CompanySkillOriginalSummary,
CompanySkillProjectScanConflict,
CompanySkillProjectScanRequest,
@@ -41,6 +63,19 @@ import type {
CompanySkillSharingScope,
CompanySkillSourceBadge,
CompanySkillSourceType,
+ CompanySkillTestInput,
+ CompanySkillTestInputCreateRequest,
+ CompanySkillTestInputUpdateRequest,
+ CompanySkillTestRun,
+ CompanySkillTestRunCreateRequest,
+ CompanySkillTestRunDetail,
+ CompanySkillTestRunHarnessContent,
+ CompanySkillTestRunListQuery,
+ CompanySkillTestRunTemplate,
+ CompanySkillTestRunTemplateCreateRequest,
+ CompanySkillTestRunTemplateSnapshot,
+ CompanySkillTestRunTemplateUpdateRequest,
+ CompanySkillTestRunStatus,
CompanySkillTrustLevel,
CompanySkillUpdateRequest,
CompanySkillUpdateStatus,
@@ -49,12 +84,16 @@ import type {
CompanySkillVersion,
CompanySkillVersionCreateRequest,
CompanySkillVersionFileInventoryEntry,
+ IssueAttachment,
+ IssueDocument,
} from "@paperclipai/shared";
-import { normalizeAgentUrlKey, parseFrontmatterMarkdown } from "@paperclipai/shared";
+import { isUuidLike, normalizeAgentUrlKey, parseFrontmatterMarkdown } from "@paperclipai/shared";
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
import { conflict, notFound, unprocessable } from "../errors.js";
import { ghFetch, gitHubApiBase, resolveRawGitHubUrl } from "./github-fetch.js";
import { agentService } from "./agents.js";
+import { issueDocumentSelect, mapIssueDocumentRow } from "./documents.js";
+import { toIssueWorkProduct } from "./work-products.js";
import { projectService } from "./projects.js";
import { normalizePortablePath } from "./portable-path.js";
import {
@@ -72,6 +111,9 @@ import {
type CompanySkillRow = typeof companySkills.$inferSelect;
type CompanySkillVersionRow = typeof companySkillVersions.$inferSelect;
type CompanySkillCommentRow = typeof companySkillComments.$inferSelect;
+type CompanySkillTestInputRow = typeof companySkillTestInputs.$inferSelect;
+type CompanySkillTestRunTemplateRow = typeof companySkillTestRunTemplates.$inferSelect;
+type CompanySkillTestRunRow = typeof companySkillTestRuns.$inferSelect;
type CompanySkillListDbRow = Pick<
CompanySkillRow,
| "id"
@@ -167,6 +209,33 @@ type ImportedSkill = {
metadata: Record<string, unknown> | null;
};
+type ImportedSkillPersistValues = Pick<
+ CompanySkill,
+ | "companyId"
+ | "key"
+ | "slug"
+ | "name"
+ | "description"
+ | "markdown"
+ | "sourceType"
+ | "sourceLocator"
+ | "sourceRef"
+ | "trustLevel"
+ | "compatibility"
+ | "iconUrl"
+ | "color"
+ | "tagline"
+ | "authorName"
+ | "homepageUrl"
+ | "categories"
+ | "sharingScope"
+ | "installCount"
+> & {
+ fileInventory: Array<Record<string, unknown>>;
+ metadata: Record<string, unknown>;
+ updatedAt: Date;
+};
+
type PackageSkillConflictStrategy = "replace" | "rename" | "skip";
export type ImportPackageSkillResult = {
@@ -971,6 +1040,86 @@ function inventoryEntriesEqual(
});
}
+function stableJsonComparable(value: unknown): unknown {
+ if (value === undefined) return undefined;
+ if (Array.isArray(value)) {
+ return value.map((entry) => stableJsonComparable(entry) ?? null);
+ }
+ if (isPlainRecord(value)) {
+ const out: Record<string, unknown> = {};
+ for (const key of Object.keys(value).sort()) {
+ const normalized = stableJsonComparable(value[key]);
+ if (normalized !== undefined) out[key] = normalized ?? null;
+ }
+ return out;
+ }
+ return value;
+}
+
+function stableJsonEqual(left: unknown, right: unknown) {
+ return JSON.stringify(stableJsonComparable(left)) === JSON.stringify(stableJsonComparable(right));
+}
+
+function isPaperclipBundledSkillKey(key: string) {
+ return key.startsWith("paperclipai/paperclip/");
+}
+
+function stripDerivedPaperclipBundledMetadata(key: string, metadata: unknown): unknown {
+ if (metadata === null || metadata === undefined) return {};
+ const comparable = stableJsonComparable(metadata);
+ if (!isPlainRecord(comparable)) return comparable;
+
+ const out = { ...comparable };
+ if (out.skillKey === key) delete out.skillKey;
+ if (out.sourceKind === "paperclip_bundled") delete out.sourceKind;
+ delete out.missingSource;
+ return out;
+}
+
+function importedSkillMetadataEqual(existing: CompanySkill, values: ImportedSkillPersistValues) {
+ const incomingMetadata = isPlainRecord(values.metadata) ? values.metadata : null;
+ if (isPaperclipBundledSkillKey(values.key) && asString(incomingMetadata?.sourceKind) === "paperclip_bundled") {
+ return JSON.stringify(stripDerivedPaperclipBundledMetadata(existing.key, existing.metadata))
+ === JSON.stringify(stripDerivedPaperclipBundledMetadata(values.key, values.metadata));
+ }
+ return stableJsonEqual(existing.metadata ?? null, values.metadata);
+}
+
+function stringArraysEqual(left: string[], right: string[]) {
+ if (left.length !== right.length) return false;
+ return left.every((entry, index) => entry === right[index]);
+}
+
+function importedSkillPersistValuesMatchExisting(
+ existing: CompanySkill,
+ values: ImportedSkillPersistValues,
+) {
+ return existing.companyId === values.companyId
+ && existing.key === values.key
+ && existing.slug === values.slug
+ && existing.name === values.name
+ && existing.description === values.description
+ && existing.markdown === values.markdown
+ && existing.sourceType === values.sourceType
+ && existing.sourceLocator === values.sourceLocator
+ && existing.sourceRef === values.sourceRef
+ && existing.trustLevel === values.trustLevel
+ && existing.compatibility === values.compatibility
+ && inventoryEntriesEqual(
+ existing.fileInventory,
+ normalizeFileInventory({ fileInventory: values.fileInventory }),
+ )
+ && existing.iconUrl === values.iconUrl
+ && existing.color === values.color
+ && existing.tagline === values.tagline
+ && existing.authorName === values.authorName
+ && existing.homepageUrl === values.homepageUrl
+ && stringArraysEqual(existing.categories, normalizeCategoryList(values.categories))
+ && existing.sharingScope === values.sharingScope
+ && existing.installCount === values.installCount
+ && importedSkillMetadataEqual(existing, values);
+}
+
function inferLocalSkillInventoryMode(
skill: Pick<CompanySkillRow, "sourceLocator" | "metadata">,
): LocalSkillInventoryMode {
@@ -1361,14 +1510,29 @@ function normalizeMutableSharingScope(value: unknown): CompanySkillSharingScope
throw unprocessable("Invalid skill sharing scope.");
}
-function normalizeCategorySlug(value: unknown) {
+function normalizeCategoryName(value: unknown) {
if (typeof value !== "string") return null;
- return normalizeSkillSlug(value);
+ const normalized = value.trim().replace(/\s+/g, " ");
+ return normalized.length > 0 ? normalized : null;
+}
+
+function categoryLookupKey(value: string) {
+ return value.toLocaleLowerCase();
}
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))));
+ const seen = new Set<string>();
+ const categories: string[] = [];
+ for (const value of values) {
+ const category = normalizeCategoryName(value);
+ if (!category) continue;
+ const key = categoryLookupKey(category);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ categories.push(category);
+ }
+ return categories;
}
function normalizeStoreText(value: unknown, maxLength = 500) {
@@ -1447,6 +1611,147 @@ function toCompanySkillComment(row: CompanySkillCommentRow): CompanySkillComment
};
}
+function toCompanySkillTestInput(row: CompanySkillTestInputRow): CompanySkillTestInput {
+ return {
+ ...row,
+ deletedAt: row.deletedAt ?? null,
+ };
+}
+
+const BUILT_IN_SKILL_TEST_RUN_TEMPLATE_ID = "built-in:default-test-template";
+const BUILT_IN_SKILL_TEST_RUN_TEMPLATE_DATE = new Date("2026-01-01T00:00:00.000Z");
+const BUILT_IN_SKILL_TEST_RUN_TEMPLATE_BODY = [
+ "You are running a Skills Studio test for `{{skillName}}` (`{{skillKey}}`), skill version v{{skillVersion}}.",
+ "",
+ "Invoke and use the selected skill under test: `{{skillInvocation}}`. Use the pinned skill revision supplied by Paperclip as the source of truth, regardless of any other runtime skills.",
+ "",
+ "This is a test run. Do not make durable changes outside this test task. Do not mutate unrelated issues, push, publish, send external messages, or affect real work.",
+ "",
+ "If the skill would create documents, images, videos, files, or other assets, create test versions in an obviously test-scoped location when applicable, then post the results back to this task as issue documents, attachments, or work products.",
+ "",
+ "Write the final result to issue document `{{outputDocumentKey}}`, then mark this test task done.",
+].join("\n");
+
+function builtInSkillTestRunTemplate(companyId: string): CompanySkillTestRunTemplate {
+ return {
+ id: BUILT_IN_SKILL_TEST_RUN_TEMPLATE_ID,
+ companyId,
+ name: "Default test template",
+ description: "Paperclip's read-only default harness instructions for Skills Studio runs.",
+ body: BUILT_IN_SKILL_TEST_RUN_TEMPLATE_BODY,
+ builtIn: true,
+ createdByAgentId: null,
+ createdByUserId: null,
+ updatedByAgentId: null,
+ updatedByUserId: null,
+ deletedAt: null,
+ createdAt: BUILT_IN_SKILL_TEST_RUN_TEMPLATE_DATE,
+ updatedAt: BUILT_IN_SKILL_TEST_RUN_TEMPLATE_DATE,
+ };
+}
+
+function toCompanySkillTestRunTemplate(row: CompanySkillTestRunTemplateRow): CompanySkillTestRunTemplate {
+ return {
+ ...row,
+ description: row.description ?? null,
+ builtIn: false,
+ createdByAgentId: row.createdByAgentId ?? null,
+ createdByUserId: row.createdByUserId ?? null,
+ updatedByAgentId: row.updatedByAgentId ?? null,
+ updatedByUserId: row.updatedByUserId ?? null,
+ deletedAt: row.deletedAt ?? null,
+ };
+}
+
+const ALLOWED_SKILL_TEST_TEMPLATE_PLACEHOLDERS = new Set([
+ "skillName",
+ "skillKey",
+ "skillInvocation",
+ "skillVersion",
+ "runId",
+ "issueId",
+ "outputDocumentKey",
+]);
+
+function validateSkillTestTemplatePlaceholders(body: string) {
+ const unknown = new Set<string>();
+ const recognized = /\{\{\s*([A-Za-z][A-Za-z0-9]*)\s*\}\}/g;
+ for (const match of body.matchAll(recognized)) {
+ const key = match[1] ?? "";
+ if (!ALLOWED_SKILL_TEST_TEMPLATE_PLACEHOLDERS.has(key)) {
+ unknown.add(key);
+ }
+ }
+ if (body.replace(recognized, "").includes("{{") || body.replace(recognized, "").includes("}}")) {
+ throw unprocessable("Malformed template placeholder. Use explicit placeholders like {{skillName}}.");
+ }
+ if (unknown.size > 0) {
+ throw unprocessable(`Unknown template placeholder${unknown.size === 1 ? "" : "s"}: ${Array.from(unknown).sort().join(", ")}`);
+ }
+}
+
+function renderSkillTestTemplate(body: string, values: Record<string, string>) {
+ validateSkillTestTemplatePlaceholders(body);
+ return body.replace(/\{\{\s*([A-Za-z][A-Za-z0-9]*)\s*\}\}/g, (_match, rawKey: string) => values[rawKey] ?? "");
+}
+
+function buildHarnessIssueDescription(inputSnapshot: string, renderedTemplateBody: string | null) {
+ const trimmedInput = inputSnapshot.trim();
+ const trimmedTemplate = renderedTemplateBody?.trim() ?? "";
+ return trimmedTemplate ? `${trimmedInput}\n\n---\n\n${trimmedTemplate}` : trimmedInput;
+}
+
+function normalizeTestRunStatus(value: string): CompanySkillTestRunStatus {
+ return value === "running" || value === "succeeded" || value === "failed" || value === "cancelled"
+ ? value
+ : "queued";
+}
+
+function emptyTestRunCost() {
+ return {
+ costCents: 0,
+ inputTokens: 0,
+ cachedInputTokens: 0,
+ outputTokens: 0,
+ };
+}
+
+function toCompanySkillTestRun(
+ row: CompanySkillTestRunRow,
+ cost = emptyTestRunCost(),
+ taskExpired = false,
+): CompanySkillTestRun {
+ return {
+ ...row,
+ inputId: row.inputId ?? null,
+ agentConfigSnapshot: isPlainRecord(row.agentConfigSnapshot) ? row.agentConfigSnapshot : {},
+ templateId: row.templateId ?? null,
+ templateName: row.templateName ?? null,
+ templateBody: row.templateBody ?? null,
+ renderedTemplateBody: row.renderedTemplateBody ?? null,
+ harnessIssueDescription: row.harnessIssueDescription || row.inputSnapshot,
+ status: normalizeTestRunStatus(row.status),
+ outputDocumentKey: row.outputDocumentKey || "output",
+ outputSnapshot: row.outputSnapshot ?? "",
+ error: row.error ?? null,
+ deletedAt: row.deletedAt ?? null,
+ supersededAt: row.supersededAt ?? null,
+ harnessIssueExpiresAt: row.harnessIssueExpiresAt ?? null,
+ harnessIssueDeletedAt: row.harnessIssueDeletedAt ?? null,
+ cost,
+ taskExpired,
+ };
+}
+
+function versionInventorySnapshotEqual(
+ left: CompanySkillVersionFileInventoryEntry[],
+ right: CompanySkillVersionFileInventoryEntry[],
+) {
+ const normalize = (entries: CompanySkillVersionFileInventoryEntry[]) =>
+ JSON.stringify([...entries].sort((a, b) => a.path.localeCompare(b.path)));
+ return normalize(left) === normalize(right);
+}
+
function getSkillMeta(skill: Pick<CompanySkill, "metadata">): SkillSourceMeta {
return isPlainRecord(skill.metadata) ? skill.metadata as SkillSourceMeta : {};
}
@@ -1606,15 +1911,30 @@ async function assertVersionMatchesSkill(
}
}
+export interface ResolvedRequestedSkillEntries {
+ /** References that resolved to a company-library skill. */
+ resolved: PaperclipDesiredSkillEntry[];
+ /**
+ * References that could not be resolved to a company-library skill, returned
+ * in first-seen order. Only populated when `tolerateUnknownReferences` is set;
+ * otherwise unknown references throw. Callers preserve these so stale desired
+ * keys stay visible (and removable) instead of silently 422-ing a whole save.
+ */
+ unresolved: string[];
+}
+
async function resolveRequestedSkillEntriesOrThrow(
db: Db,
companyId: string,
skills: CompanySkill[],
requestedSelections: Array<string | AgentDesiredSkillEntry>,
-) {
+ options: { tolerateUnknownReferences?: boolean } = {},
+): Promise<ResolvedRequestedSkillEntries> {
const missing = new Set<string>();
const ambiguous = new Set<string>();
const resolved = new Map<string, PaperclipDesiredSkillEntry>();
+ const unresolved: string[] = [];
+ const seenUnresolved = new Set<string>();
for (const rawSelection of requestedSelections) {
const selection = normalizeRequestedDesiredSkillSelection(rawSelection);
@@ -1640,9 +1960,20 @@ async function resolveRequestedSkillEntriesOrThrow(
continue;
}
+ // Unknown / stale reference (no longer in the company library).
+ if (options.tolerateUnknownReferences) {
+ if (!seenUnresolved.has(selection.key)) {
+ seenUnresolved.add(selection.key);
+ unresolved.push(selection.key);
+ }
+ continue;
+ }
missing.add(selection.key);
}
+ // Ambiguous references are always a hard error — they signal a genuine
+ // conflict the caller must disambiguate. Unknown references are only fatal
+ // when the caller has not opted into tolerating (and preserving) stale keys.
if (ambiguous.size > 0 || missing.size > 0) {
const problems: string[] = [];
if (ambiguous.size > 0) {
@@ -1654,7 +1985,7 @@ async function resolveRequestedSkillEntriesOrThrow(
throw unprocessable(`Invalid company skill selection (${problems.join("; ")}).`);
}
- return Array.from(resolved.values());
+ return { resolved: Array.from(resolved.values()), unresolved };
}
function resolveDesiredSkillKeys(
@@ -2181,6 +2512,66 @@ function toCompanySkillListItem(skill: CompanySkillListRow, attachedAgentCount:
};
}
+async function listLastEditorsBySkillId(
+ db: Db,
+ companyId: string,
+ skillIds: string[],
+): Promise<Map<string, CompanySkillLastEditor | null>> {
+ if (skillIds.length === 0) return new Map();
+ const rows = await db
+ .selectDistinctOn([companySkillVersions.companySkillId], {
+ companySkillId: companySkillVersions.companySkillId,
+ authorAgentId: companySkillVersions.authorAgentId,
+ authorUserId: companySkillVersions.authorUserId,
+ userName: authUsers.name,
+ userImage: authUsers.image,
+ agentName: agentsTable.name,
+ })
+ .from(companySkillVersions)
+ .leftJoin(authUsers, eq(authUsers.id, companySkillVersions.authorUserId))
+ .leftJoin(
+ agentsTable,
+ and(
+ eq(agentsTable.companyId, companyId),
+ eq(agentsTable.id, companySkillVersions.authorAgentId),
+ ),
+ )
+ .where(and(
+ eq(companySkillVersions.companyId, companyId),
+ inArray(companySkillVersions.companySkillId, skillIds),
+ ))
+ .orderBy(
+ companySkillVersions.companySkillId,
+ desc(companySkillVersions.createdAt),
+ desc(companySkillVersions.revisionNumber),
+ desc(companySkillVersions.id),
+ );
+
+ const editors = new Map<string, CompanySkillLastEditor | null>();
+ for (const row of rows) {
+ if (row.authorUserId) {
+ editors.set(row.companySkillId, {
+ kind: "user",
+ id: row.authorUserId,
+ name: row.userName ?? null,
+ imageUrl: row.userImage ?? null,
+ });
+ continue;
+ }
+ if (row.authorAgentId) {
+ editors.set(row.companySkillId, {
+ kind: "agent",
+ id: row.authorAgentId,
+ name: row.agentName ?? null,
+ imageUrl: null,
+ });
+ continue;
+ }
+ editors.set(row.companySkillId, null);
+ }
+ return editors;
+}
+
export function companySkillService(db: Db) {
const agents = agentService(db);
const projects = projectService(db);
@@ -2236,6 +2627,7 @@ export function companySkillService(db: Db) {
for (const skill of skills) {
if (skill.sourceType !== "local_path") continue;
+ if (isPaperclipBundledSkillKey(skill.key) || asString(skill.metadata?.sourceKind) === "paperclip_bundled") continue;
if (!missingIds.has(skill.id)) {
const metadata = getMissingSourceMarker(skill.metadata)
@@ -2247,7 +2639,7 @@ export function companySkillService(db: Db) {
: null;
const nextTrustLevel = nextInventory ? deriveTrustLevel(nextInventory) : skill.trustLevel;
const inventoryChanged = nextInventory ? !inventoryEntriesEqual(skill.fileInventory, nextInventory) : false;
- const metadataChanged = JSON.stringify(metadata ?? {}) !== JSON.stringify(skill.metadata ?? {});
+ const metadataChanged = !stableJsonEqual(metadata ?? {}, skill.metadata ?? {});
if (inventoryChanged || metadataChanged || nextTrustLevel !== skill.trustLevel) {
await db
.update(companySkills)
@@ -2268,7 +2660,7 @@ export function companySkillService(db: Db) {
skill.metadata,
buildMissingLocalSourceMarker(skill),
);
- if (JSON.stringify(metadata) !== JSON.stringify(skill.metadata ?? {})) {
+ if (!stableJsonEqual(metadata, skill.metadata ?? {})) {
await db
.update(companySkills)
.set({ metadata, updatedAt: new Date() })
@@ -2354,10 +2746,15 @@ export function companySkillService(db: Db) {
.then((entries) => entries.map((entry) => toCompanySkillListRow(entry as CompanySkillListDbRow)));
const agentRows = await agents.list(companyId);
const q = query.q?.trim().toLowerCase() ?? "";
- const categories = new Set((query.categories ?? []).map(normalizeCategorySlug).filter((value): value is string => Boolean(value)));
+ const categories = new Set(
+ (query.categories ?? [])
+ .map(normalizeCategoryName)
+ .filter((value): value is string => Boolean(value))
+ .map(categoryLookupKey),
+ );
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 (categories.size > 0 && !skill.categories.some((category) => categories.has(categoryLookupKey(category)))) return false;
if (q) {
const haystack = [
skill.name,
@@ -2388,6 +2785,13 @@ export function companySkillService(db: Db) {
if (sort === "forks") return right.forkCount - left.forkCount || left.name.localeCompare(right.name);
return left.name.localeCompare(right.name) || left.key.localeCompare(right.key);
});
+ if (query.include?.includes("lastEditor")) {
+ const lastEditors = await listLastEditorsBySkillId(db, companyId, items.map((item) => item.id));
+ return items.map((item) => ({
+ ...item,
+ lastEditor: lastEditors.get(item.id) ?? null,
+ }));
+ }
return items;
}
@@ -2444,6 +2848,20 @@ export function companySkillService(db: Db) {
return row ? toCompanySkill(row) : null;
}
+ async function getBySlugIfUnique(companyId: string, slug: string) {
+ const rows = await db
+ .select(selectCompanySkillColumns())
+ .from(companySkills)
+ .where(and(eq(companySkills.companyId, companyId), eq(companySkills.slug, slug)));
+ return rows.length === 1 ? toCompanySkill(rows[0]!) : null;
+ }
+
+ async function getByRouteRef(companyId: string, ref: string) {
+ return (isUuidLike(ref) ? await getById(companyId, ref) : null)
+ ?? await getBySlugIfUnique(companyId, ref)
+ ?? await getByKey(companyId, ref);
+ }
+
async function getVersion(companyId: string, skillId: string, versionId: string): Promise<CompanySkillVersion | null> {
const row = await db
.select()
@@ -2578,7 +2996,7 @@ export function companySkillService(db: Db) {
async function detail(companyId: string, id: string, actor?: SkillActor | null): Promise<CompanySkillDetail | null> {
await ensureSkillInventoryCurrent(companyId);
- const skill = await getById(companyId, id);
+ const skill = await getByRouteRef(companyId, id);
if (!skill) return null;
const usedByAgents = await usage(companyId, skill.key);
const existingForks = await existingForkSummaries(companyId, skill.id, actor);
@@ -2587,7 +3005,7 @@ export function companySkillService(db: Db) {
usedByAgents.length,
usedByAgents,
await getCurrentVersion(skill),
- await isStarredByActor(companyId, id, actor),
+ await isStarredByActor(companyId, skill.id, actor),
existingForks,
);
}
@@ -3473,6 +3891,71 @@ export function companySkillService(db: Db) {
return detail;
}
+ async function deleteFile(
+ companyId: string,
+ skillId: string,
+ input: CompanySkillFileDeleteRequest,
+ actor: SkillActor | null = null,
+ ): Promise<CompanySkillFileDeleteResult> {
+ await ensureSkillInventoryCurrent(companyId);
+ const skill = await getById(companyId, skillId);
+ if (!skill) throw notFound("Skill not found");
+
+ const source = deriveSkillSourceInfo(skill);
+ if (!source.editable || skill.sourceType !== "local_path") {
+ throw unprocessable(source.editableReason ?? "This skill cannot be edited.");
+ }
+
+ const normalizedPath = normalizePortablePath(input.path);
+ if (!normalizedPath) {
+ throw unprocessable("Skill file path is required.");
+ }
+
+ const deletedPaths = input.target === "folder"
+ ? skill.fileInventory
+ .map((entry) => normalizePortablePath(entry.path))
+ .filter((entryPath) => entryPath.startsWith(`${normalizedPath}/`))
+ : skill.fileInventory
+ .map((entry) => normalizePortablePath(entry.path))
+ .filter((entryPath) => entryPath === normalizedPath);
+
+ if (deletedPaths.length === 0) {
+ throw notFound(input.target === "folder" ? "Skill folder not found" : "Skill file not found");
+ }
+ if (deletedPaths.includes("SKILL.md")) {
+ throw unprocessable("SKILL.md cannot be deleted.");
+ }
+
+ const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath);
+ if (!absolutePath) throw notFound("Skill file not found");
+
+ await fs.rm(absolutePath, {
+ recursive: input.target === "folder",
+ force: false,
+ }).catch((error) => {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ throw notFound(input.target === "folder" ? "Skill folder not found" : "Skill file not found");
+ }
+ throw error;
+ });
+
+ await db
+ .update(companySkills)
+ .set({ updatedAt: new Date() })
+ .where(eq(companySkills.id, skill.id));
+
+ await createVersion(companyId, skillId, {
+ label: input.target === "folder" ? `Deleted ${normalizedPath}/` : `Deleted ${normalizedPath}`,
+ }, actor);
+
+ return {
+ skillId: skill.id,
+ path: normalizedPath,
+ target: input.target,
+ deletedPaths,
+ };
+ }
+
async function installUpdate(companyId: string, skillId: string, options: { force?: boolean } = {}): Promise<CompanySkill | null> {
await ensureSkillInventoryCurrent(companyId);
const skill = await getById(companyId, skillId);
@@ -4566,7 +5049,7 @@ export function companySkillService(db: Db) {
};
const parsed = parseFrontmatterMarkdown(skill.markdown);
const storeMetadata = readSkillStoreMetadata(parsed.frontmatter, metadata);
- const values = {
+ const values: ImportedSkillPersistValues = {
companyId,
key: skill.key,
slug: skill.slug,
@@ -4590,6 +5073,10 @@ export function companySkillService(db: Db) {
metadata,
updatedAt: new Date(),
};
+ if (existing && importedSkillPersistValuesMatchExisting(existing, values)) {
+ out.push(existing);
+ continue;
+ }
const row = existing
? await db
.update(companySkills)
@@ -4648,6 +5135,775 @@ export function companySkillService(db: Db) {
return { imported, warnings };
}
+ async function listTestInputs(companyId: string, skillId: string): Promise<CompanySkillTestInput[]> {
+ const skill = await getById(companyId, skillId);
+ if (!skill) throw notFound("Skill not found");
+ const rows = await db
+ .select()
+ .from(companySkillTestInputs)
+ .where(and(
+ eq(companySkillTestInputs.companyId, companyId),
+ eq(companySkillTestInputs.skillId, skillId),
+ isNull(companySkillTestInputs.deletedAt),
+ ))
+ .orderBy(asc(companySkillTestInputs.name), asc(companySkillTestInputs.createdAt));
+ return rows.map(toCompanySkillTestInput);
+ }
+
+ async function createTestInput(
+ companyId: string,
+ skillId: string,
+ input: CompanySkillTestInputCreateRequest,
+ actor: SkillActor | null = null,
+ ): Promise<CompanySkillTestInput> {
+ const skill = await getById(companyId, skillId);
+ if (!skill) throw notFound("Skill not found");
+ const row = await db
+ .insert(companySkillTestInputs)
+ .values({
+ companyId,
+ skillId,
+ name: input.name.trim(),
+ content: input.content,
+ createdBy: actor?.type === "agent"
+ ? actor.agentId ?? null
+ : actor?.type === "user"
+ ? actor.userId ?? null
+ : null,
+ })
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ if (!row) throw notFound("Failed to persist test input");
+ return toCompanySkillTestInput(row);
+ }
+
+ async function updateTestInput(
+ companyId: string,
+ skillId: string,
+ inputId: string,
+ input: CompanySkillTestInputUpdateRequest,
+ ): Promise<CompanySkillTestInput | null> {
+ const patch: Partial<typeof companySkillTestInputs.$inferInsert> = { updatedAt: new Date() };
+ if (input.name !== undefined) patch.name = input.name.trim();
+ if (input.content !== undefined) patch.content = input.content;
+ const row = await db
+ .update(companySkillTestInputs)
+ .set(patch)
+ .where(and(
+ eq(companySkillTestInputs.companyId, companyId),
+ eq(companySkillTestInputs.skillId, skillId),
+ eq(companySkillTestInputs.id, inputId),
+ isNull(companySkillTestInputs.deletedAt),
+ ))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ return row ? toCompanySkillTestInput(row) : null;
+ }
+
+ async function deleteTestInput(companyId: string, skillId: string, inputId: string): Promise<CompanySkillTestInput | null> {
+ const row = await db
+ .update(companySkillTestInputs)
+ .set({ deletedAt: new Date(), updatedAt: new Date() })
+ .where(and(
+ eq(companySkillTestInputs.companyId, companyId),
+ eq(companySkillTestInputs.skillId, skillId),
+ eq(companySkillTestInputs.id, inputId),
+ isNull(companySkillTestInputs.deletedAt),
+ ))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ return row ? toCompanySkillTestInput(row) : null;
+ }
+
+ async function listTestRunTemplates(companyId: string): Promise<CompanySkillTestRunTemplate[]> {
+ const rows = await db
+ .select()
+ .from(companySkillTestRunTemplates)
+ .where(and(eq(companySkillTestRunTemplates.companyId, companyId), isNull(companySkillTestRunTemplates.deletedAt)))
+ .orderBy(asc(companySkillTestRunTemplates.name), asc(companySkillTestRunTemplates.createdAt));
+ return [
+ builtInSkillTestRunTemplate(companyId),
+ ...rows.map(toCompanySkillTestRunTemplate),
+ ];
+ }
+
+ async function createTestRunTemplate(
+ companyId: string,
+ input: CompanySkillTestRunTemplateCreateRequest,
+ actor: SkillActor | null = null,
+ ): Promise<CompanySkillTestRunTemplate> {
+ validateSkillTestTemplatePlaceholders(input.body);
+ const row = await db
+ .insert(companySkillTestRunTemplates)
+ .values({
+ companyId,
+ name: input.name.trim(),
+ description: input.description?.trim() || null,
+ body: input.body,
+ createdByAgentId: actor?.type === "agent" ? actor.agentId ?? null : null,
+ createdByUserId: actor?.type === "user" ? actor.userId ?? null : null,
+ updatedByAgentId: actor?.type === "agent" ? actor.agentId ?? null : null,
+ updatedByUserId: actor?.type === "user" ? actor.userId ?? null : null,
+ })
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ if (!row) throw notFound("Failed to persist test run template");
+ return toCompanySkillTestRunTemplate(row);
+ }
+
+ async function updateTestRunTemplate(
+ companyId: string,
+ templateId: string,
+ input: CompanySkillTestRunTemplateUpdateRequest,
+ actor: SkillActor | null = null,
+ ): Promise<CompanySkillTestRunTemplate | null> {
+ if (templateId === BUILT_IN_SKILL_TEST_RUN_TEMPLATE_ID) {
+ throw unprocessable("Built-in test run templates are read-only.");
+ }
+ if (input.body !== undefined) {
+ validateSkillTestTemplatePlaceholders(input.body);
+ }
+ const patch: Partial<typeof companySkillTestRunTemplates.$inferInsert> = {
+ updatedAt: new Date(),
+ updatedByAgentId: actor?.type === "agent" ? actor.agentId ?? null : null,
+ updatedByUserId: actor?.type === "user" ? actor.userId ?? null : null,
+ };
+ if (input.name !== undefined) patch.name = input.name.trim();
+ if (input.description !== undefined) patch.description = input.description?.trim() || null;
+ if (input.body !== undefined) patch.body = input.body;
+ const row = await db
+ .update(companySkillTestRunTemplates)
+ .set(patch)
+ .where(and(
+ eq(companySkillTestRunTemplates.companyId, companyId),
+ eq(companySkillTestRunTemplates.id, templateId),
+ isNull(companySkillTestRunTemplates.deletedAt),
+ ))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ return row ? toCompanySkillTestRunTemplate(row) : null;
+ }
+
+ async function deleteTestRunTemplate(companyId: string, templateId: string): Promise<CompanySkillTestRunTemplate | null> {
+ if (templateId === BUILT_IN_SKILL_TEST_RUN_TEMPLATE_ID) {
+ throw unprocessable("Built-in test run templates are read-only.");
+ }
+ const row = await db
+ .update(companySkillTestRunTemplates)
+ .set({ deletedAt: new Date(), updatedAt: new Date() })
+ .where(and(
+ eq(companySkillTestRunTemplates.companyId, companyId),
+ eq(companySkillTestRunTemplates.id, templateId),
+ isNull(companySkillTestRunTemplates.deletedAt),
+ ))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ return row ? toCompanySkillTestRunTemplate(row) : null;
+ }
+
+ async function resolveTestRunTemplateSnapshot(
+ companyId: string,
+ input: CompanySkillTestRunCreateRequest,
+ ): Promise<CompanySkillTestRunTemplateSnapshot | null> {
+ if (input.templateSnapshot !== undefined) {
+ const snapshot = input.templateSnapshot;
+ if (!snapshot || snapshot.templateId === null) return null;
+ validateSkillTestTemplatePlaceholders(snapshot.templateBody ?? "");
+ return {
+ templateId: snapshot.templateId,
+ templateName: snapshot.templateName,
+ templateBody: snapshot.templateBody,
+ };
+ }
+
+ const templateId = input.templateId === undefined ? BUILT_IN_SKILL_TEST_RUN_TEMPLATE_ID : input.templateId;
+ if (templateId === null) return null;
+ if (templateId === BUILT_IN_SKILL_TEST_RUN_TEMPLATE_ID) {
+ const template = builtInSkillTestRunTemplate(companyId);
+ return {
+ templateId: template.id,
+ templateName: template.name,
+ templateBody: template.body,
+ };
+ }
+ const row = await db
+ .select()
+ .from(companySkillTestRunTemplates)
+ .where(and(
+ eq(companySkillTestRunTemplates.companyId, companyId),
+ eq(companySkillTestRunTemplates.id, templateId),
+ isNull(companySkillTestRunTemplates.deletedAt),
+ ))
+ .then((rows) => rows[0] ?? null);
+ if (!row) throw notFound("Test run template not found");
+ return {
+ templateId: row.id,
+ templateName: row.name,
+ templateBody: row.body,
+ };
+ }
+
+ async function ensureRunSkillVersion(
+ companyId: string,
+ skill: CompanySkill,
+ actor: SkillActor | null,
+ ): Promise<CompanySkillVersion> {
+ const currentSnapshot = serializeVersionFileInventory(await collectVersionFileInventory(companyId, skill));
+ if (currentSnapshot.length === 0) {
+ throw unprocessable("Cannot run a skill test for a skill with zero files.");
+ }
+
+ const currentVersion = await getCurrentVersion(skill);
+ if (!currentVersion || !versionInventorySnapshotEqual(currentVersion.fileInventory, currentSnapshot)) {
+ return createVersion(companyId, skill.id, { label: "Auto version for test run" }, actor);
+ }
+ return currentVersion;
+ }
+
+ function snapshotAgentConfig(agent: Awaited<ReturnType<typeof agents.getById>>) {
+ if (!agent) return {};
+ const adapterConfig = isPlainRecord(agent.adapterConfig) ? agent.adapterConfig : {};
+ const runtimeConfig = isPlainRecord(agent.runtimeConfig) ? agent.runtimeConfig : {};
+ return {
+ agentId: agent.id,
+ name: agent.name,
+ role: agent.role,
+ adapterType: agent.adapterType,
+ model: asString(adapterConfig.model) ?? asString(runtimeConfig.model) ?? null,
+ adapterConfig,
+ runtimeConfig,
+ assignedSkills: isPlainRecord(adapterConfig.paperclipSkillSync)
+ ? adapterConfig.paperclipSkillSync
+ : null,
+ instructionsRef:
+ asString(adapterConfig.instructionsFilePath) ??
+ asString(adapterConfig.instructionsPath) ??
+ asString(adapterConfig.instructionsRef) ??
+ null,
+ };
+ }
+
+ async function testRunCostByIssueIds(companyId: string, issueIds: string[]) {
+ if (issueIds.length === 0) return new Map<string, ReturnType<typeof emptyTestRunCost>>();
+ const rows = await db
+ .select({
+ issueId: costEvents.issueId,
+ costCents: sql<number>`coalesce(sum(${costEvents.costCents}), 0)::int`,
+ inputTokens: sql<number>`coalesce(sum(${costEvents.inputTokens}), 0)::int`,
+ cachedInputTokens: sql<number>`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`,
+ outputTokens: sql<number>`coalesce(sum(${costEvents.outputTokens}), 0)::int`,
+ })
+ .from(costEvents)
+ .where(and(eq(costEvents.companyId, companyId), inArray(costEvents.issueId, issueIds)))
+ .groupBy(costEvents.issueId);
+ return new Map(rows.flatMap((row) => row.issueId
+ ? [[row.issueId, {
+ costCents: Number(row.costCents ?? 0),
+ inputTokens: Number(row.inputTokens ?? 0),
+ cachedInputTokens: Number(row.cachedInputTokens ?? 0),
+ outputTokens: Number(row.outputTokens ?? 0),
+ }]]
+ : []));
+ }
+
+ async function hydrateTestRuns(companyId: string, rows: CompanySkillTestRunRow[]): Promise<CompanySkillTestRun[]> {
+ const costByIssueId = await testRunCostByIssueIds(companyId, rows.map((row) => row.issueId));
+ return rows.map((row) => toCompanySkillTestRun(
+ row,
+ costByIssueId.get(row.issueId) ?? emptyTestRunCost(),
+ Boolean(row.harnessIssueDeletedAt),
+ ));
+ }
+
+ async function createTestRun(
+ companyId: string,
+ skillId: string,
+ input: CompanySkillTestRunCreateRequest,
+ actor: SkillActor | null,
+ deps: {
+ createHarnessIssue: (issue: {
+ id: string;
+ title: string;
+ description: string;
+ assigneeAgentId: string;
+ harnessKind: "skill_test";
+ workMode: "skill_test";
+ status: "todo";
+ originKind: "skill_test";
+ originId: string;
+ originFingerprint: string;
+ }) => Promise<{ id: string }>;
+ wakeHarnessIssue: (issueId: string, agentId: string) => Promise<unknown>;
+ cleanupHarnessIssue?: (issueId: string) => Promise<unknown>;
+ retentionDays?: number;
+ },
+ ): Promise<CompanySkillTestRun> {
+ const skill = await getById(companyId, skillId);
+ if (!skill) throw notFound("Skill not found");
+ const agent = await agents.getById(input.agentId);
+ if (!agent || agent.companyId !== companyId) throw notFound("Agent not found");
+ if (agent.status === "paused") throw unprocessable("Paused agents cannot run skill tests.");
+
+ const sourceInput = input.inputId
+ ? await db
+ .select()
+ .from(companySkillTestInputs)
+ .where(and(
+ eq(companySkillTestInputs.companyId, companyId),
+ eq(companySkillTestInputs.skillId, skillId),
+ eq(companySkillTestInputs.id, input.inputId),
+ isNull(companySkillTestInputs.deletedAt),
+ ))
+ .then((rows) => rows[0] ?? null)
+ : null;
+ if (input.inputId && !sourceInput) throw notFound("Test input not found");
+ const inputSnapshot = (sourceInput?.content ?? input.content ?? "").trim();
+ if (!inputSnapshot) throw unprocessable("Test input content cannot be empty.");
+
+ // Re-run pins the viewed run's version so the new run reproduces the same
+ // snapshots; a plain run auto-snapshots the live head.
+ const version = input.skillVersionId
+ ? await getVersion(companyId, skillId, input.skillVersionId)
+ : await ensureRunSkillVersion(companyId, skill, actor);
+ if (!version) throw notFound("Skill version not found");
+ const runId = randomUUID();
+ const issueId = randomUUID();
+ const outputDocumentKey = "output";
+ const templateSnapshot = await resolveTestRunTemplateSnapshot(companyId, input);
+ const renderedTemplateBody = templateSnapshot?.templateBody
+ ? renderSkillTestTemplate(templateSnapshot.templateBody, {
+ skillName: skill.name,
+ skillKey: skill.key,
+ skillInvocation: skill.key,
+ skillVersion: String(version.revisionNumber),
+ runId,
+ issueId,
+ outputDocumentKey,
+ }).trim()
+ : null;
+ const harnessIssueDescription = buildHarnessIssueDescription(inputSnapshot, renderedTemplateBody);
+ await deps.createHarnessIssue({
+ id: issueId,
+ title: `Skill test: ${skill.name}`,
+ description: harnessIssueDescription,
+ assigneeAgentId: agent.id,
+ harnessKind: "skill_test",
+ workMode: "skill_test",
+ status: "todo",
+ originKind: "skill_test",
+ originId: runId,
+ originFingerprint: `skill_test:${runId}`,
+ });
+
+ const now = new Date();
+ const retentionDays = Math.max(0, deps.retentionDays ?? 7);
+ const previousExpiresAt = new Date(now.getTime() + retentionDays * 24 * 60 * 60 * 1000);
+ const cleanupCreatedHarnessIssue = async () => {
+ await deps.cleanupHarnessIssue?.(issueId).catch(() => {});
+ };
+ const row = await db.transaction(async (tx) => {
+ await tx
+ .update(companySkillTestRuns)
+ .set({
+ supersededAt: now,
+ status: sql`
+ case when ${companySkillTestRuns.status} in ('queued', 'running')
+ then 'cancelled'
+ else ${companySkillTestRuns.status}
+ end
+ `,
+ error: sql`
+ case when ${companySkillTestRuns.status} in ('queued', 'running')
+ then coalesce(${companySkillTestRuns.error}, 'Superseded by newer run')
+ else ${companySkillTestRuns.error}
+ end
+ `,
+ harnessIssueExpiresAt: previousExpiresAt,
+ updatedAt: now,
+ })
+ .where(and(
+ eq(companySkillTestRuns.companyId, companyId),
+ eq(companySkillTestRuns.skillId, skillId),
+ sourceInput?.id
+ ? eq(companySkillTestRuns.inputId, sourceInput.id)
+ : isNull(companySkillTestRuns.inputId),
+ isNull(companySkillTestRuns.supersededAt),
+ ));
+ return await tx
+ .insert(companySkillTestRuns)
+ .values({
+ id: runId,
+ companyId,
+ skillId,
+ inputId: sourceInput?.id ?? null,
+ inputSnapshot,
+ skillVersionId: version.id,
+ agentId: agent.id,
+ agentConfigSnapshot: snapshotAgentConfig(agent),
+ issueId,
+ templateId: templateSnapshot?.templateId ?? null,
+ templateName: templateSnapshot?.templateName ?? null,
+ templateBody: templateSnapshot?.templateBody ?? null,
+ renderedTemplateBody,
+ harnessIssueDescription,
+ status: "queued",
+ outputDocumentKey,
+ })
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ }).catch(async (error) => {
+ await cleanupCreatedHarnessIssue();
+ throw error;
+ });
+ if (!row) {
+ await cleanupCreatedHarnessIssue();
+ throw notFound("Failed to persist skill test run");
+ }
+ await deps.wakeHarnessIssue(issueId, agent.id);
+ return (await hydrateTestRuns(companyId, [row]))[0]!;
+ }
+
+ async function listTestRuns(
+ companyId: string,
+ skillId: string,
+ query: CompanySkillTestRunListQuery = {},
+ ): Promise<CompanySkillTestRun[]> {
+ const skill = await getById(companyId, skillId);
+ if (!skill) throw notFound("Skill not found");
+ const conditions = [
+ eq(companySkillTestRuns.companyId, companyId),
+ eq(companySkillTestRuns.skillId, skillId),
+ isNull(companySkillTestRuns.deletedAt),
+ ];
+ if (query.inputId) conditions.push(eq(companySkillTestRuns.inputId, query.inputId));
+ const rows = await db
+ .select()
+ .from(companySkillTestRuns)
+ .where(and(...conditions))
+ .orderBy(desc(companySkillTestRuns.createdAt), desc(companySkillTestRuns.id));
+ return hydrateTestRuns(companyId, rows);
+ }
+
+ async function getTestRunDetail(companyId: string, skillId: string, runId: string): Promise<CompanySkillTestRunDetail | null> {
+ const row = await db
+ .select()
+ .from(companySkillTestRuns)
+ .where(and(
+ eq(companySkillTestRuns.companyId, companyId),
+ eq(companySkillTestRuns.skillId, skillId),
+ eq(companySkillTestRuns.id, runId),
+ isNull(companySkillTestRuns.deletedAt),
+ ))
+ .then((rows) => rows[0] ?? null);
+ if (!row) return null;
+ const [run] = await hydrateTestRuns(companyId, [row]);
+ if (!run) return null;
+ const harnessIssueGone = Boolean(row.harnessIssueDeletedAt);
+ const [version, issue, documentRows, interactionRows, attachmentRows, workProductRows] = await Promise.all([
+ getVersion(companyId, skillId, row.skillVersionId),
+ harnessIssueGone
+ ? Promise.resolve(null)
+ : db
+ .select({
+ id: issues.id,
+ identifier: issues.identifier,
+ title: issues.title,
+ status: issues.status,
+ hiddenAt: issues.hiddenAt,
+ })
+ .from(issues)
+ .where(and(eq(issues.companyId, companyId), eq(issues.id, row.issueId)))
+ .then((rows) => rows[0] ?? null),
+ harnessIssueGone
+ ? Promise.resolve([])
+ : db
+ .select(issueDocumentSelect)
+ .from(issueDocuments)
+ .innerJoin(documents, eq(issueDocuments.documentId, documents.id))
+ .where(and(eq(issueDocuments.companyId, companyId), eq(issueDocuments.issueId, row.issueId)))
+ .orderBy(asc(issueDocuments.key)),
+ harnessIssueGone
+ ? Promise.resolve([])
+ : db
+ .select({
+ id: issueThreadInteractions.id,
+ kind: issueThreadInteractions.kind,
+ status: issueThreadInteractions.status,
+ title: issueThreadInteractions.title,
+ createdAt: issueThreadInteractions.createdAt,
+ updatedAt: issueThreadInteractions.updatedAt,
+ })
+ .from(issueThreadInteractions)
+ .where(and(eq(issueThreadInteractions.companyId, companyId), eq(issueThreadInteractions.issueId, row.issueId)))
+ .orderBy(desc(issueThreadInteractions.createdAt)),
+ harnessIssueGone
+ ? Promise.resolve([])
+ : db
+ .select({
+ id: issueAttachments.id,
+ companyId: issueAttachments.companyId,
+ issueId: issueAttachments.issueId,
+ issueCommentId: issueAttachments.issueCommentId,
+ assetId: issueAttachments.assetId,
+ provider: assets.provider,
+ objectKey: assets.objectKey,
+ contentType: assets.contentType,
+ byteSize: assets.byteSize,
+ sha256: assets.sha256,
+ originalFilename: assets.originalFilename,
+ createdByAgentId: assets.createdByAgentId,
+ createdByUserId: assets.createdByUserId,
+ createdAt: issueAttachments.createdAt,
+ updatedAt: issueAttachments.updatedAt,
+ })
+ .from(issueAttachments)
+ .innerJoin(assets, eq(issueAttachments.assetId, assets.id))
+ .where(and(eq(issueAttachments.companyId, companyId), eq(issueAttachments.issueId, row.issueId)))
+ .orderBy(desc(issueAttachments.createdAt)),
+ harnessIssueGone
+ ? Promise.resolve([])
+ : db
+ .select()
+ .from(issueWorkProducts)
+ .where(and(eq(issueWorkProducts.companyId, companyId), eq(issueWorkProducts.issueId, row.issueId)))
+ .orderBy(desc(issueWorkProducts.isPrimary), desc(issueWorkProducts.updatedAt)),
+ ]);
+ if (!version) throw notFound("Skill version not found");
+ const harnessAvailable = !harnessIssueGone && issue !== null;
+ const harnessDocuments: IssueDocument[] = harnessAvailable
+ ? documentRows.map((doc) => ({
+ ...mapIssueDocumentRow(doc, false),
+ format: doc.format as IssueDocument["format"],
+ body: doc.latestBody,
+ }))
+ : [];
+ const harnessAttachments: IssueAttachment[] = harnessAvailable
+ ? attachmentRows.map((attachment) => ({
+ ...attachment,
+ contentPath: `/api/attachments/${attachment.id}/content`,
+ openPath: `/api/attachments/${attachment.id}/content`,
+ downloadPath: `/api/attachments/${attachment.id}/content?download=1`,
+ }))
+ : [];
+ const harnessWorkProducts = harnessAvailable ? workProductRows.map(toIssueWorkProduct) : [];
+ const harnessContent: CompanySkillTestRunHarnessContent = {
+ available: harnessAvailable,
+ unavailableReason: harnessAvailable
+ ? null
+ : harnessIssueGone
+ ? (row.harnessIssueExpiresAt && row.harnessIssueDeletedAt && row.harnessIssueExpiresAt <= row.harnessIssueDeletedAt
+ ? "expired"
+ : "deleted")
+ : "missing",
+ documents: harnessDocuments,
+ attachments: harnessAttachments,
+ workProducts: harnessWorkProducts,
+ };
+ return {
+ ...run,
+ skillVersion: version,
+ outputBody: run.outputSnapshot,
+ harnessContent,
+ harnessIssue: issue ? {
+ id: issue.id,
+ identifier: issue.identifier ?? null,
+ title: issue.title,
+ status: issue.status,
+ hiddenAt: issue.hiddenAt ?? null,
+ } : null,
+ documents: harnessDocuments.map((doc) => ({
+ key: doc.key,
+ title: doc.title ?? null,
+ updatedAt: doc.updatedAt,
+ body: doc.body,
+ })),
+ interactions: interactionRows.map((interaction) => ({
+ id: interaction.id,
+ kind: interaction.kind,
+ status: interaction.status,
+ title: interaction.title ?? interaction.kind,
+ createdAt: interaction.createdAt,
+ updatedAt: interaction.updatedAt,
+ })),
+ artifacts: [
+ ...harnessAttachments.map((attachment) => ({
+ id: attachment.id,
+ kind: "attachment" as const,
+ title: attachment.originalFilename ?? "Attachment",
+ summary: null,
+ createdAt: attachment.createdAt,
+ })),
+ ...harnessWorkProducts.map((product) => ({
+ id: product.id,
+ kind: "work_product" as const,
+ title: product.title,
+ summary: product.summary ?? null,
+ createdAt: product.createdAt,
+ })),
+ ].sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime()),
+ };
+ }
+
+ async function completeTestRunForIssue(input: {
+ companyId: string;
+ issueId: string;
+ outcome: "succeeded" | "failed" | "cancelled";
+ error?: string | null;
+ }): Promise<CompanySkillTestRun | null> {
+ const row = await db
+ .select()
+ .from(companySkillTestRuns)
+ .where(and(
+ eq(companySkillTestRuns.companyId, input.companyId),
+ eq(companySkillTestRuns.issueId, input.issueId),
+ isNull(companySkillTestRuns.deletedAt),
+ isNull(companySkillTestRuns.supersededAt),
+ ))
+ .then((rows) => rows[0] ?? null);
+ if (!row || ["succeeded", "failed", "cancelled"].includes(row.status)) return row
+ ? (await hydrateTestRuns(input.companyId, [row]))[0] ?? null
+ : null;
+
+ const outputDocumentKey = row.outputDocumentKey || "output";
+ const outputDocument = await db
+ .select({ body: documents.latestBody })
+ .from(issueDocuments)
+ .innerJoin(documents, eq(issueDocuments.documentId, documents.id))
+ .where(and(
+ eq(issueDocuments.companyId, input.companyId),
+ eq(issueDocuments.issueId, input.issueId),
+ eq(issueDocuments.key, outputDocumentKey),
+ ))
+ .then((rows) => rows[0] ?? null);
+ const updated = await db
+ .update(companySkillTestRuns)
+ .set({
+ status: input.outcome,
+ outputSnapshot: outputDocument?.body ?? row.outputSnapshot ?? "",
+ error: input.error ?? null,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(companySkillTestRuns.companyId, input.companyId), eq(companySkillTestRuns.id, row.id)))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ return updated ? (await hydrateTestRuns(input.companyId, [updated]))[0] ?? null : null;
+ }
+
+ async function markTestRunRunning(companyId: string, issueId: string): Promise<CompanySkillTestRun | null> {
+ const row = await db
+ .update(companySkillTestRuns)
+ .set({ status: "running", updatedAt: new Date() })
+ .where(and(
+ eq(companySkillTestRuns.companyId, companyId),
+ eq(companySkillTestRuns.issueId, issueId),
+ eq(companySkillTestRuns.status, "queued"),
+ isNull(companySkillTestRuns.deletedAt),
+ isNull(companySkillTestRuns.supersededAt),
+ ))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ return row ? (await hydrateTestRuns(companyId, [row]))[0] ?? null : null;
+ }
+
+ async function cancelTestRun(
+ companyId: string,
+ skillId: string,
+ runId: string,
+ deps: { cancelHarnessIssue: (issueId: string) => Promise<unknown> },
+ ): Promise<CompanySkillTestRun | null> {
+ const existing = await db
+ .select()
+ .from(companySkillTestRuns)
+ .where(and(
+ eq(companySkillTestRuns.companyId, companyId),
+ eq(companySkillTestRuns.skillId, skillId),
+ eq(companySkillTestRuns.id, runId),
+ isNull(companySkillTestRuns.deletedAt),
+ isNull(companySkillTestRuns.supersededAt),
+ ))
+ .then((rows) => rows[0] ?? null);
+ if (!existing) return null;
+ if (["succeeded", "failed", "cancelled"].includes(existing.status)) {
+ return (await hydrateTestRuns(companyId, [existing]))[0] ?? null;
+ }
+ await deps.cancelHarnessIssue(existing.issueId);
+ return completeTestRunForIssue({
+ companyId,
+ issueId: existing.issueId,
+ outcome: "cancelled",
+ error: "Cancelled by operator",
+ });
+ }
+
+ async function deleteTestRun(
+ companyId: string,
+ skillId: string,
+ runId: string,
+ deps: { hideHarnessIssue: (issueId: string) => Promise<unknown> },
+ ): Promise<CompanySkillTestRun | null> {
+ const existing = await db
+ .select()
+ .from(companySkillTestRuns)
+ .where(and(
+ eq(companySkillTestRuns.companyId, companyId),
+ eq(companySkillTestRuns.skillId, skillId),
+ eq(companySkillTestRuns.id, runId),
+ isNull(companySkillTestRuns.deletedAt),
+ ))
+ .then((rows) => rows[0] ?? null);
+ if (!existing) return null;
+ // Only terminal runs are deletable — an in-flight run must be cancelled first
+ // so we never orphan a live harness task.
+ if (!["succeeded", "failed", "cancelled"].includes(existing.status)) {
+ throw unprocessable("Cancel the run before deleting it.");
+ }
+ const now = new Date();
+ const updated = await db.transaction(async (tx) => {
+ return await tx
+ .update(companySkillTestRuns)
+ .set({ deletedAt: now, harnessIssueDeletedAt: existing.harnessIssueDeletedAt ?? now, updatedAt: now })
+ .where(and(
+ eq(companySkillTestRuns.companyId, companyId),
+ eq(companySkillTestRuns.id, runId),
+ ))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ });
+ // Hide the (already-terminal) harness task so the deleted run leaves nothing
+ // dangling on the board; best-effort, run row is the source of truth.
+ if (!existing.harnessIssueDeletedAt) {
+ await deps.hideHarnessIssue(existing.issueId).catch(() => {});
+ }
+ return updated ? (await hydrateTestRuns(companyId, [updated]))[0] ?? null : null;
+ }
+
+ async function pruneExpiredTestHarnessIssues(companyId: string, now = new Date()): Promise<{ pruned: number }> {
+ const rows = await db
+ .select({
+ id: companySkillTestRuns.id,
+ issueId: companySkillTestRuns.issueId,
+ })
+ .from(companySkillTestRuns)
+ .where(and(
+ eq(companySkillTestRuns.companyId, companyId),
+ lt(companySkillTestRuns.harnessIssueExpiresAt, now),
+ isNull(companySkillTestRuns.harnessIssueDeletedAt),
+ ));
+ for (const row of rows) {
+ await db.transaction(async (tx) => {
+ await tx
+ .update(issues)
+ .set({ hiddenAt: now, updatedAt: now })
+ .where(and(eq(issues.companyId, companyId), eq(issues.id, row.issueId), eq(issues.harnessKind, "skill_test")));
+ await tx
+ .update(companySkillTestRuns)
+ .set({ harnessIssueDeletedAt: now, updatedAt: now })
+ .where(and(eq(companySkillTestRuns.companyId, companyId), eq(companySkillTestRuns.id, row.id)));
+ });
+ }
+ return { pruned: rows.length };
+ }
+
async function deleteSkill(companyId: string, skillId: string): Promise<CompanySkill | null> {
const row = await db
.select()
@@ -4692,13 +5948,18 @@ export function companySkillService(db: Db) {
listFull,
getById,
getByKey,
+ getByRouteRef,
resolveRequestedSkillKeys: async (companyId: string, requestedReferences: string[]) => {
const skills = await listFull(companyId);
return resolveRequestedSkillKeysOrThrow(skills, requestedReferences);
},
- resolveRequestedSkillEntries: async (companyId: string, requestedSelections: Array<string | AgentDesiredSkillEntry>) => {
+ resolveRequestedSkillEntries: async (
+ companyId: string,
+ requestedSelections: Array<string | AgentDesiredSkillEntry>,
+ options?: { tolerateUnknownReferences?: boolean },
+ ) => {
const skills = await listFull(companyId);
- return resolveRequestedSkillEntriesOrThrow(db, companyId, skills, requestedSelections);
+ return resolveRequestedSkillEntriesOrThrow(db, companyId, skills, requestedSelections, options);
},
categoryCounts,
detail,
@@ -4717,8 +5978,25 @@ export function companySkillService(db: Db) {
readFile,
updateSkill,
updateFile,
+ deleteFile,
createLocalSkill,
deleteSkill,
+ listTestInputs,
+ createTestInput,
+ updateTestInput,
+ deleteTestInput,
+ listTestRunTemplates,
+ createTestRunTemplate,
+ updateTestRunTemplate,
+ deleteTestRunTemplate,
+ createTestRun,
+ listTestRuns,
+ getTestRunDetail,
+ completeTestRunForIssue,
+ markTestRunRunning,
+ cancelTestRun,
+ deleteTestRun,
+ pruneExpiredTestHarnessIssues,
importFromSource,
installFromCatalog,
scanProjectWorkspaces,
diff --git a/server/src/services/costs.ts b/server/src/services/costs.ts
index 05008d8222..781d0cae11 100644
--- a/server/src/services/costs.ts
+++ b/server/src/services/costs.ts
@@ -4,6 +4,7 @@ import type { Db } from "@paperclipai/db";
import { activityLog, agents, companies, costEvents, heartbeatRuns, issues, projects } from "@paperclipai/db";
import { notFound, unprocessable } from "../errors.js";
import { budgetService, type BudgetServiceHooks } from "./budgets.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
export interface CostDateRange {
from?: Date;
@@ -153,6 +154,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
WHERE ${issues.companyId} = ${companyId}
AND ${issues.parentId} = ${issueId}
AND ${issues.hiddenAt} IS NULL
+ AND ${issues.harnessKind} IS NULL
`
: sql`
SELECT ${issues.id}
@@ -160,6 +162,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
WHERE ${issues.companyId} = ${companyId}
AND ${issues.id} = ${issueId}
AND ${issues.hiddenAt} IS NULL
+ AND ${issues.harnessKind} IS NULL
`;
const cteSeedText = options.excludeRoot
@@ -169,6 +172,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
WHERE ${issues.companyId} = ${companyId}
AND ${issues.parentId} = ${issueId}
AND ${issues.hiddenAt} IS NULL
+ AND ${issues.harnessKind} IS NULL
`
: sql`
SELECT (${issues.id})::text AS id
@@ -176,6 +180,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
WHERE ${issues.companyId} = ${companyId}
AND ${issues.id} = ${issueId}
AND ${issues.hiddenAt} IS NULL
+ AND ${issues.harnessKind} IS NULL
`;
const issueTreeCondition = sql<boolean>`
@@ -188,6 +193,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
JOIN issue_tree ON ${childIssues.parentId} = issue_tree.id
WHERE ${childIssues.companyId} = ${companyId}
AND ${childIssues.hiddenAt} IS NULL
+ AND ${childIssues.harnessKind} IS NULL
)
SELECT id FROM issue_tree
)
@@ -202,6 +208,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
JOIN issue_tree ON (${childIssues.parentId})::text = issue_tree.id
WHERE ${childIssues.companyId} = ${companyId}
AND ${childIssues.hiddenAt} IS NULL
+ AND ${childIssues.harnessKind} IS NULL
)
SELECT
count(distinct ${heartbeatRuns.id})::int AS "runCount",
@@ -245,7 +252,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
.where(
and(
eq(issues.companyId, companyId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
issueTreeCondition,
),
),
diff --git a/server/src/services/dashboard.ts b/server/src/services/dashboard.ts
index 1493a3f59e..20d47dbfef 100644
--- a/server/src/services/dashboard.ts
+++ b/server/src/services/dashboard.ts
@@ -3,6 +3,7 @@ import type { Db } from "@paperclipai/db";
import { agents, approvals, companies, costEvents, heartbeatRuns, issues } from "@paperclipai/db";
import { notFound } from "../errors.js";
import { budgetService } from "./budgets.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
const DASHBOARD_RUN_ACTIVITY_DAYS = 14;
@@ -43,7 +44,7 @@ export function dashboardService(db: Db) {
const taskRows = await db
.select({ status: issues.status, count: sql<number>`count(*)` })
.from(issues)
- .where(eq(issues.companyId, companyId))
+ .where(and(eq(issues.companyId, companyId), visibleIssueCondition()))
.groupBy(issues.status);
const pendingApprovals = await db
diff --git a/server/src/services/documents.ts b/server/src/services/documents.ts
index 78d57f92ae..ff35742650 100644
--- a/server/src/services/documents.ts
+++ b/server/src/services/documents.ts
@@ -39,7 +39,7 @@ export function extractLegacyPlanBody(description: string | null | undefined) {
return body ? body : null;
}
-function mapIssueDocumentRow(
+export function mapIssueDocumentRow(
row: {
id: string;
companyId: string;
@@ -86,7 +86,7 @@ function mapIssueDocumentRow(
};
}
-const issueDocumentSelect = {
+export const issueDocumentSelect = {
id: documents.id,
companyId: documents.companyId,
issueId: issueDocuments.issueId,
diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts
index 5a5f486cce..13564637c4 100644
--- a/server/src/services/execution-workspaces.ts
+++ b/server/src/services/execution-workspaces.ts
@@ -27,6 +27,7 @@ import { deriveProjectUrlKey, WORKSPACE_OVERVIEW_LINKED_ISSUE_LIMIT } from "@pap
import { conflict, notFound, unprocessable } from "../errors.js";
import { parseProjectExecutionWorkspacePolicy } from "./execution-workspace-policy.js";
import { issueRecoveryActionService } from "./issue-recovery-actions.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
import { readProjectWorkspaceRuntimeConfig } from "./project-workspace-runtime-config.js";
import {
listCurrentRuntimeServicesForExecutionWorkspaces,
@@ -890,7 +891,7 @@ export function executionWorkspaceService(db: Db) {
.where(
and(
eq(issues.companyId, companyId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
inArray(issues.executionWorkspaceId, workspaceIds),
),
)
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index a88f597d27..0f305846da 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -33,6 +33,8 @@ import {
activityLog,
approvals,
companyMemberships,
+ companySkillTestRuns,
+ companySkillVersions,
companySkills as companySkillsTable,
companies,
costEvents,
@@ -112,6 +114,7 @@ import {
sanitizeRuntimeServiceBaseEnv,
} from "./workspace-runtime.js";
import { issueService } from "./issues.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
import {
ISSUE_BLOCKERS_RESOLVED_WAKE_REASON,
} from "./issue-dependency-wakeups.js";
@@ -4244,6 +4247,7 @@ export async function buildPaperclipWakePayload(input: {
: [],
executionStage: Object.keys(executionStage).length > 0 ? executionStage : null,
taskWatchdog: (input.contextSnapshot.taskWatchdog ?? null) as unknown,
+ skillTest: (input.contextSnapshot.paperclipSkillTest ?? null) as unknown,
continuationSummary: safeContinuationSummary
? {
key: safeContinuationSummary.key,
@@ -4589,6 +4593,13 @@ export function buildPaperclipTaskMarkdown(input: {
"Planning mode directive:",
directive,
);
+ } else if (issue.workMode === "skill_test") {
+ lines.push(
+ `- Work mode: ${quoteTaskScalar("skill_test")}`,
+ "",
+ "Skill test mode directive:",
+ "You are testing a pinned skill revision. Make no durable changes outside this issue. Do not push, publish, send external messages, or mutate other issues. Write your final output as issue document `output`, then finish by marking this issue done.",
+ );
} else if (acceptedPlanContinuation) {
lines.push(
"",
@@ -4717,6 +4728,40 @@ export function normalizeSessionParams(params: Record<string, unknown> | null |
type RunSessionOutcome = "succeeded" | "interrupted" | "failed" | "cancelled" | "timed_out";
+type SkillTestHeartbeatCompletion = {
+ outcome: "failed" | "cancelled";
+ error: string | null;
+ heartbeatOutcome: RunSessionOutcome;
+};
+
+export function resolveSkillTestRunCompletionForHeartbeatOutcome(
+ outcome: RunSessionOutcome,
+ error: string | null | undefined,
+): SkillTestHeartbeatCompletion | null {
+ if (outcome === "cancelled") {
+ return {
+ outcome: "cancelled",
+ error: error ?? "Harness run was cancelled",
+ heartbeatOutcome: outcome,
+ };
+ }
+ if (outcome === "timed_out") {
+ return {
+ outcome: "failed",
+ error: error ?? "Timed out",
+ heartbeatOutcome: outcome,
+ };
+ }
+ if (outcome === "failed") {
+ return {
+ outcome: "failed",
+ error: error ?? "Adapter failed",
+ heartbeatOutcome: outcome,
+ };
+ }
+ return null;
+}
+
const HERMES_ADAPTER_TYPE = "hermes_local";
const HERMES_SESSION_ID_REGEX = /^(?:\d{8}_\d{6}_[A-Za-z0-9_-]{4,}|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
@@ -4888,8 +4933,9 @@ function isTruthyRuntimeEnvValue(value: string | undefined) {
export function resolveHeartbeatSchedulingSuppression(
env: Record<string, string | undefined> = process.env,
+ overrides: { allowWorktreeRunExecution?: boolean } = {},
): { suppressed: boolean; reason: "worktree_instance" | "database_restore_in_progress" | null } {
- if (isTruthyRuntimeEnvValue(env.PAPERCLIP_IN_WORKTREE)) {
+ if (isTruthyRuntimeEnvValue(env.PAPERCLIP_IN_WORKTREE) && !overrides.allowWorktreeRunExecution) {
return { suppressed: true, reason: "worktree_instance" };
}
if (
@@ -4907,7 +4953,37 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
enabled: (await instanceSettings.getGeneral()).censorUsernameInLogs,
});
const runtimeEnv = options.runtimeEnv ?? process.env;
- const getSchedulingSuppression = () => resolveHeartbeatSchedulingSuppression(runtimeEnv);
+ const inWorktreeRuntime = isTruthyRuntimeEnvValue(runtimeEnv.PAPERCLIP_IN_WORKTREE);
+ // Preview worktree instances suppress the run engine by default. Users can lift
+ // that per-worktree via the `enableWorktreeRunExecution` experimental setting
+ // (worktree instances have their own isolated DB, so it can't affect the parent).
+ // Only worktree runtimes ever read the setting; a short TTL keeps the hot-path
+ // suppression checks off the DB, and a read failure falls back to prior/default
+ // (fail closed to suppression).
+ let cachedWorktreeRunExecutionOverride: { value: boolean; at: number } = { value: false, at: 0 };
+ const WORKTREE_RUN_EXECUTION_OVERRIDE_TTL_MS = 3_000;
+ const resolveWorktreeRunExecutionOverride = async (): Promise<boolean> => {
+ if (!inWorktreeRuntime) return false;
+ const now = Date.now();
+ if (now - cachedWorktreeRunExecutionOverride.at < WORKTREE_RUN_EXECUTION_OVERRIDE_TTL_MS) {
+ return cachedWorktreeRunExecutionOverride.value;
+ }
+ try {
+ const experimental = await instanceSettings.getExperimental();
+ cachedWorktreeRunExecutionOverride = {
+ value: experimental.enableWorktreeRunExecution === true,
+ at: now,
+ };
+ } catch {
+ // Keep the prior (default-false) value so a settings read failure fails
+ // closed to the safe suppressed state.
+ }
+ return cachedWorktreeRunExecutionOverride.value;
+ };
+ const getSchedulingSuppression = async () =>
+ resolveHeartbeatSchedulingSuppression(runtimeEnv, {
+ allowWorktreeRunExecution: await resolveWorktreeRunExecutionOverride(),
+ });
const runLogStore = getRunLogStore();
const secretsSvc = secretService(db);
@@ -4938,6 +5014,72 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
const taskWatchdogs = taskWatchdogService(db, { enqueueWakeup });
let unsafeTextProjectionPromise: Promise<boolean> | null = null;
+ async function completeSkillTestRunForHeartbeatOutcome(input: {
+ run: typeof heartbeatRuns.$inferSelect;
+ issueId: string | null;
+ issueWorkMode?: string | null;
+ outcome: RunSessionOutcome;
+ error: string | null;
+ }) {
+ const completion = resolveSkillTestRunCompletionForHeartbeatOutcome(input.outcome, input.error);
+ if (!completion || !input.issueId) return null;
+
+ let isSkillTestIssue = input.issueWorkMode === "skill_test";
+ if (!isSkillTestIssue && input.issueWorkMode === undefined) {
+ const issueRow = await db
+ .select({
+ workMode: issues.workMode,
+ harnessKind: issues.harnessKind,
+ })
+ .from(issues)
+ .where(and(eq(issues.companyId, input.run.companyId), eq(issues.id, input.issueId)))
+ .then((rows) => rows[0] ?? null);
+ isSkillTestIssue = issueRow?.workMode === "skill_test" || issueRow?.harnessKind === "skill_test";
+ }
+ if (!isSkillTestIssue) return null;
+
+ const existingRun = await db
+ .select({
+ id: companySkillTestRuns.id,
+ status: companySkillTestRuns.status,
+ })
+ .from(companySkillTestRuns)
+ .where(and(
+ eq(companySkillTestRuns.companyId, input.run.companyId),
+ eq(companySkillTestRuns.issueId, input.issueId),
+ ))
+ .then((rows) => rows[0] ?? null);
+ if (!existingRun || ["succeeded", "failed", "cancelled"].includes(existingRun.status)) return null;
+
+ const completedRun = await companySkills.completeTestRunForIssue({
+ companyId: input.run.companyId,
+ issueId: input.issueId,
+ outcome: completion.outcome,
+ error: completion.error,
+ });
+ if (!completedRun) return null;
+
+ await logActivity(db, {
+ companyId: input.run.companyId,
+ actorType: "system",
+ actorId: "heartbeat_finalize",
+ agentId: input.run.agentId,
+ runId: input.run.id,
+ action: "company.skill_test_run_completed",
+ entityType: "company_skill_test_run",
+ entityId: completedRun.id,
+ details: {
+ issueId: input.issueId,
+ status: completedRun.status,
+ outputDocumentKey: completedRun.outputDocumentKey,
+ heartbeatOutcome: completion.heartbeatOutcome,
+ source: "heartbeat.run_finalized",
+ },
+ });
+
+ return completedRun;
+ }
+
async function releaseEnvironmentLeasesForRun(input: {
runId: string;
companyId: string;
@@ -5103,6 +5245,54 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
.then((rows) => rows[0] ?? null);
}
+ async function getPinnedSkillTestContext(companyId: string, issueId: string) {
+ const row = await db
+ .select({
+ testRunId: companySkillTestRuns.id,
+ skillId: companySkillTestRuns.skillId,
+ inputId: companySkillTestRuns.inputId,
+ skillVersionId: companySkillTestRuns.skillVersionId,
+ outputDocumentKey: companySkillTestRuns.outputDocumentKey,
+ fileInventory: companySkillVersions.fileInventory,
+ revisionNumber: companySkillVersions.revisionNumber,
+ label: companySkillVersions.label,
+ })
+ .from(companySkillTestRuns)
+ .innerJoin(
+ companySkillVersions,
+ and(
+ eq(companySkillVersions.id, companySkillTestRuns.skillVersionId),
+ eq(companySkillVersions.companyId, companySkillTestRuns.companyId),
+ ),
+ )
+ .where(and(eq(companySkillTestRuns.companyId, companyId), eq(companySkillTestRuns.issueId, issueId)))
+ .then((rows) => rows[0] ?? null);
+ if (!row) return null;
+ const fileInventory = Array.isArray(row.fileInventory)
+ ? row.fileInventory.flatMap((entry) => {
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [];
+ const record = entry as unknown as Record<string, unknown>;
+ const path = typeof record.path === "string" ? record.path : "";
+ if (!path) return [];
+ return [{
+ path,
+ kind: typeof record.kind === "string" ? record.kind : "other",
+ content: typeof record.content === "string" ? record.content : "",
+ }];
+ })
+ : [];
+ return {
+ testRunId: row.testRunId,
+ skillId: row.skillId,
+ inputId: row.inputId ?? null,
+ skillVersionId: row.skillVersionId,
+ revisionNumber: row.revisionNumber,
+ label: row.label ?? null,
+ outputDocumentKey: row.outputDocumentKey,
+ fileInventory,
+ };
+ }
+
async function getRoutineEnvForExecutionIssue(
companyId: string,
issueContext: Awaited<ReturnType<typeof getIssueExecutionContext>> | null,
@@ -5500,7 +5690,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
eq(issues.companyId, claimed.companyId),
eq(issues.originKind, RECOVERY_ORIGIN_KINDS.strandedIssueRecovery),
eq(issues.originId, claimed.id),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, ["done", "cancelled"]),
),
)
@@ -7120,7 +7310,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
RECOVERY_ORIGIN_KINDS.issueGraphLivenessEscalation,
]),
eq(issues.originId, issue.id),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, ["done", "cancelled"]),
),
)
@@ -9979,7 +10169,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
}
async function resumeQueuedRuns() {
- if (getSchedulingSuppression().suppressed) return;
+ if ((await getSchedulingSuppression()).suppressed) return;
const queuedRuns = await db
.select({ agentId: heartbeatRuns.agentId })
@@ -10107,7 +10297,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
}
async function startNextQueuedRunForAgent(agentId: string) {
- if (getSchedulingSuppression().suppressed) return [];
+ if ((await getSchedulingSuppression()).suppressed) return [];
return withAgentStartLock(agentId, async () => {
const agent = await getAgent(agentId);
@@ -10187,7 +10377,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
}
async function executeRun(runId: string) {
- if (getSchedulingSuppression().suppressed) return;
+ if ((await getSchedulingSuppression()).suppressed) return;
let run = await getRun(runId);
if (!run) return;
@@ -10455,6 +10645,18 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
} else {
delete context.paperclipContinuationSummary;
}
+ const pinnedSkillTestContext =
+ issueRef?.workMode === "skill_test"
+ ? await getPinnedSkillTestContext(agent.companyId, issueRef.id)
+ : null;
+ if (pinnedSkillTestContext) {
+ context.paperclipSkillTest = {
+ ...pinnedSkillTestContext,
+ directive: "Use this pinned file inventory as the exact skill revision under test, regardless of synced runtime skills.",
+ };
+ } else {
+ delete context.paperclipSkillTest;
+ }
const paperclipWakePayload = await buildPaperclipWakePayload({
db,
companyId: agent.companyId,
@@ -11729,8 +11931,19 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
};
const adapter = getServerAdapter(agent.adapterType);
+ const localAgentJwtScope =
+ issueRef?.workMode === "skill_test"
+ ? { kind: "skill_test" as const, issueId: issueRef.id }
+ : { kind: "standard" as const };
const authToken = adapter.supportsLocalAgentJwt
- ? createLocalAgentJwt(agent.id, agent.companyId, agent.adapterType, run.id, run.responsibleUserId)
+ ? createLocalAgentJwt(
+ agent.id,
+ agent.companyId,
+ agent.adapterType,
+ run.id,
+ run.responsibleUserId,
+ localAgentJwtScope,
+ )
: null;
if (adapter.supportsLocalAgentJwt && !authToken) {
logger.warn(
@@ -12185,6 +12398,24 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
exitCode: adapterResult.exitCode,
},
});
+ try {
+ await completeSkillTestRunForHeartbeatOutcome({
+ run: finalizedRun,
+ issueId,
+ issueWorkMode: issueRef?.workMode ?? null,
+ outcome,
+ error: runErrorMessage,
+ });
+ } catch (err) {
+ logger.warn(
+ { err, runId: finalizedRun.id, issueId },
+ "failed to complete skill test run after heartbeat finalization",
+ );
+ await onLog(
+ "stderr",
+ `[paperclip] Failed to complete skill test run: ${err instanceof Error ? err.message : String(err)}\n`,
+ );
+ }
const livenessRun = finalizedRun;
await refreshContinuationSummaryForRun(livenessRun, agent);
const skipRunIssueComment = parseObject(livenessRun.contextSnapshot).skipIssueComment === true;
@@ -12381,6 +12612,20 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
message,
});
const livenessRun = await classifyAndPersistRunLiveness(failedRun) ?? failedRun;
+ try {
+ await completeSkillTestRunForHeartbeatOutcome({
+ run: livenessRun,
+ issueId,
+ issueWorkMode: issueRef?.workMode ?? null,
+ outcome: "failed",
+ error: message,
+ });
+ } catch (err) {
+ logger.warn(
+ { err, runId: livenessRun.id, issueId },
+ "failed to complete skill test run after heartbeat adapter failure",
+ );
+ }
await refreshContinuationSummaryForRun(livenessRun, agent);
if (!isWorkspaceValidationFailedRun(livenessRun) && !isConfigurationIncompleteFailedRun(livenessRun)) {
await finalizeIssueCommentPolicy(livenessRun, agent);
@@ -12476,6 +12721,20 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
message,
}).catch(() => undefined);
const livenessRun = await classifyAndPersistRunLiveness(failedRun).catch(() => failedRun);
+ const setupFailureIssueId = readNonEmptyString(parseObject(livenessRun.contextSnapshot).issueId);
+ if (setupFailureIssueId) {
+ await completeSkillTestRunForHeartbeatOutcome({
+ run: livenessRun,
+ issueId: setupFailureIssueId,
+ outcome: "failed",
+ error: message,
+ }).catch((completionErr) => {
+ logger.warn(
+ { err: completionErr, runId: livenessRun.id, issueId: setupFailureIssueId },
+ "failed to complete skill test run after heartbeat setup failure",
+ );
+ });
+ }
const failedAgent = setupFailureAgent ?? await getAgent(run.agentId).catch(() => null);
if (failedAgent) {
await refreshContinuationSummaryForRun(livenessRun, failedAgent).catch(() => undefined);
@@ -13420,7 +13679,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
});
};
- const schedulingSuppression = getSchedulingSuppression();
+ const schedulingSuppression = await getSchedulingSuppression();
if (schedulingSuppression.suppressed) {
await writeSkippedHeartbeatRequest("heartbeat.scheduling_suppressed", {
reason: schedulingSuppression.reason,
@@ -15008,6 +15267,10 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
reportRunActivity: clearDetachedRunWarning,
reapOrphanedRuns,
+ // Override-aware scheduling-suppression check (honors the worktree
+ // run-execution experimental setting). Callers outside the service that
+ // gate on suppression should prefer this over the env-only resolver.
+ resolveSchedulingSuppression: getSchedulingSuppression,
drainRunningRunsForShutdown,
promoteDueScheduledRetries,
@@ -15050,7 +15313,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
buildRunOutputSilence,
tickTimers: async (now = new Date()) => {
- if (getSchedulingSuppression().suppressed) {
+ if ((await getSchedulingSuppression()).suppressed) {
return {
checked: 0,
enqueued: 0,
diff --git a/server/src/services/instance-settings.ts b/server/src/services/instance-settings.ts
index cdb0ef3047..55f08f1f29 100644
--- a/server/src/services/instance-settings.ts
+++ b/server/src/services/instance-settings.ts
@@ -59,6 +59,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
autoRestartDevServerWhenIdle: parsed.data.autoRestartDevServerWhenIdle ?? false,
enableIssueGraphLivenessAutoRecovery: parsed.data.enableIssueGraphLivenessAutoRecovery ?? false,
enableWorkspaceBranchReconcileForward: parsed.data.enableWorkspaceBranchReconcileForward ?? false,
+ enableWorktreeRunExecution: parsed.data.enableWorktreeRunExecution ?? false,
issueGraphLivenessAutoRecoveryLookbackHours:
parsed.data.issueGraphLivenessAutoRecoveryLookbackHours ??
DEFAULT_ISSUE_GRAPH_LIVENESS_AUTO_RECOVERY_LOOKBACK_HOURS,
@@ -80,6 +81,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
autoRestartDevServerWhenIdle: false,
enableIssueGraphLivenessAutoRecovery: false,
enableWorkspaceBranchReconcileForward: false,
+ enableWorktreeRunExecution: false,
issueGraphLivenessAutoRecoveryLookbackHours:
DEFAULT_ISSUE_GRAPH_LIVENESS_AUTO_RECOVERY_LOOKBACK_HOURS,
};
diff --git a/server/src/services/issue-visibility.ts b/server/src/services/issue-visibility.ts
new file mode 100644
index 0000000000..8857e79bb1
--- /dev/null
+++ b/server/src/services/issue-visibility.ts
@@ -0,0 +1,10 @@
+import { and, isNull, type SQL } from "drizzle-orm";
+import { issues } from "@paperclipai/db";
+
+export function visibleIssueCondition(): SQL {
+ return and(isNull(issues.hiddenAt), isNull(issues.harnessKind))!;
+}
+
+export function visibleIssueSql(alias = "issues") {
+ return `"${alias}"."hidden_at" IS NULL AND "${alias}"."harness_kind" IS NULL`;
+}
diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts
index 213a3dc044..2f75a672bf 100644
--- a/server/src/services/issues.ts
+++ b/server/src/services/issues.ts
@@ -101,6 +101,7 @@ import {
RECOVERY_ORIGIN_KINDS,
} from "./recovery/origins.js";
import { classifyIssueGraphLiveness, type IssueLivenessFinding } from "./recovery/issue-graph-liveness.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
const ALL_ISSUE_STATUSES = ["backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"];
const MAX_ISSUE_COMMENT_PAGE_LIMIT = 500;
@@ -1728,6 +1729,7 @@ async function liveDescendantCountMapForIssues(
JOIN heartbeat_runs live_run ON live_run.id = live_issue.execution_run_id
WHERE live_issue.company_id = ${companyId}
AND live_issue.hidden_at IS NULL
+ AND live_issue.harness_kind IS NULL
AND live_run.company_id = ${companyId}
AND live_run.status IN ('queued', 'running')
UNION
@@ -1736,6 +1738,7 @@ async function liveDescendantCountMapForIssues(
JOIN issues live_issue ON live_issue.id::text = (live_run.context_snapshot ->> 'issueId')
WHERE live_issue.company_id = ${companyId}
AND live_issue.hidden_at IS NULL
+ AND live_issue.harness_kind IS NULL
AND live_run.company_id = ${companyId}
AND live_run.status IN ('queued', 'running')
),
@@ -1745,6 +1748,7 @@ async function liveDescendantCountMapForIssues(
JOIN issues parent ON parent.id = live_issues.parent_id
WHERE parent.company_id = ${companyId}
AND parent.hidden_at IS NULL
+ AND parent.harness_kind IS NULL
UNION ALL
SELECT
live_ancestors.live_issue_id,
@@ -1755,6 +1759,7 @@ async function liveDescendantCountMapForIssues(
JOIN issues parent ON parent.id = live_ancestors.next_parent_id
WHERE parent.company_id = ${companyId}
AND parent.hidden_at IS NULL
+ AND parent.harness_kind IS NULL
AND NOT parent.id = ANY(live_ancestors.visited_issue_ids)
)
SELECT
@@ -1961,7 +1966,7 @@ async function listIssueProductivityReviewMap(
eq(issues.companyId, companyId),
eq(issues.originKind, PRODUCTIVITY_REVIEW_ORIGIN_KIND),
inArray(issues.originId, chunk),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, PRODUCTIVITY_REVIEW_TERMINAL_STATUSES),
),
)
@@ -2226,7 +2231,7 @@ async function listIssueBlockerAttentionMap(
and(
eq(issues.companyId, companyId),
eq(issues.originKind, BLOCKER_ATTENTION_OPEN_RECOVERY_ORIGIN_KIND),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, BLOCKER_ATTENTION_OPEN_RECOVERY_TERMINAL_STATUSES),
),
);
@@ -2429,6 +2434,7 @@ const issueListSelect = {
`,
status: issues.status,
workMode: issues.workMode,
+ harnessKind: issues.harnessKind,
priority: issues.priority,
assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId,
@@ -2978,7 +2984,7 @@ async function listIssueBlockedInboxAttentionMap(
.from(issues)
.where(and(
eq(issues.companyId, companyId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, [...BLOCKED_INBOX_TERMINAL_STATUSES]),
)),
dbOrTx
@@ -3388,7 +3394,7 @@ async function blockedInboxIssueConditions(
) {
const conditions = [
eq(issues.companyId, companyId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, [...BLOCKED_INBOX_TERMINAL_STATUSES]),
];
const touchedByUserId = filters?.touchedByUserId?.trim() || undefined;
@@ -4600,7 +4606,7 @@ export function issueService(db: Db) {
});
}
- const conditions = [eq(issues.companyId, companyId)];
+ const conditions = [eq(issues.companyId, companyId), visibleIssueCondition()];
const assigneeAgentFilter = parseIssueAssigneeAgentFilter(filters?.assigneeAgentId);
assertValidAssigneeAgentFilter(assigneeAgentFilter);
const limit = typeof filters?.limit === "number" && Number.isFinite(filters.limit)
@@ -4723,8 +4729,6 @@ export function issueService(db: Db) {
if (filters?.excludeRoutineExecutions && !filters?.originKind && !filters?.originId) {
conditions.push(ne(issues.originKind, "routine_execution"));
}
- conditions.push(isNull(issues.hiddenAt));
-
const priorityOrder = sql`CASE ${issues.priority} WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END`;
const searchOrder = sql<number>`
CASE
@@ -4847,7 +4851,7 @@ export function issueService(db: Db) {
return countBlockedInboxIssues(db, companyId, filters);
}
- const conditions = [eq(issues.companyId, companyId), isNull(issues.hiddenAt)];
+ const conditions = [eq(issues.companyId, companyId), visibleIssueCondition()];
const statuses = parseStatusFilter(filters?.status);
if (statuses.length === 1) conditions.push(eq(issues.status, statuses[0]!));
else if (statuses.length > 1) conditions.push(inArray(issues.status, statuses));
@@ -4889,7 +4893,7 @@ export function issueService(db: Db) {
) => {
const conditions = [
eq(issues.companyId, companyId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
nonPluginOperationIssueCondition(),
unreadForUserCondition(companyId, userId),
];
@@ -5234,6 +5238,7 @@ export function issueService(db: Db) {
WHERE company_id = ${issue.companyId}
AND id = ${issue.id}
AND hidden_at IS NULL
+ AND harness_kind IS NULL
UNION ALL
SELECT
child.id,
@@ -5254,6 +5259,7 @@ export function issueService(db: Db) {
JOIN issue_tree ON child.parent_id = issue_tree.id
WHERE child.company_id = ${issue.companyId}
AND child.hidden_at IS NULL
+ AND child.harness_kind IS NULL
AND issue_tree.depth < ${maxDepth + 1}
AND NOT child.id = ANY(issue_tree.path)
)
@@ -5320,6 +5326,7 @@ export function issueService(db: Db) {
AND relation.type = 'blocks'
AND blocker.company_id = ${issue.companyId}
AND blocker.hidden_at IS NULL
+ AND blocker.harness_kind IS NULL
AND relation.related_issue_id::text IN (${nodeIdValues})
)
SELECT *
diff --git a/server/src/services/pipeline-case-outputs.ts b/server/src/services/pipeline-case-outputs.ts
index 01fc0edb7c..c71701a2c2 100644
--- a/server/src/services/pipeline-case-outputs.ts
+++ b/server/src/services/pipeline-case-outputs.ts
@@ -25,6 +25,7 @@ import {
type SourceTrustMetadata,
} from "@paperclipai/shared";
import { notFound } from "../errors.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
import { isLowTrustQuarantined, LOW_TRUST_QUARANTINED_BODY } from "./source-trust.js";
const PREVIEW_TEXT_MAX_LENGTH = 500;
@@ -300,7 +301,7 @@ export function pipelineCaseOutputsService(db: Db) {
eq(pipelineCaseIssueLinks.caseId, caseId),
isNull(pipelineCaseIssueLinks.retiredAt),
eq(issues.companyId, companyId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
isNull(issues.cancelledAt),
ne(issues.status, "cancelled"),
))
diff --git a/server/src/services/pipelines-aggregation.ts b/server/src/services/pipelines-aggregation.ts
index 0a6ef574fd..e89d8e27a0 100644
--- a/server/src/services/pipelines-aggregation.ts
+++ b/server/src/services/pipelines-aggregation.ts
@@ -12,6 +12,7 @@ import {
routines,
} from "@paperclipai/db";
import { notFound } from "../errors.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
export const PIPELINE_ATTENTION_DEFAULT_LIMIT = 50;
export const PIPELINE_ATTENTION_MAX_LIMIT = 100;
@@ -569,7 +570,7 @@ export async function loadActiveWorkForCases(
inArray(pipelineCaseIssueLinks.role, ["work", "automation"]),
eq(issues.companyId, companyId),
eq(issues.status, "in_progress"),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
))
.orderBy(desc(issues.updatedAt));
for (const row of rows) {
@@ -721,7 +722,7 @@ async function loadOpenWorkIssuesForCases(db: Db, companyId: string, caseIds: st
eq(issues.companyId, companyId),
ne(issues.status, "done"),
ne(issues.status, "cancelled"),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
))
.orderBy(desc(issues.updatedAt));
for (const row of rows) {
diff --git a/server/src/services/pipelines.ts b/server/src/services/pipelines.ts
index 558339fb52..a4a58a42ef 100644
--- a/server/src/services/pipelines.ts
+++ b/server/src/services/pipelines.ts
@@ -49,6 +49,7 @@ import type { IssueAssignmentWakeupDeps } from "./issue-assignment-wakeup.js";
import { logActivity } from "./activity-log.js";
import { assertAssignableAgent } from "./agent-assignability.js";
import { authorizationService } from "./authorization.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
import {
formatPipelineCaseOutputContextMarkdown,
pipelineCaseOutputsService,
@@ -359,7 +360,7 @@ async function getUsableConversationIssue(db: PipelineDb, companyId: string, iss
.where(and(
eq(issues.companyId, companyId),
eq(issues.id, issueId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
isNull(issues.cancelledAt),
ne(issues.status, "cancelled"),
))
@@ -408,7 +409,7 @@ async function resolveLatestCaseIssueLink(
eq(pipelineCaseIssueLinks.caseId, input.caseId),
inArray(pipelineCaseIssueLinks.role, input.roles),
eq(issues.companyId, input.companyId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
isNull(issues.cancelledAt),
ne(issues.status, "cancelled"),
))
@@ -1924,7 +1925,7 @@ async function postSystemCommentOnLinkedIssues(
inArray(pipelineCaseIssueLinks.role, input.roles),
ne(issues.status, "done"),
ne(issues.status, "cancelled"),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
));
for (const row of rows) {
@@ -2022,7 +2023,7 @@ async function notifyDependentWorkIssuesOfUpstreamContentChange(
eq(issues.companyId, input.companyId),
ne(issues.status, "done"),
ne(issues.status, "cancelled"),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
));
const issueIdsByCase = new Map<string, string[]>();
for (const row of linkRows) {
diff --git a/server/src/services/productivity-review.ts b/server/src/services/productivity-review.ts
index e7fad83898..45962040ba 100644
--- a/server/src/services/productivity-review.ts
+++ b/server/src/services/productivity-review.ts
@@ -14,6 +14,7 @@ import { logger } from "../middleware/logger.js";
import { logActivity } from "./activity-log.js";
import { budgetService } from "./budgets.js";
import { issueService } from "./issues.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
import {
recoveryAssigneeAdapterOverrides,
withRecoveryModelProfileHint,
@@ -250,7 +251,7 @@ export function productivityReviewService(db: Db, deps?: { enqueueWakeup?: Enque
eq(issues.companyId, companyId),
eq(issues.originKind, PRODUCTIVITY_REVIEW_ORIGIN_KIND),
eq(issues.originId, sourceIssueId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, ["done", "cancelled"]),
),
)
@@ -298,7 +299,7 @@ export function productivityReviewService(db: Db, deps?: { enqueueWakeup?: Enque
eq(issues.companyId, companyId),
eq(issues.originKind, PRODUCTIVITY_REVIEW_ORIGIN_KIND),
eq(issues.originId, sourceIssueId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
sql`${issues.status} <> 'cancelled'`,
sql`${issues.createdAt} >= ${cutoff.toISOString()}::timestamptz`,
),
@@ -771,7 +772,7 @@ export function productivityReviewService(db: Db, deps?: { enqueueWakeup?: Enque
.where(
and(
opts?.companyId ? eq(issues.companyId, opts.companyId) : undefined,
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
isNull(issues.assigneeUserId),
inArray(issues.status, ["todo", "in_progress"]),
sql`${issues.assigneeAgentId} is not null`,
diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts
index c9ffde514c..336f5a8fb0 100644
--- a/server/src/services/recovery/service.ts
+++ b/server/src/services/recovery/service.ts
@@ -26,6 +26,7 @@ import {
} from "@paperclipai/db";
import { parseObject, asBoolean, asNumber } from "../../adapters/utils.js";
import { runningProcesses } from "../../adapters/index.js";
+import { visibleIssueCondition } from "../issue-visibility.js";
import { forbidden, notFound } from "../../errors.js";
import { logger } from "../../middleware/logger.js";
import { isPidAlive, isProcessGroupAlive, terminateLocalService } from "../local-service-supervisor.js";
@@ -1010,7 +1011,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
eq(issues.companyId, companyId),
eq(issues.originKind, STALE_ACTIVE_RUN_EVALUATION_ORIGIN_KIND),
eq(issues.originId, runId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, ["done", "cancelled"]),
),
)
@@ -1036,7 +1037,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
eq(issues.companyId, companyId),
eq(issues.originKind, STALE_ACTIVE_RUN_EVALUATION_ORIGIN_KIND),
eq(issues.originId, runId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
eq(issues.status, "done"),
),
)
@@ -1133,7 +1134,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
const [issue] = await db
.select()
.from(issues)
- .where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId), isNull(issues.hiddenAt)))
+ .where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId), visibleIssueCondition()))
.limit(1);
return issue ?? null;
}
@@ -1499,7 +1500,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
? db
.select({ id: issues.id, identifier: issues.identifier, title: issues.title, status: issues.status })
.from(issues)
- .where(and(eq(issues.companyId, input.run.companyId), eq(issues.parentId, input.sourceIssue.id), isNull(issues.hiddenAt)))
+ .where(and(eq(issues.companyId, input.run.companyId), eq(issues.parentId, input.sourceIssue.id), visibleIssueCondition()))
.orderBy(desc(issues.updatedAt))
.limit(8)
: Promise.resolve([]),
@@ -2100,7 +2101,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
eq(issues.companyId, companyId),
eq(issues.originKind, STRANDED_ISSUE_RECOVERY_ORIGIN_KIND),
eq(issues.originId, sourceIssueId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, ["done", "cancelled"]),
),
)
@@ -2641,7 +2642,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
and(
eq(issues.companyId, issue.companyId),
eq(issues.parentId, issue.id),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, ["done", "cancelled"]),
),
);
@@ -3332,7 +3333,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
.from(issues)
.where(
and(
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.originKind, [RECOVERY_ORIGIN_KINDS.issueGraphLivenessEscalation]),
),
));
@@ -3389,7 +3390,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
.innerJoin(heartbeatRuns, eq(issues.executionRunId, heartbeatRuns.id))
.where(
and(
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.originKind, [RECOVERY_ORIGIN_KINDS.issueGraphLivenessEscalation]),
inArray(heartbeatRuns.status, [...EXECUTION_PATH_HEARTBEAT_RUN_STATUSES]),
),
@@ -3431,7 +3432,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
.from(issues)
.where(
and(
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
inArray(issues.originKind, [
STRANDED_ISSUE_RECOVERY_ORIGIN_KIND,
RECOVERY_ORIGIN_KINDS.issueGraphLivenessEscalation,
@@ -3523,7 +3524,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
eq(issues.companyId, companyId),
eq(issues.originKind, RECOVERY_ORIGIN_KINDS.issueGraphLivenessEscalation),
eq(issues.originId, incidentKey),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, ["done", "cancelled"]),
),
)
@@ -3540,7 +3541,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
eq(issues.companyId, finding.companyId),
eq(issues.originKind, RECOVERY_ORIGIN_KINDS.issueGraphLivenessEscalation),
eq(issues.originFingerprint, livenessRecoveryLeafFingerprint(finding)),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, ["done", "cancelled"]),
),
)
@@ -3556,7 +3557,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
and(
eq(issues.companyId, finding.companyId),
eq(issues.originKind, RECOVERY_ORIGIN_KINDS.issueGraphLivenessEscalation),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, ["done", "cancelled"]),
),
);
@@ -3633,7 +3634,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
.where(
and(
eq(issues.originKind, RECOVERY_ORIGIN_KINDS.issueGraphLivenessEscalation),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
notInArray(issues.status, ["done", "cancelled"]),
),
);
@@ -3692,7 +3693,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
.where(
and(
eq(issues.originKind, RECOVERY_ORIGIN_KINDS.issueGraphLivenessEscalation),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
inArray(issues.status, ["done", "cancelled"]),
),
);
@@ -4112,7 +4113,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
const queryCandidates = (afterIssueId: string | null) => {
const filters = [
eq(issues.status, "blocked"),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
sql`${issues.assigneeAgentId} is not null`,
];
if (opts?.companyId) filters.push(eq(issues.companyId, opts.companyId));
diff --git a/server/src/services/routines.ts b/server/src/services/routines.ts
index 5fcd373dae..0d21e4b026 100644
--- a/server/src/services/routines.ts
+++ b/server/src/services/routines.ts
@@ -60,6 +60,7 @@ import { getTelemetryClient } from "../telemetry.js";
import { getConfiguredSecretProvider } from "../secrets/configured-provider.js";
import { issueService } from "./issues.js";
import { assertAssignableAgent } from "./agent-assignability.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
import { secretService } from "./secrets.js";
import { getSecretProvider } from "../secrets/provider-registry.js";
import { parseCron, validateCron } from "./cron.js";
@@ -1060,7 +1061,7 @@ export function routineService(
eq(issues.originKind, "routine_execution"),
inArray(issues.originId, routineIds),
inArray(issues.status, OPEN_ISSUE_STATUSES),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
),
)
.orderBy(issues.originId, desc(issues.updatedAt), desc(issues.createdAt));
@@ -1098,7 +1099,7 @@ export function routineService(
eq(issues.originKind, "routine_execution"),
inArray(issues.originId, missingRoutineIds),
inArray(issues.status, OPEN_ISSUE_STATUSES),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
),
)
.orderBy(issues.originId, desc(issues.updatedAt), desc(issues.createdAt));
@@ -1250,7 +1251,7 @@ export function routineService(
eq(issues.originKind, originKind),
eq(issues.originId, originId),
inArray(issues.status, OPEN_ISSUE_STATUSES),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
...(fingerprintCondition ? [fingerprintCondition] : []),
),
)
@@ -1276,7 +1277,7 @@ export function routineService(
eq(issues.originKind, originKind),
eq(issues.originId, originId),
inArray(issues.status, OPEN_ISSUE_STATUSES),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
...(fingerprintCondition ? [fingerprintCondition] : []),
),
)
diff --git a/server/src/services/task-watchdogs.ts b/server/src/services/task-watchdogs.ts
index 3e2be28e94..daee9a52c7 100644
--- a/server/src/services/task-watchdogs.ts
+++ b/server/src/services/task-watchdogs.ts
@@ -21,6 +21,7 @@ import { parseObject } from "../adapters/utils.js";
import { logActivity } from "./activity-log.js";
import { evaluateAgentInvokabilityFromDb } from "./agent-invokability.js";
import { issueService } from "./issues.js";
+import { visibleIssueCondition } from "./issue-visibility.js";
import { TASK_WATCHDOG_ORIGIN_KIND } from "./task-watchdog-scope.js";
const TASK_WATCHDOG_STOP_FINGERPRINT_PREFIX = "task_watchdog_stop:";
@@ -740,6 +741,7 @@ export function taskWatchdogService(db: Db, deps: TaskWatchdogServiceDeps = {})
WHERE company_id = ${companyId}
AND id = ${watchedIssueId}
AND hidden_at IS NULL
+ AND harness_kind IS NULL
UNION ALL
SELECT
child.id,
@@ -758,6 +760,7 @@ export function taskWatchdogService(db: Db, deps: TaskWatchdogServiceDeps = {})
JOIN watched_issues ON child.parent_id = watched_issues.id
WHERE child.company_id = ${companyId}
AND child.hidden_at IS NULL
+ AND child.harness_kind IS NULL
AND child.origin_kind <> ${TASK_WATCHDOG_ORIGIN_KIND}
AND watched_issues.depth < ${TASK_WATCHDOG_SUBTREE_MAX_DEPTH - 1}
)
@@ -836,7 +839,7 @@ export function taskWatchdogService(db: Db, deps: TaskWatchdogServiceDeps = {})
.where(and(
eq(issues.companyId, companyId),
inArray(issues.id, subtreeIssueIds),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
inArray(heartbeatRuns.status, [...TASK_WATCHDOG_LIVE_RUN_STATUSES]),
)),
db
@@ -1025,7 +1028,7 @@ export function taskWatchdogService(db: Db, deps: TaskWatchdogServiceDeps = {})
eq(issues.companyId, companyId),
eq(issues.originKind, TASK_WATCHDOG_ORIGIN_KIND),
eq(issues.originId, watchedIssueId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
))
.orderBy(asc(issues.createdAt), asc(issues.id))
.limit(1)
@@ -1177,7 +1180,7 @@ export function taskWatchdogService(db: Db, deps: TaskWatchdogServiceDeps = {})
.where(and(
eq(issues.companyId, input.watchdog.companyId),
eq(issues.id, input.watchdog.watchdogIssueId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
))
.then((rows) => rows[0] ?? null)
: null;
@@ -1280,7 +1283,7 @@ export function taskWatchdogService(db: Db, deps: TaskWatchdogServiceDeps = {})
const sourceIssue = await db
.select()
.from(issues)
- .where(and(eq(issues.companyId, watchdog.companyId), eq(issues.id, watchdog.issueId), isNull(issues.hiddenAt)))
+ .where(and(eq(issues.companyId, watchdog.companyId), eq(issues.id, watchdog.issueId), visibleIssueCondition()))
.then((rows) => rows[0] ?? null);
if (!sourceIssue || sourceIssue.originKind === TASK_WATCHDOG_ORIGIN_KIND) {
return { state: "skipped" as const, reason: "watched_issue_not_applicable" };
@@ -1314,7 +1317,7 @@ export function taskWatchdogService(db: Db, deps: TaskWatchdogServiceDeps = {})
.where(and(
eq(issues.companyId, watchdog.companyId),
eq(issues.id, existingWatchdogIssueId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
))
.then((rows) => rows[0] ?? null)
: null;
@@ -1420,12 +1423,14 @@ export function taskWatchdogService(db: Db, deps: TaskWatchdogServiceDeps = {})
WHERE company_id = ${companyId}
AND id = ${issueId}
AND hidden_at IS NULL
+ AND harness_kind IS NULL
UNION ALL
SELECT parent.id, parent.parent_id, ancestors.depth + 1
FROM issues parent
JOIN ancestors ON parent.id = ancestors.parent_id
WHERE parent.company_id = ${companyId}
AND parent.hidden_at IS NULL
+ AND parent.harness_kind IS NULL
AND ancestors.depth < ${TASK_WATCHDOG_SUBTREE_MAX_DEPTH - 1}
)
SELECT id FROM ancestors
diff --git a/server/src/services/work-timeline.ts b/server/src/services/work-timeline.ts
index 46d36976da..96e7e6722b 100644
--- a/server/src/services/work-timeline.ts
+++ b/server/src/services/work-timeline.ts
@@ -11,6 +11,7 @@ import {
issues,
issueThreadInteractions,
} from "@paperclipai/db";
+import { visibleIssueCondition } from "./issue-visibility.js";
// DTO types are shared with the UI via @paperclipai/shared so both sides consume
// one contract. Re-exported here for back-compat with existing server imports.
@@ -205,7 +206,7 @@ export function workTimelineService(db: Db) {
const filterConditions = [
eq(issues.companyId, input.companyId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
input.goalId ? eq(issues.goalId, input.goalId) : undefined,
input.projectId ? eq(issues.projectId, input.projectId) : undefined,
input.issueId ? eq(issues.id, input.issueId) : undefined,
@@ -331,7 +332,7 @@ export function workTimelineService(db: Db) {
.where(
and(
eq(issues.companyId, input.companyId),
- isNull(issues.hiddenAt),
+ visibleIssueCondition(),
inArray(issues.id, issueIds),
input.goalId ? eq(issues.goalId, input.goalId) : undefined,
input.projectId ? eq(issues.projectId, input.projectId) : undefined,
diff --git a/tests/e2e/signoff-policy.spec.ts b/tests/e2e/signoff-policy.spec.ts
index 9e98810ee3..0ffb2d5816 100644
--- a/tests/e2e/signoff-policy.spec.ts
+++ b/tests/e2e/signoff-policy.spec.ts
@@ -75,6 +75,27 @@ async function getIssueRunLockState(board: APIRequestContext, issueId: string):
};
}
+async function retryAgentPatchWithCurrentLockOnConflict(
+ board: APIRequestContext,
+ agent: AgentAuth,
+ issueId: string,
+ failedRes: Awaited<ReturnType<APIRequestContext["patch"]>>,
+ patchData: Record<string, unknown>,
+) {
+ if (failedRes.status() !== 409) return failedRes;
+ const issueRunLock = await getIssueRunLockState(board, issueId);
+ if (issueRunLock.assigneeAgentId !== agent.agentId) return failedRes;
+
+ const lockedRunId = issueRunLock.checkoutRunId ?? issueRunLock.executionRunId;
+ if (!lockedRunId) return failedRes;
+
+ const retryRes = await agent.request.patch(`${BASE_URL}/api/issues/${issueId}`, {
+ headers: { "X-Paperclip-Run-Id": lockedRunId },
+ data: patchData,
+ });
+ return retryRes.ok() ? retryRes : failedRes;
+}
+
/** PATCH an issue as an agent with a fresh heartbeat run ID. */
async function agentPatch(
board: APIRequestContext,
@@ -112,13 +133,8 @@ async function agentCheckoutAndPatch(
});
if (!checkoutRes.ok()) {
if (checkoutRes.status() === 409) {
- const issueRunLock = await getIssueRunLockState(board, issueId);
- const lockedRunId = issueRunLock.checkoutRunId ?? issueRunLock.executionRunId;
- const res = await agent.request.patch(`${BASE_URL}/api/issues/${issueId}`, {
- headers: { "X-Paperclip-Run-Id": lockedRunId ?? runId },
- data: patchData,
- });
- if (res.ok() && issueRunLock.assigneeAgentId === agent.agentId) {
+ const res = await retryAgentPatchWithCurrentLockOnConflict(board, agent, issueId, checkoutRes, patchData);
+ if (res.ok()) {
return res;
}
}
@@ -141,7 +157,7 @@ async function agentCheckoutAndPatch(
headers: { "X-Paperclip-Run-Id": runId },
data: patchData,
});
- return res;
+ return retryAgentPatchWithCurrentLockOnConflict(board, agent, issueId, res, patchData);
}
async function setupCompany(boardRequest: APIRequestContext): Promise<TestContext> {
@@ -380,10 +396,14 @@ test.describe("Signoff execution policy", () => {
const issueId = issue.id;
// Executor marks done → routes to reviewer
- await agentCheckoutAndPatch(
+ const doneRes = await agentCheckoutAndPatch(
ctx.boardRequest, ctx.executor, issueId, ["in_progress"],
{ status: "done", comment: "Done." },
);
+ expect(doneRes.ok()).toBe(true);
+ const doneIssue = await doneRes.json();
+ expect(doneIssue.status).toBe("in_review");
+ expect(doneIssue.assigneeAgentId).toBe(ctx.reviewer.agentId);
// Reviewer tries to approve without comment → should fail
const noCommentRes = await agentPatch(
diff --git a/ui/package.json b/ui/package.json
index cab88c52e9..1e545b206d 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -44,8 +44,8 @@
"@paperclipai/adapter-opencode-local": "workspace:*",
"@paperclipai/adapter-pi-local": "workspace:*",
"@paperclipai/adapter-utils": "workspace:*",
- "@paperclipai/shared": "workspace:*",
"@paperclipai/hermes-paperclip-adapter": "workspace:*",
+ "@paperclipai/shared": "workspace:*",
"@radix-ui/react-slot": "^1.3.0",
"@tailwindcss/typography": "^0.5.20",
"@tanstack/react-query": "^5.101.2",
@@ -63,22 +63,23 @@
"react-dom": "^19.2.7",
"react-i18next": "^17.0.7",
"react-markdown": "^10.1.0",
+ "react-resizable-panels": "^4.12.1",
"react-router-dom": "^7.16.0",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.6.0"
},
"devDependencies": {
- "@tailwindcss/vite": "^4.3.0",
"@storybook/addon-a11y": "10.4.2",
"@storybook/addon-docs": "10.4.6",
"@storybook/react-vite": "10.4.6",
+ "@tailwindcss/vite": "^4.3.0",
"@types/node": "^22.19.21",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^4.3.4",
+ "storybook": "10.4.6",
"tailwindcss": "^4.3.0",
"typescript": "^5.7.3",
- "storybook": "10.4.6",
"vite": "^6.1.0",
"vitest": "^4.1.8"
}
diff --git a/ui/src/App.test.tsx b/ui/src/App.test.tsx
index ed6bba5d9e..9f7b3cd32d 100644
--- a/ui/src/App.test.tsx
+++ b/ui/src/App.test.tsx
@@ -6,6 +6,7 @@ import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CloudAccessGate } from "./components/CloudAccessGate";
+import appSource from "./App.tsx?raw";
const mockHealthApi = vi.hoisted(() => ({
get: vi.fn(),
@@ -227,3 +228,17 @@ describe("CloudAccessGate", () => {
unmountRoot(root);
});
});
+
+describe("Skill Studio routes", () => {
+ it("registers create mode before the skillId route in prefixed and unprefixed routing", () => {
+ const createRoute = 'path="skills/studio/new"';
+ const detailRoute = 'path="skills/studio/:skillId"';
+ const createIndexes = [...appSource.matchAll(new RegExp(createRoute, "g"))].map((match) => match.index ?? -1);
+ const detailIndexes = [...appSource.matchAll(new RegExp(detailRoute, "g"))].map((match) => match.index ?? -1);
+
+ expect(createIndexes).toHaveLength(2);
+ expect(detailIndexes).toHaveLength(2);
+ expect(createIndexes[0]).toBeLessThan(detailIndexes[0]!);
+ expect(createIndexes[1]).toBeLessThan(detailIndexes[1]!);
+ });
+});
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 943b2ecd54..54797e9945 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -45,6 +45,7 @@ import { CompanySettingsPluginPage } from "./pages/CompanySettingsPluginPage";
import { CompanyAccess, CompanyAccessLegacyRoute } from "./pages/CompanyAccess";
import { CompanyInvites } from "./pages/CompanyInvites";
import { CompanySkills } from "./pages/CompanySkills";
+import { SkillStudio } from "./pages/SkillStudio";
import { Secrets } from "./pages/Secrets";
import { CompanyExport } from "./pages/CompanyExport";
import { CompanyImport } from "./pages/CompanyImport";
@@ -105,6 +106,10 @@ function boardRoutes() {
<Route path="company/settings/instance/plugins/:pluginId" element={<PluginSettings />} />
<Route path="company/settings/instance/adapters" element={<AdapterManager />} />
<Route path="company/settings/:settingsRoutePath/*" element={<CompanySettingsPluginPage />} />
+ <Route path="skills/studio" element={<SkillStudio />} />
+ <Route path="skills/studio/new" element={<SkillStudio />} />
+ <Route path="skills/studio/:skillId" element={<SkillStudio />} />
+ <Route path="skills/:skillId/studio" element={<LegacySkillStudioRedirect />} />
<Route path="skills/*" element={<CompanySkills />} />
<Route path="settings" element={<LegacySettingsRedirect />} />
<Route path="settings/*" element={<LegacySettingsRedirect />} />
@@ -220,6 +225,33 @@ function InboxRootRedirect() {
return <Navigate to={`/inbox/${loadLastInboxTab()}`} replace />;
}
+function LegacySkillStudioRedirect() {
+ const location = useLocation();
+ const { companies, selectedCompany, loading } = useCompany();
+ const { companyPrefix, skillId } = useParams<{ companyPrefix?: string; skillId?: string }>();
+
+ if (loading) return null;
+
+ const targetCompany =
+ (companyPrefix
+ ? companies.find((company) => company.issuePrefix.toUpperCase() === companyPrefix.toUpperCase())
+ : null) ??
+ selectedCompany ??
+ companies[0] ??
+ null;
+
+ if (!targetCompany || !skillId) {
+ return <Navigate to="/skills/studio" replace />;
+ }
+
+ return (
+ <Navigate
+ to={`/${targetCompany.issuePrefix}/skills/studio/${encodeURIComponent(skillId)}${location.search}${location.hash}`}
+ replace
+ />
+ );
+}
+
function LegacySettingsRedirect() {
const location = useLocation();
const { companies, selectedCompany, loading } = useCompany();
@@ -421,6 +453,10 @@ export function App() {
<Route path="pipelines/:pipelineId/cases/:caseId" element={<UnprefixedBoardRedirect />} />
<Route path="artifacts" element={<UnprefixedBoardRedirect />} />
<Route path="u/:userSlug" element={<UnprefixedBoardRedirect />} />
+ <Route path="skills/studio" element={<UnprefixedBoardRedirect />} />
+ <Route path="skills/studio/new" element={<UnprefixedBoardRedirect />} />
+ <Route path="skills/studio/:skillId" element={<UnprefixedBoardRedirect />} />
+ <Route path="skills/:skillId/studio" element={<LegacySkillStudioRedirect />} />
<Route path="skills/*" element={<UnprefixedBoardRedirect />} />
<Route path="settings" element={<LegacySettingsRedirect />} />
<Route path="settings/*" element={<LegacySettingsRedirect />} />
diff --git a/ui/src/api/client.ts b/ui/src/api/client.ts
index d3bf0a5eea..69b51b6470 100644
--- a/ui/src/api/client.ts
+++ b/ui/src/api/client.ts
@@ -47,4 +47,6 @@ export const api = {
patch: <T>(path: string, body: unknown) =>
request<T>(path, { method: "PATCH", body: JSON.stringify(body) }),
delete: <T>(path: string) => request<T>(path, { method: "DELETE" }),
+ deleteWithBody: <T>(path: string, body: unknown) =>
+ request<T>(path, { method: "DELETE", body: JSON.stringify(body) }),
};
diff --git a/ui/src/api/companySkills.ts b/ui/src/api/companySkills.ts
index 1e3aeb8f3d..731a8f6da7 100644
--- a/ui/src/api/companySkills.ts
+++ b/ui/src/api/companySkills.ts
@@ -10,7 +10,11 @@ import type {
CompanySkillCreateRequest,
CompanySkillDetail,
CompanySkillFileDetail,
+ CompanySkillFileDeleteRequest,
+ CompanySkillFileDeleteResult,
+ CompanySkillForkPrecheckResult,
CompanySkillForkRequest,
+ CompanySkillForkResult,
CompanySkillImportResult,
CompanySkillInstallCatalogRequest,
CompanySkillInstallCatalogResult,
@@ -19,6 +23,16 @@ import type {
CompanySkillProjectScanRequest,
CompanySkillProjectScanResult,
CompanySkillStarResult,
+ CompanySkillTestInput,
+ CompanySkillTestInputCreateRequest,
+ CompanySkillTestInputUpdateRequest,
+ CompanySkillTestRun,
+ CompanySkillTestRunCreateRequest,
+ CompanySkillTestRunDetail,
+ CompanySkillTestRunListQuery,
+ CompanySkillTestRunTemplate,
+ CompanySkillTestRunTemplateCreateRequest,
+ CompanySkillTestRunTemplateUpdateRequest,
CompanySkillUpdateRequest,
CompanySkillUpdateStatus,
CompanySkillVersion,
@@ -39,6 +53,7 @@ export const companySkillsApi = {
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);
+ for (const include of query.include ?? []) params.append("include[]", include);
const search = params.toString();
return api.get<CompanySkillListItem[]>(`/companies/${encodeURIComponent(companyId)}/skills${search ? `?${search}` : ""}`);
},
@@ -61,6 +76,76 @@ export const companySkillsApi = {
`/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/versions`,
payload,
),
+ // --- Skill Studio test inputs (PAP-12960 P1 API) ---
+ testInputs: (companyId: string, skillId: string) =>
+ api.get<CompanySkillTestInput[]>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/test-inputs`,
+ ),
+ createTestInput: (companyId: string, skillId: string, payload: CompanySkillTestInputCreateRequest) =>
+ api.post<CompanySkillTestInput>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/test-inputs`,
+ payload,
+ ),
+ updateTestInput: (
+ companyId: string,
+ skillId: string,
+ inputId: string,
+ payload: CompanySkillTestInputUpdateRequest,
+ ) =>
+ api.patch<CompanySkillTestInput>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/test-inputs/${encodeURIComponent(inputId)}`,
+ payload,
+ ),
+ deleteTestInput: (companyId: string, skillId: string, inputId: string) =>
+ api.delete<CompanySkillTestInput>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/test-inputs/${encodeURIComponent(inputId)}`,
+ ),
+ // --- Skill Studio cross-skill run templates ---
+ testRunTemplates: (companyId: string) =>
+ api.get<CompanySkillTestRunTemplate[]>(
+ `/companies/${encodeURIComponent(companyId)}/skill-test-run-templates`,
+ ),
+ createTestRunTemplate: (companyId: string, payload: CompanySkillTestRunTemplateCreateRequest) =>
+ api.post<CompanySkillTestRunTemplate>(
+ `/companies/${encodeURIComponent(companyId)}/skill-test-run-templates`,
+ payload,
+ ),
+ updateTestRunTemplate: (companyId: string, templateId: string, payload: CompanySkillTestRunTemplateUpdateRequest) =>
+ api.patch<CompanySkillTestRunTemplate>(
+ `/companies/${encodeURIComponent(companyId)}/skill-test-run-templates/${encodeURIComponent(templateId)}`,
+ payload,
+ ),
+ deleteTestRunTemplate: (companyId: string, templateId: string) =>
+ api.delete<CompanySkillTestRunTemplate>(
+ `/companies/${encodeURIComponent(companyId)}/skill-test-run-templates/${encodeURIComponent(templateId)}`,
+ ),
+ // --- Skill Studio test runs ---
+ testRuns: (companyId: string, skillId: string, query: CompanySkillTestRunListQuery = {}) => {
+ const params = new URLSearchParams();
+ if (query.inputId) params.set("inputId", query.inputId);
+ const search = params.toString();
+ return api.get<CompanySkillTestRun[]>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/test-runs${search ? `?${search}` : ""}`,
+ );
+ },
+ testRunDetail: (companyId: string, skillId: string, runId: string) =>
+ api.get<CompanySkillTestRunDetail>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/test-runs/${encodeURIComponent(runId)}`,
+ ),
+ createTestRun: (companyId: string, skillId: string, payload: CompanySkillTestRunCreateRequest) =>
+ api.post<CompanySkillTestRun>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/test-runs`,
+ payload,
+ ),
+ cancelTestRun: (companyId: string, skillId: string, runId: string) =>
+ api.post<CompanySkillTestRun>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/test-runs/${encodeURIComponent(runId)}/cancel`,
+ {},
+ ),
+ deleteTestRun: (companyId: string, skillId: string, runId: string) =>
+ api.delete<CompanySkillTestRun>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/test-runs/${encodeURIComponent(runId)}`,
+ ),
star: (companyId: string, skillId: string) =>
api.post<CompanySkillStarResult>(
`/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/star`,
@@ -71,10 +156,14 @@ export const companySkillsApi = {
`/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/star`,
),
fork: (companyId: string, skillId: string, payload: CompanySkillForkRequest = {}) =>
- api.post<CompanySkill>(
+ api.post<CompanySkillForkResult>(
`/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/fork`,
payload,
),
+ forkPrecheck: (companyId: string, skillId: string) =>
+ api.get<CompanySkillForkPrecheckResult>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/fork-precheck`,
+ ),
comments: (companyId: string, skillId: string) =>
api.get<CompanySkillComment[]>(
`/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/comments`,
@@ -106,6 +195,11 @@ export const companySkillsApi = {
`/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/files`,
{ path, content },
),
+ deleteFile: (companyId: string, skillId: string, payload: CompanySkillFileDeleteRequest) =>
+ api.deleteWithBody<CompanySkillFileDeleteResult>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/files`,
+ payload,
+ ),
create: (companyId: string, payload: CompanySkillCreateRequest) =>
api.post<CompanySkill>(
`/companies/${encodeURIComponent(companyId)}/skills`,
diff --git a/ui/src/components/ActivityCharts.tsx b/ui/src/components/ActivityCharts.tsx
index 429d412f8b..cc72236270 100644
--- a/ui/src/components/ActivityCharts.tsx
+++ b/ui/src/components/ActivityCharts.tsx
@@ -21,7 +21,7 @@ function emptyRunDay(date: string): DashboardRunActivityDay {
const runSegmentColors = {
succeeded: "var(--hex-10b981)",
- recovered: "var(--hex-f59e0b)",
+ recovered: "var(--status-task-todo)",
failed: "var(--hex-ef4444)",
other: "var(--hex-737373)",
} as const;
diff --git a/ui/src/components/FrontmatterPanel.test.tsx b/ui/src/components/FrontmatterPanel.test.tsx
new file mode 100644
index 0000000000..78139113b9
--- /dev/null
+++ b/ui/src/components/FrontmatterPanel.test.tsx
@@ -0,0 +1,228 @@
+// @vitest-environment jsdom
+
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { joinFrontmatterBlock, splitFrontmatterBlock } from "@paperclipai/shared";
+import {
+ FrontmatterPanel,
+ type FrontmatterPanelChange,
+ type FrontmatterPanelProps,
+} from "./FrontmatterPanel";
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+function flushUi(callback: () => void) {
+ flushSync(callback);
+}
+
+function setValue(el: HTMLInputElement | HTMLTextAreaElement, value: string) {
+ const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
+ const setter = Object.getOwnPropertyDescriptor(proto, "value")!.set!;
+ flushUi(() => {
+ setter.call(el, value);
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+function click(el: Element | null | undefined) {
+ flushUi(() => {
+ el?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+}
+
+function findButtonByText(container: HTMLElement, text: string): HTMLButtonElement | null {
+ return (
+ Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find(
+ (button) => button.textContent?.trim() === text,
+ ) ?? null
+ );
+}
+
+function expandPanel(container: HTMLElement) {
+ const toggle = container.querySelector<HTMLButtonElement>('button[aria-controls="frontmatter-panel-body"]');
+ click(toggle);
+}
+
+describe("FrontmatterPanel", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ flushUi(() => root.unmount());
+ container.remove();
+ });
+
+ function render(props: Partial<FrontmatterPanelProps> & { onChange?: (c: FrontmatterPanelChange) => void }) {
+ const onChange = props.onChange ?? vi.fn();
+ flushUi(() => {
+ root.render(
+ <FrontmatterPanel
+ frontmatterText={props.frontmatterText ?? ""}
+ hasFrontmatter={props.hasFrontmatter ?? false}
+ fileName={props.fileName ?? "SKILL.md"}
+ skillSlug={props.skillSlug}
+ readOnly={props.readOnly}
+ onChange={onChange}
+ />,
+ );
+ });
+ return onChange;
+ }
+
+ it("does not emit on mount — byte-identity round-trip is preserved when untouched", () => {
+ const onChange = vi.fn();
+ render({
+ frontmatterText: "name: reflection-coach\ndescription: A helpful coach",
+ hasFrontmatter: true,
+ onChange,
+ });
+ expect(onChange).not.toHaveBeenCalled();
+ const toggle = container.querySelector<HTMLButtonElement>('button[aria-controls="frontmatter-panel-body"]');
+ expect(toggle?.getAttribute("aria-expanded")).toBe("false");
+ expect(container.querySelector("#fm-name")).toBeNull();
+ expandPanel(container);
+ // The Fields tab is available for this round-trippable block after expansion.
+ expect(container.querySelector<HTMLInputElement>("#fm-name")?.value).toBe("reflection-coach");
+ });
+
+ it("edits `name` in Fields mode and emits only that field changed", () => {
+ const onChange = vi.fn();
+ render({
+ frontmatterText: "name: coach\ndescription: A coach",
+ hasFrontmatter: true,
+ onChange,
+ });
+ expandPanel(container);
+ const nameInput = container.querySelector<HTMLInputElement>("#fm-name")!;
+ setValue(nameInput, "new-coach");
+ const last = onChange.mock.calls.at(-1)![0] as FrontmatterPanelChange;
+ expect(last.frontmatterText).toBe("name: new-coach\ndescription: A coach");
+ expect(last.hasFrontmatter).toBe(true);
+ });
+
+ it("edits allowed-tools via the chip input", () => {
+ const onChange = vi.fn();
+ render({
+ frontmatterText: "name: coach\nallowed-tools:\n - Read",
+ hasFrontmatter: true,
+ onChange,
+ });
+ expandPanel(container);
+ const chipInput = container.querySelector<HTMLInputElement>('input[aria-label="Add tool"]')!;
+ setValue(chipInput, "Grep");
+ flushUi(() => {
+ chipInput.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true }),
+ );
+ });
+ const last = onChange.mock.calls.at(-1)![0] as FrontmatterPanelChange;
+ expect(last.frontmatterText).toBe("name: coach\nallowed-tools:\n - Read\n - Grep");
+ });
+
+ it("edits nested metadata scalar values", () => {
+ const onChange = vi.fn();
+ render({
+ frontmatterText: "name: coach\nmetadata:\n author: Paperclip\n version: 2",
+ hasFrontmatter: true,
+ onChange,
+ });
+ expandPanel(container);
+ const valueInput = container.querySelector<HTMLInputElement>('input[aria-label="Value for author"]')!;
+ setValue(valueInput, "Anthropic");
+ const last = onChange.mock.calls.at(-1)![0] as FrontmatterPanelChange;
+ // author changes; version stays a NUMBER (not requoted) because it was untouched.
+ expect(last.frontmatterText).toBe("name: coach\nmetadata:\n author: Anthropic\n version: 2");
+ });
+
+ it("locks Fields mode for non-round-trippable YAML (inline comment) and preserves raw bytes", () => {
+ const onChange = vi.fn();
+ const raw = "name: coach # keep me\ndescription: A coach";
+ render({ frontmatterText: raw, hasFrontmatter: true, onChange });
+ expandPanel(container);
+
+ // Fields tab is disabled; the YAML textarea is shown instead.
+ const fieldsTab = findButtonByText(container, "Fields");
+ expect(fieldsTab?.getAttribute("aria-disabled")).toBe("true");
+ const yaml = container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Frontmatter YAML"]');
+ expect(yaml?.value).toBe(raw);
+ expect(container.querySelector("#fm-name")).toBeNull();
+
+ // Editing raw YAML passes through byte-for-byte.
+ setValue(yaml!, `${raw}\nextra: value`);
+ const last = onChange.mock.calls.at(-1)![0] as FrontmatterPanelChange;
+ expect(last.frontmatterText).toBe(`${raw}\nextra: value`);
+ });
+
+ it("shows a warning chip for missing name/description on SKILL.md", () => {
+ render({
+ frontmatterText: "name: coach",
+ hasFrontmatter: true,
+ fileName: "SKILL.md",
+ });
+ const chip = container.querySelector('[data-testid="frontmatter-warning-chip"]');
+ expect(chip?.textContent).toContain("issue");
+ });
+
+ it("flags a wrong-typed allowed-tools value instead of editing it as a list", () => {
+ render({
+ frontmatterText: "name: coach\ndescription: x\nallowed-tools: Read",
+ hasFrontmatter: true,
+ });
+ expandPanel(container);
+ expect(container.textContent).toContain("Expected a list");
+ });
+
+ it("adds frontmatter to a file that has none, seeding name from the slug", () => {
+ const onChange = vi.fn();
+ render({
+ frontmatterText: "",
+ hasFrontmatter: false,
+ fileName: "SKILL.md",
+ skillSlug: "reflection-coach",
+ onChange,
+ });
+ const addButton = container.querySelector<HTMLButtonElement>('[data-testid="add-frontmatter"]');
+ expect(addButton).toBeTruthy();
+ click(addButton);
+ const last = onChange.mock.calls.at(-1)![0] as FrontmatterPanelChange;
+ expect(last.hasFrontmatter).toBe(true);
+ expect(last.frontmatterText).toContain("name: reflection-coach");
+ expect(last.frontmatterText).toContain("description:");
+ });
+
+ it("renders read-only fields without editing affordances", () => {
+ render({
+ frontmatterText: "name: coach\nallowed-tools:\n - Read",
+ hasFrontmatter: true,
+ readOnly: true,
+ });
+ expandPanel(container);
+ const nameInput = container.querySelector<HTMLInputElement>("#fm-name");
+ expect(nameInput?.readOnly).toBe(true);
+ // No chip remove buttons, no add-tool input.
+ expect(container.querySelector('input[aria-label="Add tool"]')).toBeNull();
+ expect(container.querySelector('button[aria-label="Remove Read"]')).toBeNull();
+ });
+
+ it("keeps the full document byte-identical through split → panel → join with no edits", () => {
+ const file = "---\nname: coach\ndescription: A coach\n---\n# Body\n\nHello world\n";
+ const block = splitFrontmatterBlock(file);
+ const onChange = vi.fn();
+ render({
+ frontmatterText: block.frontmatterText,
+ hasFrontmatter: block.hasFrontmatter,
+ onChange,
+ });
+ expect(onChange).not.toHaveBeenCalled();
+ // The parent would rejoin the untouched block with the untouched body.
+ expect(joinFrontmatterBlock(block)).toBe(file);
+ });
+});
diff --git a/ui/src/components/FrontmatterPanel.tsx b/ui/src/components/FrontmatterPanel.tsx
new file mode 100644
index 0000000000..c8b27a5b30
--- /dev/null
+++ b/ui/src/components/FrontmatterPanel.tsx
@@ -0,0 +1,732 @@
+import { useCallback, useMemo, useState } from "react";
+import {
+ analyzeFrontmatterBlock,
+ asStringArray,
+ getSkillFrontmatterUnknownKeys,
+ isFrontmatterPlainRecord,
+ parseFrontmatterFields,
+ stringifyFrontmatter,
+} from "@paperclipai/shared";
+import { AlertTriangle, ChevronDown, ChevronRight, Info, Plus, Trash2, X } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Textarea } from "@/components/ui/textarea";
+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Collapsible, CollapsibleContent } from "@/components/ui/collapsible";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+
+/**
+ * Skill Studio frontmatter editor (PAP-13145 Option B / PAP-13155).
+ *
+ * The rich markdown editor must never see the leading `---` YAML block or it
+ * corrupts it into headings/thematic breaks on every round-trip. Studio splits
+ * the file into a frontmatter block (owned by this panel) and a body (owned by
+ * MarkdownEditor); this panel offers a schema-aware Fields form when the YAML
+ * can be safely re-serialized, and always falls back to raw YAML when it can't.
+ *
+ * Byte-identity guarantee (QA PAP-13156): this panel only calls `onChange` in
+ * response to a real user edit. Opening a file and saving it untouched never
+ * routes through the serializer, so bytes are preserved exactly. Callers must
+ * mount this panel with a per-file `key` so its local state resets on file
+ * switches.
+ */
+
+type FrontmatterMode = "fields" | "yaml";
+
+export interface FrontmatterPanelChange {
+ frontmatterText: string;
+ hasFrontmatter: boolean;
+}
+
+export interface FrontmatterPanelProps {
+ /** Raw YAML block between the `---` fences (from `splitFrontmatterBlock`). */
+ frontmatterText: string;
+ hasFrontmatter: boolean;
+ /** File path, e.g. `SKILL.md`. Drives required-field rules + expand default. */
+ fileName: string;
+ /** Skill slug used to seed `name:` when adding frontmatter to a SKILL.md. */
+ skillSlug?: string;
+ readOnly?: boolean;
+ onChange: (change: FrontmatterPanelChange) => void;
+ className?: string;
+}
+
+type ScalarValue = string | number | boolean | null;
+
+interface ScalarRow {
+ id: string;
+ key: string;
+ /** Original parsed value, preserved verbatim until the row is edited. */
+ rawValue: unknown;
+ text: string;
+ edited: boolean;
+}
+
+interface UnknownRow extends ScalarRow {
+ editable: boolean;
+}
+
+interface FormModel {
+ hasName: boolean;
+ name: string;
+ hasDescription: boolean;
+ description: string;
+ allowedToolsPresent: boolean;
+ /** null → present but not a string list (type mismatch, edit in YAML). */
+ allowedTools: string[] | null;
+ metadataPresent: boolean;
+ /** null → metadata is a plain scalar record we can edit as rows. */
+ metadataComplex: unknown;
+ metaRows: ScalarRow[];
+ unknown: UnknownRow[];
+}
+
+function isScalar(value: unknown): value is ScalarValue {
+ return (
+ value === null
+ || typeof value === "string"
+ || typeof value === "number"
+ || typeof value === "boolean"
+ );
+}
+
+function scalarToText(value: unknown): string {
+ if (value === null || value === undefined) return "";
+ if (typeof value === "boolean") return value ? "true" : "false";
+ return String(value);
+}
+
+/** Coerce edited text back to a YAML scalar so `version: 2` stays a number. */
+function coerceScalar(text: string): ScalarValue {
+ if (text === "") return "";
+ if (text === "true") return true;
+ if (text === "false") return false;
+ if (text === "null" || text === "~") return null;
+ if (/^-?\d+(\.\d+)?$/u.test(text)) return Number(text);
+ return text;
+}
+
+function isFlatScalarRecord(value: unknown): value is Record<string, ScalarValue> {
+ return isFrontmatterPlainRecord(value) && Object.values(value).every(isScalar);
+}
+
+function buildFormModel(obj: Record<string, unknown>): FormModel {
+ const allowedToolsPresent = "allowed-tools" in obj;
+ const metadataValue = obj.metadata;
+ const metadataPresent = "metadata" in obj;
+ const metadataEditable = metadataPresent && isFlatScalarRecord(metadataValue);
+
+ const metaRows: ScalarRow[] = metadataEditable
+ ? Object.entries(metadataValue as Record<string, ScalarValue>).map(([key, value], index) => ({
+ id: `meta-${index}-${key}`,
+ key,
+ rawValue: value,
+ text: scalarToText(value),
+ edited: false,
+ }))
+ : [];
+
+ const unknown: UnknownRow[] = getSkillFrontmatterUnknownKeys(obj).map((key, index) => {
+ const value = obj[key];
+ const editable = isScalar(value);
+ return {
+ id: `unknown-${index}-${key}`,
+ key,
+ rawValue: value,
+ text: scalarToText(value),
+ edited: false,
+ editable,
+ };
+ });
+
+ return {
+ hasName: "name" in obj,
+ name: typeof obj.name === "string" ? obj.name : scalarToText(obj.name),
+ hasDescription: "description" in obj,
+ description: typeof obj.description === "string" ? obj.description : scalarToText(obj.description),
+ allowedToolsPresent,
+ allowedTools: allowedToolsPresent ? asStringArray(obj["allowed-tools"]) : [],
+ metadataPresent,
+ metadataComplex: metadataPresent && !metadataEditable ? metadataValue : null,
+ metaRows,
+ unknown,
+ };
+}
+
+function scalarRowsToObject(rows: ScalarRow[]): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ for (const row of rows) {
+ const key = row.key.trim();
+ if (!key) continue;
+ out[key] = row.edited ? coerceScalar(row.text) : row.rawValue;
+ }
+ return out;
+}
+
+/**
+ * Rebuild the frontmatter object from the form. Known keys are emitted in schema
+ * order (name, description, allowed-tools, metadata) followed by unknown keys —
+ * matches the panel's display order. Only reached in Fields mode, which is only
+ * available for round-trippable blocks, so this never runs on messy YAML.
+ */
+function serializeForm(form: FormModel): string {
+ const out: Record<string, unknown> = {};
+ if (form.hasName) out.name = form.name;
+ if (form.hasDescription) out.description = form.description;
+ if (form.allowedToolsPresent) out["allowed-tools"] = form.allowedTools ?? [];
+ if (form.metadataPresent) {
+ out.metadata = form.metadataComplex !== null ? form.metadataComplex : scalarRowsToObject(form.metaRows);
+ }
+ for (const row of form.unknown) {
+ const key = row.key.trim();
+ if (!key) continue;
+ out[key] = row.editable && row.edited ? coerceScalar(row.text) : row.rawValue;
+ }
+ return stringifyFrontmatter(out);
+}
+
+const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
+
+interface ValidationIssue {
+ field: string;
+ message: string;
+}
+
+function collectValidation(form: FormModel, isSkillFile: boolean): ValidationIssue[] {
+ const issues: ValidationIssue[] = [];
+ const name = form.name.trim();
+ const description = form.description.trim();
+ if (isSkillFile && !name) issues.push({ field: "name", message: "SKILL.md needs a name." });
+ if (name && !SLUG_RE.test(name)) {
+ issues.push({ field: "name", message: "Use lowercase letters, numbers and hyphens." });
+ }
+ if (isSkillFile && !description) {
+ issues.push({ field: "description", message: "SKILL.md needs a description." });
+ }
+ if (form.allowedToolsPresent && form.allowedTools === null) {
+ issues.push({ field: "allowed-tools", message: "Expected a list — edit in YAML." });
+ }
+ return issues;
+}
+
+function isSkillMarkdown(fileName: string): boolean {
+ return /(^|\/)skill\.md$/i.test(fileName);
+}
+
+export function FrontmatterPanel({
+ frontmatterText,
+ hasFrontmatter,
+ fileName,
+ skillSlug,
+ readOnly = false,
+ onChange,
+ className,
+}: FrontmatterPanelProps) {
+ const isSkillFile = isSkillMarkdown(fileName);
+
+ // `yamlText` is the canonical raw block — always equal to whatever we've last
+ // emitted (or the original text before any edit). `form` is authoritative only
+ // while in Fields mode. Both initialize from props; the caller keys us per file.
+ const [present, setPresent] = useState(hasFrontmatter);
+ const [yamlText, setYamlText] = useState(frontmatterText);
+ const initialAnalysis = useMemo(() => analyzeFrontmatterBlock(frontmatterText), [frontmatterText]);
+ const [form, setForm] = useState<FormModel>(() => buildFormModel(initialAnalysis.parsed));
+ const [mode, setMode] = useState<FrontmatterMode>(
+ hasFrontmatter && initialAnalysis.canRoundTrip ? "fields" : "yaml",
+ );
+ const [open, setOpen] = useState(false);
+
+ const analysis = useMemo(() => analyzeFrontmatterBlock(yamlText), [yamlText]);
+ const canUseFields = present && analysis.canRoundTrip;
+ const effectiveMode: FrontmatterMode = mode === "fields" && !canUseFields ? "yaml" : mode;
+
+ const validation = useMemo(
+ () => (effectiveMode === "fields" ? collectValidation(form, isSkillFile) : []),
+ [effectiveMode, form, isSkillFile],
+ );
+
+ const emit = useCallback(
+ (nextRaw: string, nextPresent: boolean) => {
+ onChange({ frontmatterText: nextRaw, hasFrontmatter: nextPresent });
+ },
+ [onChange],
+ );
+
+ const commitForm = useCallback(
+ (nextForm: FormModel) => {
+ setForm(nextForm);
+ let nextRaw: string;
+ try {
+ nextRaw = serializeForm(nextForm);
+ } catch {
+ // Unsupported key/value (e.g. a metadata key with a colon) — drop this
+ // edit rather than emit corrupt YAML.
+ return;
+ }
+ setYamlText(nextRaw);
+ emit(nextRaw, true);
+ },
+ [emit],
+ );
+
+ const handleYamlChange = useCallback(
+ (next: string) => {
+ setYamlText(next);
+ emit(next, true);
+ },
+ [emit],
+ );
+
+ const switchMode = useCallback(
+ (next: FrontmatterMode) => {
+ if (next === "fields") {
+ if (!canUseFields) return;
+ setForm(buildFormModel(parseFrontmatterFields(yamlText)));
+ }
+ setMode(next);
+ },
+ [canUseFields, yamlText],
+ );
+
+ const addFrontmatter = useCallback(() => {
+ const seed: FormModel = {
+ hasName: true,
+ name: isSkillFile ? (skillSlug ?? "").trim() : "",
+ hasDescription: isSkillFile,
+ description: "",
+ allowedToolsPresent: false,
+ allowedTools: [],
+ metadataPresent: false,
+ metadataComplex: null,
+ metaRows: [],
+ unknown: [],
+ };
+ setPresent(true);
+ setMode("fields");
+ setOpen(true);
+ setForm(seed);
+ const nextRaw = serializeForm(seed);
+ setYamlText(nextRaw);
+ emit(nextRaw, true);
+ }, [emit, isSkillFile, skillSlug]);
+
+ const summary = useMemo(() => buildSummary(analysis.parsed), [analysis.parsed]);
+ const warningCount = validation.length;
+
+ const chevron = open ? (
+ <ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ ) : (
+ <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ );
+
+ return (
+ <TooltipProvider>
+ <Collapsible
+ open={open}
+ onOpenChange={setOpen}
+ className={cn("border-b border-border", className)}
+ data-testid="frontmatter-panel"
+ >
+ <div className="flex items-center gap-2 px-3 py-1.5">
+ <button
+ type="button"
+ onClick={() => setOpen((value) => !value)}
+ className="flex min-w-0 flex-1 items-center gap-1.5 text-left"
+ aria-expanded={open}
+ aria-controls="frontmatter-panel-body"
+ >
+ {chevron}
+ <span className="text-sm font-medium">Frontmatter</span>
+ {!open && present ? (
+ <span className="truncate text-xs text-muted-foreground">{summary}</span>
+ ) : null}
+ {!open && !present ? (
+ <span className="text-xs text-muted-foreground">None</span>
+ ) : null}
+ </button>
+
+ {present ? (
+ <Tabs
+ value={effectiveMode}
+ onValueChange={(value) => switchMode(value as FrontmatterMode)}
+ >
+ <TabsList variant="line" className="h-7">
+ {canUseFields ? (
+ <TabsTrigger value="fields" className="px-2 py-0.5 text-xs">
+ Fields
+ </TabsTrigger>
+ ) : (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <TabsTrigger
+ value="fields"
+ disabled
+ aria-disabled="true"
+ className="px-2 py-0.5 text-xs opacity-50"
+ >
+ Fields
+ </TabsTrigger>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-60">
+ Switch to YAML to edit. This frontmatter uses YAML features the form can't safely
+ round-trip (e.g. comments, anchors, or custom ordering). Editing here keeps it
+ byte-for-byte.
+ </TooltipContent>
+ </Tooltip>
+ )}
+ <TabsTrigger value="yaml" className="px-2 py-0.5 text-xs">
+ YAML
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ ) : !readOnly ? (
+ <Button variant="ghost" size="sm" onClick={addFrontmatter} data-testid="add-frontmatter">
+ <Plus className="mr-1 h-3.5 w-3.5" />
+ Add frontmatter
+ </Button>
+ ) : null}
+
+ {present && effectiveMode === "fields" && warningCount > 0 ? (
+ <Badge variant="outline" className="gap-1 text-amber-500" data-testid="frontmatter-warning-chip">
+ <AlertTriangle className="h-3.5 w-3.5" />
+ {warningCount} {warningCount === 1 ? "issue" : "issues"}
+ </Badge>
+ ) : null}
+ </div>
+
+ <CollapsibleContent id="frontmatter-panel-body">
+ {present ? (
+ <div className="px-3 pb-3">
+ {effectiveMode === "fields" ? (
+ <FieldsForm
+ form={form}
+ validation={validation}
+ readOnly={readOnly}
+ onCommit={commitForm}
+ />
+ ) : (
+ <YamlEditor
+ value={yamlText}
+ readOnly={readOnly}
+ canReturnToFields={canUseFields}
+ parseError={present && !analysis.canRoundTrip && analysis.issues.length === 0}
+ onChange={handleYamlChange}
+ />
+ )}
+ </div>
+ ) : (
+ <div className="px-3 pb-2 text-xs text-muted-foreground">
+ This file has no frontmatter.
+ </div>
+ )}
+ </CollapsibleContent>
+ </Collapsible>
+ </TooltipProvider>
+ );
+}
+
+function buildSummary(parsed: Record<string, unknown>): string {
+ const parts: string[] = [];
+ if (typeof parsed.name === "string" && parsed.name.trim()) parts.push(parsed.name.trim());
+ const tools = asStringArray(parsed["allowed-tools"]);
+ if (tools && tools.length > 0) parts.push(`${tools.length} ${tools.length === 1 ? "tool" : "tools"}`);
+ if (isFrontmatterPlainRecord(parsed.metadata)) {
+ const count = Object.keys(parsed.metadata).length;
+ if (count > 0) parts.push(`${count} metadata`);
+ }
+ return parts.join(" · ");
+}
+
+function fieldWarning(validation: ValidationIssue[], field: string): string | null {
+ return validation.find((issue) => issue.field === field)?.message ?? null;
+}
+
+function FieldWarning({ message }: { message: string }) {
+ return (
+ <p className="mt-1 flex items-center gap-1 text-xs text-amber-500">
+ <AlertTriangle className="h-3.5 w-3.5 shrink-0" />
+ {message}
+ </p>
+ );
+}
+
+function FieldsForm({
+ form,
+ validation,
+ readOnly,
+ onCommit,
+}: {
+ form: FormModel;
+ validation: ValidationIssue[];
+ readOnly: boolean;
+ onCommit: (form: FormModel) => void;
+}) {
+ const nameWarning = fieldWarning(validation, "name");
+ const descriptionWarning = fieldWarning(validation, "description");
+ const toolsWarning = fieldWarning(validation, "allowed-tools");
+
+ return (
+ <div className="space-y-3 pt-1">
+ {form.hasName ? (
+ <div>
+ <Label htmlFor="fm-name" className="text-xs text-muted-foreground">
+ name
+ </Label>
+ <Input
+ id="fm-name"
+ value={form.name}
+ readOnly={readOnly}
+ aria-invalid={Boolean(nameWarning)}
+ onChange={(event) => onCommit({ ...form, name: event.target.value })}
+ className="mt-1"
+ />
+ {nameWarning ? <FieldWarning message={nameWarning} /> : null}
+ </div>
+ ) : null}
+
+ {form.hasDescription ? (
+ <div>
+ <Label htmlFor="fm-description" className="text-xs text-muted-foreground">
+ description
+ </Label>
+ <Textarea
+ id="fm-description"
+ value={form.description}
+ readOnly={readOnly}
+ rows={3}
+ onChange={(event) => onCommit({ ...form, description: event.target.value })}
+ className="mt-1"
+ />
+ {descriptionWarning ? <FieldWarning message={descriptionWarning} /> : null}
+ </div>
+ ) : null}
+
+ {form.allowedToolsPresent ? (
+ <div>
+ <Label className="text-xs text-muted-foreground">allowed-tools</Label>
+ {form.allowedTools === null ? (
+ <p className="mt-1 text-xs text-amber-500">
+ {toolsWarning ?? "Expected a list — edit in YAML."}
+ </p>
+ ) : (
+ <ChipInput
+ values={form.allowedTools}
+ readOnly={readOnly}
+ placeholder="Add a tool…"
+ onChange={(next) => onCommit({ ...form, allowedTools: next })}
+ />
+ )}
+ </div>
+ ) : null}
+
+ {form.metadataPresent ? (
+ <div>
+ <Label className="text-xs text-muted-foreground">metadata</Label>
+ {form.metadataComplex !== null ? (
+ <p className="mt-1 text-xs text-muted-foreground">Complex value — edit in YAML.</p>
+ ) : (
+ <MetadataRows
+ rows={form.metaRows}
+ readOnly={readOnly}
+ onChange={(rows) => onCommit({ ...form, metaRows: rows })}
+ />
+ )}
+ </div>
+ ) : null}
+
+ {form.unknown.map((row, index) =>
+ row.editable ? (
+ <div key={row.id}>
+ <Label htmlFor={`fm-unknown-${row.id}`} className="text-xs text-muted-foreground">
+ {row.key}
+ </Label>
+ <Input
+ id={`fm-unknown-${row.id}`}
+ value={row.text}
+ readOnly={readOnly}
+ onChange={(event) => {
+ const unknown = form.unknown.slice();
+ unknown[index] = { ...row, text: event.target.value, edited: true };
+ onCommit({ ...form, unknown });
+ }}
+ className="mt-1"
+ />
+ </div>
+ ) : (
+ <div key={row.id}>
+ <Label className="text-xs text-muted-foreground">{row.key}</Label>
+ <p className="mt-1 text-xs text-muted-foreground">Complex value — edit in YAML.</p>
+ </div>
+ ),
+ )}
+ </div>
+ );
+}
+
+function MetadataRows({
+ rows,
+ readOnly,
+ onChange,
+}: {
+ rows: ScalarRow[];
+ readOnly: boolean;
+ onChange: (rows: ScalarRow[]) => void;
+}) {
+ const update = (index: number, patch: Partial<ScalarRow>) => {
+ const next = rows.slice();
+ next[index] = { ...next[index]!, ...patch, edited: true };
+ onChange(next);
+ };
+ const remove = (index: number) => {
+ onChange(rows.filter((_, i) => i !== index));
+ };
+ const add = () => {
+ onChange([
+ ...rows,
+ { id: `meta-new-${rows.length}-${Date.now()}`, key: "", rawValue: "", text: "", edited: true },
+ ]);
+ };
+
+ return (
+ <div className="mt-1 space-y-1.5">
+ {rows.map((row, index) => (
+ <div key={row.id} className="flex items-center gap-1.5">
+ <Input
+ aria-label={`Metadata key ${index + 1}`}
+ value={row.key}
+ readOnly={readOnly}
+ placeholder="key"
+ onChange={(event) => update(index, { key: event.target.value })}
+ className="h-8 flex-1 font-mono text-xs"
+ />
+ <Input
+ aria-label={`Value for ${row.key || `field ${index + 1}`}`}
+ value={row.text}
+ readOnly={readOnly}
+ placeholder="value"
+ onChange={(event) => update(index, { text: event.target.value })}
+ className="h-8 flex-1 text-xs"
+ />
+ {!readOnly ? (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8 shrink-0"
+ aria-label={`Remove ${row.key || `field ${index + 1}`}`}
+ onClick={() => remove(index)}
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ ) : null}
+ </div>
+ ))}
+ {!readOnly ? (
+ <Button variant="ghost" size="sm" onClick={add} className="text-xs">
+ <Plus className="mr-1 h-3.5 w-3.5" />
+ add field
+ </Button>
+ ) : null}
+ </div>
+ );
+}
+
+function ChipInput({
+ values,
+ readOnly,
+ placeholder,
+ onChange,
+}: {
+ values: string[];
+ readOnly: boolean;
+ placeholder?: string;
+ onChange: (values: string[]) => void;
+}) {
+ const [draft, setDraft] = useState("");
+
+ const commit = () => {
+ const value = draft.trim();
+ if (!value) return;
+ onChange([...values, value]);
+ setDraft("");
+ };
+
+ return (
+ <div className="mt-1 flex flex-wrap items-center gap-1.5 rounded-md border border-border px-2 py-1.5">
+ {values.map((value, index) => (
+ <Badge key={`${value}-${index}`} variant="secondary" className="gap-1">
+ {value}
+ {!readOnly ? (
+ <button
+ type="button"
+ aria-label={`Remove ${value}`}
+ onClick={() => onChange(values.filter((_, i) => i !== index))}
+ className="hover:text-foreground"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ ) : null}
+ </Badge>
+ ))}
+ {!readOnly ? (
+ <input
+ value={draft}
+ placeholder={values.length === 0 ? placeholder : undefined}
+ onChange={(event) => setDraft(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === ",") {
+ event.preventDefault();
+ commit();
+ } else if (event.key === "Backspace" && draft === "" && values.length > 0) {
+ onChange(values.slice(0, -1));
+ }
+ }}
+ onBlur={commit}
+ aria-label="Add tool"
+ className="min-w-24 flex-1 bg-transparent text-xs outline-none"
+ />
+ ) : null}
+ </div>
+ );
+}
+
+function YamlEditor({
+ value,
+ readOnly,
+ canReturnToFields,
+ parseError,
+ onChange,
+}: {
+ value: string;
+ readOnly: boolean;
+ canReturnToFields: boolean;
+ parseError: boolean;
+ onChange: (value: string) => void;
+}) {
+ return (
+ <div className="pt-1">
+ {!canReturnToFields && !parseError ? (
+ <div className="mb-1.5 flex items-start gap-2 rounded-md bg-muted/40 px-2 py-1.5 text-xs text-muted-foreground">
+ <Info className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden="true" />
+ <span>Editing raw YAML to preserve formatting the form can't reconstruct.</span>
+ </div>
+ ) : null}
+ <Textarea
+ value={value}
+ readOnly={readOnly}
+ spellCheck={false}
+ rows={Math.min(12, Math.max(3, value.split("\n").length))}
+ onChange={(event) => onChange(event.target.value)}
+ className="font-mono text-xs"
+ aria-label="Frontmatter YAML"
+ />
+ <p className="mt-1 text-xs text-muted-foreground">
+ Raw YAML is the source of truth in this mode.
+ </p>
+ </div>
+ );
+}
diff --git a/ui/src/components/IssueAttachmentsSection.test.tsx b/ui/src/components/IssueAttachmentsSection.test.tsx
index 3e0bb3a8c9..7683bee9a6 100644
--- a/ui/src/components/IssueAttachmentsSection.test.tsx
+++ b/ui/src/components/IssueAttachmentsSection.test.tsx
@@ -327,4 +327,28 @@ describe("IssueAttachmentsSection", () => {
"/api/attachments/pdf-attachment/content?download=1",
);
});
+
+ it("can render read-only attachments without destructive controls", async () => {
+ const attachment = makeAttachment({
+ id: "read-only-pdf",
+ originalFilename: "stored-report.pdf",
+ contentType: "application/pdf",
+ contentPath: "/api/attachments/read-only-pdf/content",
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <IssueAttachmentsSection attachments={[attachment]} onImageClick={vi.fn()} />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+
+ expect(container.textContent).toContain("stored-report.pdf");
+ expect(container.querySelector('a[aria-label="Open stored-report.pdf"]')).toBeTruthy();
+ expect(container.querySelector('a[aria-label="Download stored-report.pdf"]')).toBeTruthy();
+ expect(container.querySelector('button[title="Delete attachment"]')).toBeNull();
+ expect(container.textContent).not.toContain("Delete this attachment?");
+ });
});
diff --git a/ui/src/components/IssueAttachmentsSection.tsx b/ui/src/components/IssueAttachmentsSection.tsx
index 8f7b934823..0852c0c4f2 100644
--- a/ui/src/components/IssueAttachmentsSection.tsx
+++ b/ui/src/components/IssueAttachmentsSection.tsx
@@ -26,7 +26,7 @@ interface IssueAttachmentsSectionProps {
error?: string | null;
dragActive?: boolean;
deletePending?: boolean;
- onDelete: (attachmentId: string) => void;
+ onDelete?: (attachmentId: string) => void;
onImageClick: (attachment: IssueAttachment) => void;
onDragEnter?: (evt: DragEvent<HTMLDivElement>) => void;
onDragOver?: (evt: DragEvent<HTMLDivElement>) => void;
@@ -51,7 +51,7 @@ function AttachmentActions({
onPreview,
}: {
attachment: IssueAttachment;
- onDelete: (attachmentId: string) => void;
+ onDelete?: (attachmentId: string) => void;
deletePending?: boolean;
onPreview?: (attachment: IssueAttachment) => void;
}) {
@@ -79,16 +79,18 @@ function AttachmentActions({
<Download className="h-4 w-4" />
</a>
</Button>
- <Button
- variant="ghost"
- size="icon-sm"
- title="Delete attachment"
- className="text-muted-foreground hover:text-destructive"
- onClick={() => onDelete(attachment.id)}
- disabled={deletePending}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
+ {onDelete ? (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ title="Delete attachment"
+ className="text-muted-foreground hover:text-destructive"
+ onClick={() => onDelete(attachment.id)}
+ disabled={deletePending}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ ) : null}
</div>
);
}
@@ -107,7 +109,7 @@ function MarkdownAttachmentCard({
deletePending,
}: {
attachment: IssueAttachment;
- onDelete: (attachmentId: string) => void;
+ onDelete?: (attachmentId: string) => void;
deletePending?: boolean;
}) {
const filename = attachmentFilename(attachment);
@@ -152,7 +154,7 @@ function VideoAttachmentCard({
onPreview,
}: {
attachment: IssueAttachment;
- onDelete: (attachmentId: string) => void;
+ onDelete?: (attachmentId: string) => void;
deletePending?: boolean;
onPreview?: (attachment: IssueAttachment) => void;
}) {
@@ -182,7 +184,7 @@ function GenericAttachmentRow({
deletePending,
}: {
attachment: IssueAttachment;
- onDelete: (attachmentId: string) => void;
+ onDelete?: (attachmentId: string) => void;
deletePending?: boolean;
}) {
const filename = attachmentFilename(attachment);
@@ -245,6 +247,7 @@ export function IssueAttachmentsSection({
const requestDelete = (attachmentId: string) => setConfirmDeleteId(attachmentId);
const confirmDelete = (attachmentId: string) => {
+ if (!onDelete) return;
onDelete(attachmentId);
setConfirmDeleteId(null);
};
@@ -289,7 +292,7 @@ export function IssueAttachmentsSection({
loading="lazy"
/>
<div className="absolute inset-0 bg-black/0 transition-colors group-hover:bg-black/30" />
- {confirmDeleteId === attachment.id ? (
+ {onDelete && confirmDeleteId === attachment.id ? (
<div
className="absolute inset-0 flex flex-col items-center justify-center gap-1.5 bg-black/60"
onClick={(event) => event.stopPropagation()}
@@ -319,7 +322,7 @@ export function IssueAttachmentsSection({
</button>
</div>
</div>
- ) : (
+ ) : onDelete ? (
<button
type="button"
className="absolute right-1.5 top-1.5 rounded-md bg-black/50 p-1 text-white opacity-0 transition-opacity hover:bg-destructive group-hover:opacity-100"
@@ -331,7 +334,7 @@ export function IssueAttachmentsSection({
>
<Trash2 className="h-3.5 w-3.5" />
</button>
- )}
+ ) : null}
</div>
))}
</div>
@@ -343,7 +346,7 @@ export function IssueAttachmentsSection({
<MarkdownAttachmentCard
key={attachment.id}
attachment={attachment}
- onDelete={requestDelete}
+ onDelete={onDelete ? requestDelete : undefined}
deletePending={deletePending}
/>
))}
@@ -356,7 +359,7 @@ export function IssueAttachmentsSection({
<VideoAttachmentCard
key={attachment.id}
attachment={attachment}
- onDelete={requestDelete}
+ onDelete={onDelete ? requestDelete : undefined}
deletePending={deletePending}
onPreview={onImageClick}
/>
@@ -370,14 +373,14 @@ export function IssueAttachmentsSection({
<GenericAttachmentRow
key={attachment.id}
attachment={attachment}
- onDelete={requestDelete}
+ onDelete={onDelete ? requestDelete : undefined}
deletePending={deletePending}
/>
))}
</div>
)}
- {confirmDeleteId && !imageAttachments.some((attachment) => attachment.id === confirmDeleteId) ? (
+ {onDelete && confirmDeleteId && !imageAttachments.some((attachment) => attachment.id === confirmDeleteId) ? (
<div className="flex items-center justify-between gap-3 rounded-md border border-destructive/20 bg-destructive/5 px-4 py-3">
<p className="text-sm font-medium text-destructive">Delete this attachment? This cannot be undone.</p>
<div className="flex shrink-0 items-center gap-2">
diff --git a/ui/src/components/Layout.test.tsx b/ui/src/components/Layout.test.tsx
index 968b93eefa..d8e318febc 100644
--- a/ui/src/components/Layout.test.tsx
+++ b/ui/src/components/Layout.test.tsx
@@ -485,6 +485,44 @@ describe("Layout", () => {
});
});
+ it("forces the app sidebar rail only for the Skills Store route", async () => {
+ async function renderAt(pathname: string) {
+ currentPathname = pathname;
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <Layout />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+ await flushReact();
+ return root;
+ }
+
+ let root = await renderAt("/PAP/skills/studio");
+ expect(mockSetForceCollapsed).toHaveBeenCalledWith(true);
+ await act(async () => {
+ root.unmount();
+ });
+
+ mockSetForceCollapsed.mockClear();
+ container.innerHTML = "";
+
+ root = await renderAt("/PAP/agents/briefing-analyst/skills");
+ expect(mockSetForceCollapsed).not.toHaveBeenCalledWith(true);
+ expect(mockSetForceCollapsed).toHaveBeenCalledWith(false);
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
it("renders a route-scoped plugin sidebar for a matching plugin page route", async () => {
currentPathname = "/PAP/wiki";
mockPluginSlots.slots = [
diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsx
index 73e5b9fb2a..c694b81fbf 100644
--- a/ui/src/components/Layout.tsx
+++ b/ui/src/components/Layout.tsx
@@ -52,6 +52,16 @@ function getCompanyRouteSegment(pathname: string, companyPrefix: string | undefi
return segments[1]?.toLowerCase() ?? null;
}
+function isSkillsStoreRoute(pathname: string, companyPrefix: string | undefined) {
+ const segments = pathname.split("/").filter(Boolean);
+ if (segments[0]?.toLowerCase() === "skills") return true;
+ if (!companyPrefix) return false;
+ return (
+ segments[0]?.toUpperCase() === companyPrefix.toUpperCase() &&
+ segments[1]?.toLowerCase() === "skills"
+ );
+}
+
export function Layout() {
const {
sidebarOpen,
@@ -83,8 +93,8 @@ export function Layout() {
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);
+ // app nav collapses to its rail throughout the Skills Store section (PAP-10879).
+ const isSkillsRoute = isSkillsStoreRoute(location.pathname, companyPrefix);
const onboardingTriggered = useRef(false);
const lastMainScrollTop = useRef(0);
const previousPathname = useRef<string | null>(null);
diff --git a/ui/src/components/SkillCardIcon.tsx b/ui/src/components/SkillCardIcon.tsx
new file mode 100644
index 0000000000..7a63c87f4c
--- /dev/null
+++ b/ui/src/components/SkillCardIcon.tsx
@@ -0,0 +1,38 @@
+import { skillAccentColor } from "@/lib/skill-create";
+
+/**
+ * Minimal shape needed to render a skill's square icon. `DiscoveryCard`
+ * (store) and the agent-skills row model both satisfy this, so the icon can be
+ * shared without pulling the whole store page into other modules.
+ */
+export interface SkillIconCard {
+ key: string;
+ name: string;
+ slug?: string | null;
+ iconUrl: string | null;
+ color: string | null;
+}
+
+export function SkillCardIcon({ card, size = 36 }: { card: SkillIconCard; 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 (
+ <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>
+ );
+}
diff --git a/ui/src/components/skill-studio/AgentsUsingSkillDialog.test.tsx b/ui/src/components/skill-studio/AgentsUsingSkillDialog.test.tsx
new file mode 100644
index 0000000000..9652bc7a1a
--- /dev/null
+++ b/ui/src/components/skill-studio/AgentsUsingSkillDialog.test.tsx
@@ -0,0 +1,347 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type {
+ AgentDesiredSkillEntry,
+ CompanySkillDetail,
+ CompanySkillUsageAgent,
+ CompanySkillVersion,
+} from "@paperclipai/shared";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ AgentsUsingSkillBadge,
+ AgentsUsingSkillDialog,
+} from "./AgentsUsingSkillDialog";
+
+const mockAgentsApi = vi.hoisted(() => ({
+ list: vi.fn(),
+ skills: vi.fn(),
+ syncSkills: vi.fn(),
+}));
+const mockCompanySkillsApi = vi.hoisted(() => ({
+ versions: vi.fn(),
+}));
+const mockPushToast = vi.hoisted(() => vi.fn());
+
+vi.mock("@/lib/router", () => ({
+ Link: ({ children, to }: { children: ReactNode; to: string }) => <a href={to}>{children}</a>,
+}));
+vi.mock("@/api/agents", () => ({ agentsApi: mockAgentsApi }));
+vi.mock("@/api/companySkills", () => ({ companySkillsApi: mockCompanySkillsApi }));
+vi.mock("@/adapters/use-adapter-capabilities", () => ({
+ useAdapterCapabilities: () => () => ({
+ supportsInstructionsBundle: true,
+ supportsSkills: true,
+ supportsLocalAgentJwt: true,
+ requiresMaterializedRuntimeSkills: false,
+ supportsModelProfiles: false,
+ }),
+}));
+vi.mock("@/context/ToastContext", () => ({
+ useOptionalToastActions: () => ({ pushToast: mockPushToast }),
+}));
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root | null = null;
+let container: HTMLDivElement | null = null;
+
+// React's `act` is not usable in this vitest setup (known gotcha); drive
+// updates through flushSync like SkillStudio.test.tsx does.
+async function act(callback: () => void | Promise<void>) {
+ let result: void | Promise<void> = undefined;
+ flushSync(() => {
+ result = callback();
+ });
+ await result;
+}
+
+async function flush() {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+}
+
+function teardown() {
+ if (root) flushSync(() => root?.unmount());
+ container?.remove();
+ root = null;
+ container = null;
+ // Radix Dialog portals to document.body; drop any leftovers between renders.
+ document.body.innerHTML = "";
+}
+
+async function renderNode(node: ReactNode) {
+ teardown();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ await act(async () => {
+ root?.render(<QueryClientProvider client={queryClient}>{node}</QueryClientProvider>);
+ });
+ await flush();
+}
+
+async function click(el: Element) {
+ await act(async () => {
+ el.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flush();
+}
+
+function findButton(name: string): HTMLButtonElement {
+ const match = Array.from(document.body.querySelectorAll("button")).find(
+ (button) => button.textContent?.trim() === name,
+ ) as HTMLButtonElement | undefined;
+ if (!match) throw new Error(`No button labelled "${name}"`);
+ return match;
+}
+
+function makeAgent(overrides: Partial<CompanySkillUsageAgent> = {}): CompanySkillUsageAgent {
+ return {
+ id: "agent-1",
+ name: "Reviewer",
+ urlKey: "reviewer",
+ adapterType: "claude_local",
+ desired: true,
+ actualState: null,
+ versionId: null,
+ ...overrides,
+ };
+}
+
+function makeVersion(overrides: Partial<CompanySkillVersion> = {}): CompanySkillVersion {
+ return {
+ id: "ver-1",
+ companyId: "company-1",
+ companySkillId: "skill-1",
+ revisionNumber: 1,
+ label: null,
+ fileInventory: [],
+ authorAgentId: null,
+ authorUserId: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ ...overrides,
+ };
+}
+
+function makeSkill(overrides: Partial<CompanySkillDetail> = {}): CompanySkillDetail {
+ return {
+ id: "skill-1",
+ companyId: "company-1",
+ key: "paperclip/demo",
+ slug: "demo",
+ name: "Demo Skill",
+ description: null,
+ markdown: "",
+ sourceType: "local_path",
+ sourceLocator: null,
+ sourceRef: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [],
+ iconUrl: null,
+ color: null,
+ tagline: null,
+ authorName: null,
+ homepageUrl: null,
+ categories: [],
+ sharingScope: "company",
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 0,
+ installCount: 0,
+ forkCount: 0,
+ currentVersionId: "ver-3",
+ 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: makeVersion({ id: "ver-3", revisionNumber: 3 }),
+ starredByCurrentActor: false,
+ existingForks: [],
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ mockAgentsApi.list.mockResolvedValue([]);
+ mockAgentsApi.skills.mockResolvedValue({
+ adapterType: "claude_local",
+ supported: true,
+ mode: "managed",
+ desiredSkills: [],
+ desiredSkillEntries: [],
+ entries: [],
+ warnings: [],
+ });
+ mockAgentsApi.syncSkills.mockResolvedValue({});
+ mockCompanySkillsApi.versions.mockResolvedValue([]);
+ mockPushToast.mockReset();
+});
+
+afterEach(() => {
+ teardown();
+ vi.clearAllMocks();
+});
+
+describe("AgentsUsingSkillBadge", () => {
+ it("renders a muted '0 agents' button with an a11y label when unused", async () => {
+ await renderNode(<AgentsUsingSkillBadge companyId="company-1" skill={makeSkill()} />);
+ const badge = findButton("0 agents");
+ expect(badge).toBeDefined();
+ expect(badge?.getAttribute("aria-label")).toBe("0 agents use this skill");
+ expect(badge?.className).toContain("text-muted-foreground");
+ });
+
+ it("pluralizes and opens the dialog on click", async () => {
+ const skill = makeSkill({
+ usedByAgents: [makeAgent(), makeAgent({ id: "agent-2", name: "Coder", urlKey: "coder" })],
+ });
+ await renderNode(<AgentsUsingSkillBadge companyId="company-1" skill={skill} />);
+ const badge = findButton("2 agents");
+ expect(badge?.getAttribute("aria-label")).toBe("2 agents use this skill");
+ await click(badge!);
+ expect(document.body.textContent).toContain("Agents using Demo Skill");
+ expect(document.body.textContent).toContain("Reviewer");
+ expect(document.body.textContent).toContain("Coder");
+ });
+});
+
+describe("AgentsUsingSkillDialog", () => {
+ it("shows a version select with Latest (vN) and a static '—' when no version history", async () => {
+ mockCompanySkillsApi.versions.mockResolvedValue([
+ makeVersion({ id: "ver-3", revisionNumber: 3 }),
+ makeVersion({ id: "ver-2", revisionNumber: 2 }),
+ ]);
+ const skill = makeSkill({ usedByAgents: [makeAgent()] });
+ await renderNode(
+ <AgentsUsingSkillDialog open onOpenChange={() => {}} companyId="company-1" skill={skill} />,
+ );
+ const select = document.body.querySelector("select");
+ expect(select).not.toBeNull();
+ expect(select?.textContent).toContain("Latest (v3)");
+ expect(select?.textContent).toContain("v2");
+
+ // No version history → "—" and no select.
+ await renderNode(
+ <AgentsUsingSkillDialog
+ open
+ onOpenChange={() => {}}
+ companyId="company-1"
+ skill={makeSkill({ currentVersion: null, currentVersionId: null, usedByAgents: [makeAgent()] })}
+ />,
+ );
+ // The second render's dialog is the last-opened; its row shows an em dash.
+ expect(document.body.textContent).toContain("—");
+ });
+
+ it("shows a 'behind latest' hint for a stale pin", async () => {
+ mockCompanySkillsApi.versions.mockResolvedValue([
+ makeVersion({ id: "ver-3", revisionNumber: 3 }),
+ makeVersion({ id: "ver-1", revisionNumber: 1 }),
+ ]);
+ const skill = makeSkill({ usedByAgents: [makeAgent({ versionId: "ver-1" })] });
+ await renderNode(
+ <AgentsUsingSkillDialog open onOpenChange={() => {}} companyId="company-1" skill={skill} />,
+ );
+ expect(document.body.textContent).toContain("2 versions behind latest");
+ });
+
+ it("removes via GET-then-sync and preserves the agent's other skills", async () => {
+ mockAgentsApi.skills.mockResolvedValue({
+ adapterType: "claude_local",
+ supported: true,
+ mode: "managed",
+ desiredSkills: ["paperclip/demo", "paperclip/other"],
+ desiredSkillEntries: [
+ { key: "paperclip/demo", versionId: null },
+ { key: "paperclip/other", versionId: null },
+ ] satisfies AgentDesiredSkillEntry[],
+ entries: [],
+ warnings: [],
+ });
+ const skill = makeSkill({ usedByAgents: [makeAgent()] });
+ await renderNode(
+ <AgentsUsingSkillDialog open onOpenChange={() => {}} companyId="company-1" skill={skill} />,
+ );
+
+ // The trash button has no text; grab it by aria-label.
+ const trash = document.body.querySelector<HTMLButtonElement>(
+ 'button[aria-label^="Remove this skill from"]',
+ );
+ await click(trash!);
+ const confirm = document.body.querySelector<HTMLButtonElement>(
+ 'button[aria-label^="Confirm removing this skill from"]',
+ );
+ await click(confirm!);
+
+ expect(mockAgentsApi.skills).toHaveBeenCalledWith("agent-1", "company-1");
+ expect(mockAgentsApi.syncSkills).toHaveBeenCalledTimes(1);
+ const [, sentEntries] = mockAgentsApi.syncSkills.mock.calls[0];
+ expect(sentEntries).toEqual([{ key: "paperclip/other", versionId: null }]);
+ });
+
+ it("pins a version by sending the full set with the target repinned", async () => {
+ mockCompanySkillsApi.versions.mockResolvedValue([
+ makeVersion({ id: "ver-3", revisionNumber: 3 }),
+ makeVersion({ id: "ver-2", revisionNumber: 2 }),
+ ]);
+ mockAgentsApi.skills.mockResolvedValue({
+ adapterType: "claude_local",
+ supported: true,
+ mode: "managed",
+ desiredSkills: ["paperclip/demo", "paperclip/other"],
+ desiredSkillEntries: [
+ { key: "paperclip/demo", versionId: null },
+ { key: "paperclip/other", versionId: null },
+ ] satisfies AgentDesiredSkillEntry[],
+ entries: [],
+ warnings: [],
+ });
+ const skill = makeSkill({ usedByAgents: [makeAgent()] });
+ await renderNode(
+ <AgentsUsingSkillDialog open onOpenChange={() => {}} companyId="company-1" skill={skill} />,
+ );
+ const select = document.body.querySelector<HTMLSelectElement>("select");
+ await act(async () => {
+ const setter = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, "value")?.set;
+ setter?.call(select, "ver-2");
+ select?.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ await flush();
+
+ expect(mockAgentsApi.syncSkills).toHaveBeenCalledTimes(1);
+ const [, sentEntries] = mockAgentsApi.syncSkills.mock.calls[0];
+ expect(sentEntries).toContainEqual({ key: "paperclip/other", versionId: null });
+ expect(sentEntries).toContainEqual({ key: "paperclip/demo", versionId: "ver-2" });
+ });
+
+ it("hides mutating controls in read-only mode but keeps the roster", async () => {
+ const skill = makeSkill({ usedByAgents: [makeAgent()] });
+ await renderNode(
+ <AgentsUsingSkillDialog
+ open
+ onOpenChange={() => {}}
+ companyId="company-1"
+ skill={skill}
+ canManage={false}
+ />,
+ );
+ expect(document.body.textContent).toContain("Reviewer");
+ expect(document.body.querySelector('button[aria-label^="Remove this skill from"]')).toBeNull();
+ expect(document.body.querySelector("select")).toBeNull();
+ });
+});
diff --git a/ui/src/components/skill-studio/AgentsUsingSkillDialog.tsx b/ui/src/components/skill-studio/AgentsUsingSkillDialog.tsx
new file mode 100644
index 0000000000..aa88f29119
--- /dev/null
+++ b/ui/src/components/skill-studio/AgentsUsingSkillDialog.tsx
@@ -0,0 +1,477 @@
+import { useEffect, useMemo, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Loader2, Plus, Trash2, Users } from "lucide-react";
+import type {
+ Agent,
+ AgentDesiredSkillEntry,
+ CompanySkillDetail,
+ CompanySkillUsageAgent,
+ CompanySkillVersion,
+} from "@paperclipai/shared";
+import { Link } from "@/lib/router";
+import { agentsApi } from "@/api/agents";
+import { companySkillsApi } from "@/api/companySkills";
+import { queryKeys } from "@/lib/queryKeys";
+import { useAdapterCapabilities } from "@/adapters/use-adapter-capabilities";
+import { useOptionalToastActions } from "@/context/ToastContext";
+import { AgentIcon } from "@/components/AgentIconPicker";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ SearchableSelect,
+ type SearchableSelectGroup,
+ type SearchableSelectOption,
+} from "@/components/SearchableSelect";
+import { cn } from "@/lib/utils";
+
+const LATEST_VALUE = "__latest__";
+
+// A single change the operator can request against one agent's desired skill
+// set. The sync endpoint replaces the *entire* set, so every mutation is
+// applied against a freshly fetched snapshot (see `applyChange`).
+type SkillChange =
+ | { kind: "add" }
+ | { kind: "remove" }
+ | { kind: "pin"; versionId: string | null };
+
+/**
+ * Header pill that shows how many agents have this skill in their desired set
+ * and opens the management modal. Owns the dialog's open state so the header
+ * stays declarative.
+ */
+export function AgentsUsingSkillBadge({
+ companyId,
+ skill,
+ canManage = true,
+}: {
+ companyId: string;
+ skill: CompanySkillDetail;
+ canManage?: boolean;
+}) {
+ const [open, setOpen] = useState(false);
+ const count = skill.usedByAgents.length;
+ const label = `${count} ${count === 1 ? "agent uses" : "agents use"} this skill`;
+
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => setOpen(true)}
+ aria-label={label}
+ className={cn(
+ "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors",
+ count > 0
+ ? "border-border bg-muted text-foreground hover:bg-accent"
+ : "border-border/60 bg-transparent text-muted-foreground hover:bg-accent/50",
+ )}
+ >
+ <Users className="h-3.5 w-3.5" aria-hidden="true" />
+ {count} {count === 1 ? "agent" : "agents"}
+ </button>
+ <AgentsUsingSkillDialog
+ open={open}
+ onOpenChange={setOpen}
+ companyId={companyId}
+ skill={skill}
+ canManage={canManage}
+ />
+ </>
+ );
+}
+
+/**
+ * Modal listing the agents that have this skill assigned, with per-agent
+ * version pinning and add/remove. All writes go through
+ * `POST /api/agents/:id/skills/sync`, which *replaces* the agent's whole
+ * desired set — so we always read the agent's current set first and send it
+ * back with just the one change applied (never derive from skill-detail data).
+ */
+export function AgentsUsingSkillDialog({
+ open,
+ onOpenChange,
+ companyId,
+ skill,
+ canManage = true,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ companyId: string;
+ skill: CompanySkillDetail;
+ canManage?: boolean;
+}) {
+ const queryClient = useQueryClient();
+ const toast = useOptionalToastActions();
+ const adapterCaps = useAdapterCapabilities();
+ const [pendingAgentId, setPendingAgentId] = useState<string | null>(null);
+ const [confirmRemoveId, setConfirmRemoveId] = useState<string | null>(null);
+
+ // Lazy: only fetch versions/agents once the modal is open. Skills with no
+ // version history (currentVersion === null, e.g. read-only catalog/bundled)
+ // never render a pin select, so their versions query stays disabled.
+ const hasVersions = skill.currentVersion !== null;
+ const versionsQuery = useQuery({
+ queryKey: queryKeys.companySkills.versions(companyId, skill.id),
+ queryFn: () => companySkillsApi.versions(companyId, skill.id),
+ enabled: open && hasVersions,
+ });
+ const agentsQuery = useQuery({
+ queryKey: queryKeys.agents.list(companyId),
+ queryFn: () => agentsApi.list(companyId),
+ enabled: open,
+ });
+
+ useEffect(() => {
+ if (!open) setConfirmRemoveId(null);
+ }, [open]);
+
+ const versions = useMemo<CompanySkillVersion[]>(
+ () => [...(versionsQuery.data ?? [])].sort((a, b) => b.revisionNumber - a.revisionNumber),
+ [versionsQuery.data],
+ );
+ const latestRevision = skill.currentVersion?.revisionNumber ?? null;
+ const revisionByVersionId = useMemo(
+ () => new Map(versions.map((version) => [version.id, version.revisionNumber])),
+ [versions],
+ );
+
+ const agentMetaById = useMemo(
+ () => new Map((agentsQuery.data ?? []).map((agent) => [agent.id, agent])),
+ [agentsQuery.data],
+ );
+
+ // Company agents that support skills and don't already have this one — the
+ // footer add-agent picker.
+ const attachedIds = useMemo(
+ () => new Set(skill.usedByAgents.map((entry) => entry.id)),
+ [skill.usedByAgents],
+ );
+ const addableAgents = useMemo(
+ () =>
+ (agentsQuery.data ?? [])
+ .filter(
+ (agent) =>
+ !attachedIds.has(agent.id) &&
+ agent.status !== "terminated" &&
+ adapterCaps(agent.adapterType).supportsSkills,
+ )
+ .sort((a, b) => a.name.localeCompare(b.name)),
+ [agentsQuery.data, attachedIds, adapterCaps],
+ );
+
+ const syncMutation = useMutation({
+ mutationFn: async ({
+ agent,
+ change,
+ }: {
+ agent: Pick<CompanySkillUsageAgent, "id" | "name"> | Agent;
+ change: SkillChange;
+ }) => {
+ const skillKey = skill.key;
+ const snapshot = await agentsApi.skills(agent.id, companyId);
+ // Prefer the richer entries payload; fall back to bare keys (versionId
+ // null = tracks latest) for older snapshots.
+ const currentEntries: AgentDesiredSkillEntry[] =
+ snapshot.desiredSkillEntries ?? snapshot.desiredSkills.map((key) => ({ key, versionId: null }));
+ const others = currentEntries.filter((entry) => entry.key !== skillKey);
+ const nextEntries = [...others];
+ if (change.kind !== "remove") {
+ const versionId = change.kind === "pin" ? change.versionId : null;
+ nextEntries.push({ key: skillKey, versionId });
+ }
+ // Set-equality round-trip: skip the write if nothing actually changed so
+ // we don't churn the agent's config (order-insensitive per b8b6f4446).
+ if (desiredSetsEqual(currentEntries, nextEntries)) {
+ return { agentId: agent.id, changed: false };
+ }
+ await agentsApi.syncSkills(agent.id, nextEntries, companyId);
+ return { agentId: agent.id, changed: true };
+ },
+ onSuccess: async ({ agentId }) => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(companyId, skill.id) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(companyId) }),
+ // Keep the agent's own Skills tab (PAP-13194) in sync.
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.skills(agentId) }),
+ ]);
+ },
+ onError: (error) => {
+ const message = error instanceof Error ? error.message : "Failed to update agent skills.";
+ toast?.pushToast({
+ tone: "error",
+ title: "Update failed",
+ body: message.includes("403") ? "You don't have permission to change this agent's skills." : message,
+ });
+ },
+ });
+
+ async function applyChange(
+ agent: Pick<CompanySkillUsageAgent, "id" | "name"> | Agent,
+ change: SkillChange,
+ ) {
+ setPendingAgentId(agent.id);
+ try {
+ await syncMutation.mutateAsync({ agent, change });
+ setConfirmRemoveId(null);
+ } catch {
+ // Toast already surfaced by the mutation's onError.
+ } finally {
+ setPendingAgentId(null);
+ }
+ }
+
+ const rows = skill.usedByAgents;
+ const count = rows.length;
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Agents using {skill.name}</DialogTitle>
+ <DialogDescription>
+ {count === 0
+ ? "No agents have this skill assigned yet."
+ : `${count} ${count === 1 ? "agent has" : "agents have"} this skill in their desired set.`}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="max-h-80 overflow-y-auto">
+ {count === 0 ? (
+ <div className="rounded-md border border-dashed border-border px-4 py-8 text-center text-sm text-muted-foreground">
+ {canManage
+ ? "Add an agent below to assign this skill."
+ : "This skill isn't assigned to any agents."}
+ </div>
+ ) : (
+ <ul className="divide-y divide-border">
+ {rows.map((agent) => (
+ <AgentRow
+ key={agent.id}
+ agent={agent}
+ icon={agentMetaById.get(agent.id)?.icon ?? null}
+ canManage={canManage}
+ hasVersions={hasVersions}
+ versions={versions}
+ latestRevision={latestRevision}
+ pinnedRevision={agent.versionId ? revisionByVersionId.get(agent.versionId) ?? null : null}
+ busy={pendingAgentId === agent.id}
+ confirmingRemove={confirmRemoveId === agent.id}
+ onRequestRemove={() => setConfirmRemoveId(agent.id)}
+ onCancelRemove={() => setConfirmRemoveId(null)}
+ onRemove={() => applyChange(agent, { kind: "remove" })}
+ onPin={(versionId) => applyChange(agent, { kind: "pin", versionId })}
+ />
+ ))}
+ </ul>
+ )}
+ </div>
+
+ {canManage ? (
+ <div className="flex items-center gap-2 border-t border-border pt-3">
+ <AddAgentPicker
+ agents={addableAgents}
+ loading={agentsQuery.isLoading}
+ disabled={syncMutation.isPending}
+ onSelect={(agent) => applyChange(agent, { kind: "add" })}
+ />
+ {syncMutation.isPending ? (
+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" aria-hidden="true" />
+ ) : null}
+ </div>
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function AgentRow({
+ agent,
+ icon,
+ canManage,
+ hasVersions,
+ versions,
+ latestRevision,
+ pinnedRevision,
+ busy,
+ confirmingRemove,
+ onRequestRemove,
+ onCancelRemove,
+ onRemove,
+ onPin,
+}: {
+ agent: CompanySkillUsageAgent;
+ icon: string | null;
+ canManage: boolean;
+ hasVersions: boolean;
+ versions: CompanySkillVersion[];
+ latestRevision: number | null;
+ pinnedRevision: number | null;
+ busy: boolean;
+ confirmingRemove: boolean;
+ onRequestRemove: () => void;
+ onCancelRemove: () => void;
+ onRemove: () => void;
+ onPin: (versionId: string | null) => void;
+}) {
+ const behindLatest =
+ pinnedRevision !== null && latestRevision !== null && latestRevision > pinnedRevision
+ ? latestRevision - pinnedRevision
+ : 0;
+
+ return (
+ <li className="flex items-center gap-3 py-2.5">
+ <AgentIcon icon={icon} className="h-6 w-6 shrink-0 rounded-md text-muted-foreground" />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <Link
+ to={`/agents/${agent.urlKey}/skills`}
+ className="truncate text-sm font-medium text-foreground hover:underline"
+ >
+ {agent.name}
+ </Link>
+ <span className="truncate text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-muted-foreground">
+ {agent.adapterType}
+ </span>
+ </div>
+
+ <div className="flex shrink-0 flex-col items-end gap-0.5">
+ {!hasVersions ? (
+ <span className="text-sm text-muted-foreground" aria-label={`${agent.name} version`}>
+ —
+ </span>
+ ) : canManage ? (
+ <select
+ aria-label={`${agent.name} skill version`}
+ value={agent.versionId ?? LATEST_VALUE}
+ disabled={busy}
+ onChange={(event) =>
+ onPin(event.target.value === LATEST_VALUE ? null : event.target.value)
+ }
+ className="h-8 rounded-md border border-border bg-background px-2 text-xs text-foreground disabled:opacity-60"
+ >
+ <option value={LATEST_VALUE}>
+ Latest{latestRevision !== null ? ` (v${latestRevision})` : ""}
+ </option>
+ {versions.map((version) => (
+ <option key={version.id} value={version.id}>
+ v{version.revisionNumber}
+ {version.label ? ` · ${version.label}` : ""}
+ </option>
+ ))}
+ </select>
+ ) : (
+ <span className="text-xs text-muted-foreground">
+ {agent.versionId
+ ? `v${pinnedRevision ?? "?"}`
+ : `Latest${latestRevision !== null ? ` (v${latestRevision})` : ""}`}
+ </span>
+ )}
+ {behindLatest > 0 ? (
+ <span className="text-(length:--text-nano) text-amber-500">
+ {behindLatest} version{behindLatest === 1 ? "" : "s"} behind latest
+ </span>
+ ) : null}
+ </div>
+
+ {canManage ? (
+ confirmingRemove ? (
+ <div className="flex shrink-0 items-center gap-1">
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={onRemove}
+ disabled={busy}
+ aria-label={`Confirm removing this skill from ${agent.name}`}
+ >
+ {busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : "Remove"}
+ </Button>
+ <Button variant="ghost" size="sm" onClick={onCancelRemove} disabled={busy}>
+ Cancel
+ </Button>
+ </div>
+ ) : (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={onRequestRemove}
+ disabled={busy}
+ className="shrink-0 text-muted-foreground hover:text-destructive"
+ aria-label={`Remove this skill from ${agent.name}`}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ )
+ ) : null}
+ </li>
+ );
+}
+
+function AddAgentPicker({
+ agents,
+ loading,
+ disabled,
+ onSelect,
+}: {
+ agents: Agent[];
+ loading: boolean;
+ disabled: boolean;
+ onSelect: (agent: Agent) => void;
+}) {
+ type AgentOption = SearchableSelectOption<string> & { agent: Agent };
+ const groups = useMemo<readonly SearchableSelectGroup<string, AgentOption>[]>(() => {
+ const options: AgentOption[] = agents.map((agent) => ({
+ key: agent.id,
+ value: agent.id,
+ label: agent.name,
+ title: agent.name,
+ searchText: [agent.name, agent.adapterType].join(" "),
+ agent,
+ }));
+ return [{ id: "agents", options }];
+ }, [agents]);
+
+ return (
+ <SearchableSelect<string, AgentOption>
+ value=""
+ groups={groups}
+ loading={loading}
+ loadingMessage="Loading agents..."
+ placeholder="Add agent…"
+ searchPlaceholder="Search agents..."
+ emptyMessage="All eligible agents already have this skill."
+ disabled={disabled}
+ onValueChange={(_value, option) => {
+ onSelect(option.agent);
+ return { close: true };
+ }}
+ triggerClassName="h-8 w-full justify-start"
+ contentClassName="w-72"
+ renderValue={() => (
+ <span className="flex items-center gap-1.5 text-muted-foreground">
+ <Plus className="h-3.5 w-3.5" aria-hidden="true" />
+ Add agent…
+ </span>
+ )}
+ renderOption={(option) => (
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate">{option.label}</span>
+ <span className="truncate text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-muted-foreground">
+ {option.agent.adapterType}
+ </span>
+ </span>
+ )}
+ />
+ );
+}
+
+/** Order-insensitive comparison of desired skill sets by (key, versionId). */
+function desiredSetsEqual(a: AgentDesiredSkillEntry[], b: AgentDesiredSkillEntry[]): boolean {
+ if (a.length !== b.length) return false;
+ const encode = (entry: AgentDesiredSkillEntry) => `${entry.key}${entry.versionId ?? ""}`;
+ const setA = new Set(a.map(encode));
+ return b.every((entry) => setA.has(encode(entry)));
+}
diff --git a/ui/src/components/skill-studio/ForkSkillDialog.test.tsx b/ui/src/components/skill-studio/ForkSkillDialog.test.tsx
new file mode 100644
index 0000000000..0f036cbdac
--- /dev/null
+++ b/ui/src/components/skill-studio/ForkSkillDialog.test.tsx
@@ -0,0 +1,304 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type {
+ CompanySkillDetail,
+ CompanySkillForkPrecheckResult,
+ CompanySkillForkSummary,
+ CompanySkillUsageAgent,
+} from "@paperclipai/shared";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ForkSkillDialog } from "./ForkSkillDialog";
+
+const mockNavigate = vi.hoisted(() => vi.fn());
+const mockCompanySkillsApi = vi.hoisted(() => ({
+ fork: vi.fn(),
+ forkPrecheck: vi.fn(),
+ detail: vi.fn(),
+}));
+const mockPushToast = vi.hoisted(() => vi.fn());
+
+vi.mock("@/lib/router", () => ({
+ Link: ({ children, to }: { children: ReactNode; to: string }) => <a href={to}>{children}</a>,
+ useNavigate: () => mockNavigate,
+}));
+vi.mock("@/api/companySkills", () => ({ companySkillsApi: mockCompanySkillsApi }));
+vi.mock("@/context/ToastContext", () => ({
+ useOptionalToastActions: () => ({ pushToast: mockPushToast }),
+}));
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root | null = null;
+let container: HTMLDivElement | null = null;
+
+// React's `act` is not usable in this vitest setup; drive updates via flushSync
+// like SkillStudio.test.tsx / AgentsUsingSkillDialog.test.tsx do.
+async function act(callback: () => void | Promise<void>) {
+ let result: void | Promise<void> = undefined;
+ flushSync(() => {
+ result = callback();
+ });
+ await result;
+}
+
+async function flush() {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+}
+
+function teardown() {
+ if (root) flushSync(() => root?.unmount());
+ container?.remove();
+ root = null;
+ container = null;
+ document.body.innerHTML = "";
+}
+
+async function renderNode(node: ReactNode) {
+ teardown();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ await act(async () => {
+ root?.render(<QueryClientProvider client={queryClient}>{node}</QueryClientProvider>);
+ });
+ await flush();
+}
+
+async function click(el: Element) {
+ await act(async () => {
+ el.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flush();
+}
+
+function findButton(match: (text: string) => boolean): HTMLButtonElement {
+ const found = Array.from(document.body.querySelectorAll("button")).find((button) =>
+ match(button.textContent?.trim() ?? ""),
+ ) as HTMLButtonElement | undefined;
+ if (!found) throw new Error("button not found");
+ return found;
+}
+
+function makeAgent(over: Partial<CompanySkillUsageAgent> = {}): CompanySkillUsageAgent {
+ return {
+ id: "agent-1",
+ name: "Reviewer",
+ urlKey: "reviewer",
+ adapterType: "claude_local",
+ desired: true,
+ actualState: null,
+ versionId: null,
+ ...over,
+ };
+}
+
+function makeSkill(over: Partial<CompanySkillDetail> = {}): CompanySkillDetail {
+ return {
+ id: "skill-1",
+ companyId: "company-1",
+ key: "github/anthropics/skills",
+ slug: "deep-research",
+ name: "Deep Research",
+ description: null,
+ markdown: "",
+ sourceType: "github",
+ sourceLocator: "https://github.com/anthropics/skills",
+ sourceRef: "0123456789abcdef0123456789abcdef01234567",
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [],
+ iconUrl: null,
+ color: null,
+ tagline: null,
+ authorName: null,
+ homepageUrl: null,
+ categories: [],
+ sharingScope: "company",
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 0,
+ installCount: 0,
+ forkCount: 0,
+ currentVersionId: "ver-1",
+ metadata: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ updatedAt: new Date("2026-01-02T00:00:00Z"),
+ attachedAgentCount: 0,
+ usedByAgents: [],
+ editable: false,
+ editableReason: "This skill comes from GitHub and is read-only.",
+ sourceLabel: "GitHub",
+ sourceBadge: "github",
+ sourcePath: null,
+ currentVersion: null,
+ starredByCurrentActor: false,
+ existingForks: [],
+ ...over,
+ };
+}
+
+function makePrecheck(over: Partial<CompanySkillForkPrecheckResult> = {}): CompanySkillForkPrecheckResult {
+ return {
+ skillId: "skill-1",
+ original: {
+ id: "skill-1",
+ name: "Deep Research",
+ slug: "deep-research",
+ sourceType: "github",
+ sourceLocator: "https://github.com/anthropics/skills",
+ sourceRef: "0123456789abcdef0123456789abcdef01234567",
+ },
+ agentUsageCount: 0,
+ usedByAgents: [],
+ existingForks: [],
+ ...over,
+ };
+}
+
+function makeForkSummary(over: Partial<CompanySkillForkSummary> = {}): CompanySkillForkSummary {
+ return {
+ id: "fork-existing",
+ name: "Deep Research (copy)",
+ slug: "deep-research-fork",
+ sourceType: "local_path",
+ sourceLocator: null,
+ sourceRef: null,
+ key: "company/deep-research-fork",
+ forkedFromSkillId: "skill-1",
+ forkedFromCompanyId: "company-1",
+ currentVersionId: "v1",
+ createdByCurrentActor: true,
+ diverged: false,
+ createdAt: new Date("2026-07-01T00:00:00Z"),
+ updatedAt: new Date("2026-07-01T00:00:00Z"),
+ ...over,
+ };
+}
+
+beforeEach(() => {
+ mockCompanySkillsApi.forkPrecheck.mockResolvedValue(makePrecheck());
+ mockCompanySkillsApi.fork.mockResolvedValue({
+ skill: { id: "fork-new" },
+ original: makePrecheck().original,
+ reassignments: [],
+ });
+ mockCompanySkillsApi.detail.mockResolvedValue(makeSkill());
+ mockNavigate.mockReset();
+ mockPushToast.mockReset();
+});
+
+afterEach(() => {
+ teardown();
+ vi.clearAllMocks();
+});
+
+describe("ForkSkillDialog", () => {
+ it("shows the agent count prominently and forks with reassignment ON by default", async () => {
+ const agents = [makeAgent({ id: "a1", name: "Reviewer" }), makeAgent({ id: "a2", name: "Planner" })];
+ mockCompanySkillsApi.forkPrecheck.mockResolvedValue(
+ makePrecheck({ agentUsageCount: 2, usedByAgents: agents }),
+ );
+ mockCompanySkillsApi.fork.mockResolvedValue({
+ skill: { id: "fork-new" },
+ original: makePrecheck().original,
+ reassignments: [
+ { agentId: "a1", previousSkillKey: "k", nextSkillKey: "kf" },
+ { agentId: "a2", previousSkillKey: "k", nextSkillKey: "kf" },
+ ],
+ });
+
+ await renderNode(
+ <ForkSkillDialog
+ companyId="company-1"
+ skill={makeSkill({ usedByAgents: agents, attachedAgentCount: 2 })}
+ open
+ onOpenChange={() => {}}
+ />,
+ );
+
+ expect(document.body.textContent).toContain("2 agents currently use this skill");
+ expect(document.body.textContent).toContain("Reviewer");
+ expect(document.body.textContent).toContain("Planner");
+
+ const confirm = findButton((t) => t.startsWith("Create copy & switch 2 agents"));
+ await click(confirm);
+
+ expect(mockCompanySkillsApi.fork).toHaveBeenCalledWith("company-1", "skill-1", {
+ reassignAgentIds: ["a1", "a2"],
+ });
+ expect(mockNavigate).toHaveBeenCalledWith("/skills/studio/fork-new");
+ expect(mockPushToast).toHaveBeenCalledWith(
+ expect.objectContaining({ tone: "success" }),
+ );
+ });
+
+ it("forks with NO reassignment when the toggle is switched off", async () => {
+ const agents = [makeAgent({ id: "a1" })];
+ mockCompanySkillsApi.forkPrecheck.mockResolvedValue(
+ makePrecheck({ agentUsageCount: 1, usedByAgents: agents }),
+ );
+
+ await renderNode(
+ <ForkSkillDialog
+ companyId="company-1"
+ skill={makeSkill({ usedByAgents: agents, attachedAgentCount: 1 })}
+ open
+ onOpenChange={() => {}}
+ />,
+ );
+
+ const toggle = document.body.querySelector<HTMLButtonElement>(
+ 'button[aria-label="Switch these agents to the copy"]',
+ );
+ expect(toggle).toBeTruthy();
+ expect(toggle?.getAttribute("aria-checked")).toBe("true");
+ await click(toggle!);
+ expect(toggle?.getAttribute("aria-checked")).toBe("false");
+
+ await click(findButton((t) => t === "Create copy"));
+
+ expect(mockCompanySkillsApi.fork).toHaveBeenCalledWith("company-1", "skill-1", {
+ reassignAgentIds: [],
+ });
+ });
+
+ it("offers 'Open your existing copy' when an un-diverged same-actor fork exists", async () => {
+ mockCompanySkillsApi.forkPrecheck.mockResolvedValue(
+ makePrecheck({ existingForks: [makeForkSummary({ id: "fork-existing" })] }),
+ );
+
+ await renderNode(
+ <ForkSkillDialog
+ companyId="company-1"
+ skill={makeSkill({ existingForks: [makeForkSummary({ id: "fork-existing" })] })}
+ open
+ onOpenChange={() => {}}
+ />,
+ );
+
+ expect(document.body.textContent).toContain("You already have a copy");
+ await click(findButton((t) => t === "Open your existing copy"));
+ expect(mockNavigate).toHaveBeenCalledWith("/skills/studio/fork-existing");
+ expect(mockCompanySkillsApi.fork).not.toHaveBeenCalled();
+ });
+
+ it("hides the toggle and reports zero usage when no agents use the skill", async () => {
+ await renderNode(
+ <ForkSkillDialog companyId="company-1" skill={makeSkill()} open onOpenChange={() => {}} />,
+ );
+
+ expect(document.body.textContent).toContain("No agents currently use this skill");
+ expect(
+ document.body.querySelector('button[aria-label="Switch these agents to the copy"]'),
+ ).toBeNull();
+ });
+});
diff --git a/ui/src/components/skill-studio/ForkSkillDialog.tsx b/ui/src/components/skill-studio/ForkSkillDialog.tsx
new file mode 100644
index 0000000000..1a3ae5c578
--- /dev/null
+++ b/ui/src/components/skill-studio/ForkSkillDialog.tsx
@@ -0,0 +1,251 @@
+import { useEffect, useMemo, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { GitFork, Loader2, Users } from "lucide-react";
+import type {
+ CompanySkillDetail,
+ CompanySkillForkPrecheckResult,
+} from "@paperclipai/shared";
+import { useNavigate } from "@/lib/router";
+import { companySkillsApi } from "@/api/companySkills";
+import { queryKeys } from "@/lib/queryKeys";
+import { skillStudioRoute } from "@/lib/company-skill-routes";
+import { useOptionalToastActions } from "@/context/ToastContext";
+import {
+ agentUsageSentence,
+ pickReusableFork,
+ reassignTargetIds,
+} from "@/lib/skill-fork";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { ToggleSwitch } from "@/components/ui/toggle-switch";
+import { cn } from "@/lib/utils";
+
+/**
+ * "Edit a copy" confirm dialog for read-only external skills (PAP-13112,
+ * plan §3.1 / §3.2). Forks the skill through the existing fork endpoint and —
+ * critically (P3, Dotta: "important! definitely need to show this to the
+ * user") — surfaces how many agents run the original and offers a default-ON
+ * switch to move them to the copy. When an un-diverged copy by the current
+ * actor already exists, it offers to open that instead of minting another
+ * (fork-sprawl guard, §5).
+ */
+export function ForkSkillDialog({
+ companyId,
+ skill,
+ open,
+ onOpenChange,
+}: {
+ companyId: string;
+ skill: CompanySkillDetail;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const navigate = useNavigate();
+ const queryClient = useQueryClient();
+ const toast = useOptionalToastActions();
+ const [reassign, setReassign] = useState(true);
+
+ // Seed from the already-loaded skill detail so the dialog renders instantly,
+ // then let the dedicated precheck endpoint refresh usage/existing-fork data.
+ const seededPrecheck: CompanySkillForkPrecheckResult = useMemo(
+ () => ({
+ skillId: skill.id,
+ original: {
+ id: skill.id,
+ name: skill.name,
+ slug: skill.slug,
+ sourceType: skill.sourceType,
+ sourceLocator: skill.sourceLocator,
+ sourceRef: skill.sourceRef,
+ },
+ agentUsageCount: skill.attachedAgentCount,
+ usedByAgents: skill.usedByAgents,
+ existingForks: skill.existingForks,
+ }),
+ [skill],
+ );
+
+ const precheckQuery = useQuery({
+ queryKey: queryKeys.companySkills.forkPrecheck(companyId, skill.id),
+ queryFn: () => companySkillsApi.forkPrecheck(companyId, skill.id),
+ enabled: open && Boolean(companyId && skill.id),
+ initialData: seededPrecheck,
+ });
+
+ const precheck = precheckQuery.data ?? seededPrecheck;
+ const usedByAgents = precheck.usedByAgents;
+ const agentCount = precheck.agentUsageCount;
+ const reusableFork = useMemo(
+ () => pickReusableFork(precheck.existingForks),
+ [precheck.existingForks],
+ );
+
+ // Reset the toggle each time the dialog opens (default ON per §3.2).
+ useEffect(() => {
+ if (open) setReassign(true);
+ }, [open]);
+
+ const forkMutation = useMutation({
+ mutationFn: () =>
+ companySkillsApi.fork(companyId, skill.id, {
+ reassignAgentIds: reassign ? reassignTargetIds(usedByAgents) : [],
+ }),
+ onSuccess: (result) => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(companyId) });
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.detail(companyId, skill.id),
+ });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(companyId) });
+ for (const entry of result.reassignments) {
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.agents.skills(entry.agentId),
+ });
+ }
+ const switched = result.reassignments.length;
+ toast?.pushToast({
+ tone: "success",
+ title: "Editing a copy",
+ body:
+ switched > 0
+ ? `Created a copy of ${skill.name} and switched ${switched} ${switched === 1 ? "agent" : "agents"} to it.`
+ : `Created a copy of ${skill.name}. It's now editable.`,
+ });
+ onOpenChange(false);
+ navigate(skillStudioRoute(result.skill.id));
+ },
+ onError: (error) => {
+ toast?.pushToast({
+ tone: "error",
+ title: "Couldn't create a copy",
+ body: error instanceof Error ? error.message : "The fork request failed.",
+ });
+ },
+ });
+
+ const busy = forkMutation.isPending;
+ const forkLabel =
+ reassign && agentCount > 0
+ ? `Create copy & switch ${agentCount} ${agentCount === 1 ? "agent" : "agents"}`
+ : "Create copy";
+
+ const openExisting = () => {
+ if (!reusableFork) return;
+ onOpenChange(false);
+ navigate(skillStudioRoute(reusableFork.id));
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={(next) => (busy ? undefined : onOpenChange(next))}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <GitFork className="h-4 w-4" />
+ Edit a copy of {skill.name}
+ </DialogTitle>
+ <DialogDescription>
+ {skill.name} is read-only because it comes from an external source.
+ Creating a fully editable copy in your workspace leaves the original
+ untouched and still updatable.
+ </DialogDescription>
+ </DialogHeader>
+
+ {reusableFork ? (
+ <div className="rounded-md border border-primary/40 bg-primary/5 p-3 text-sm">
+ <p className="font-medium text-foreground">You already have a copy</p>
+ <p className="mt-0.5 text-muted-foreground">
+ An unedited copy of this skill already exists. Open it instead of
+ making another.
+ </p>
+ <Button
+ type="button"
+ size="sm"
+ className="mt-2"
+ onClick={openExisting}
+ disabled={busy}
+ >
+ Open your existing copy
+ </Button>
+ </div>
+ ) : null}
+
+ {/* P3 — unmissable agent-switch block (plan §3.2), not fine print. */}
+ <div
+ className={cn(
+ "rounded-md border p-3",
+ agentCount > 0 ? "border-amber-500/40 bg-amber-500/5" : "border-border bg-muted/30",
+ )}
+ >
+ <div className="flex items-center gap-2 text-sm font-medium text-foreground">
+ <Users className="h-4 w-4 shrink-0" />
+ <span>{agentUsageSentence(agentCount)}</span>
+ </div>
+
+ {agentCount > 0 ? (
+ <>
+ <div className="mt-2 flex flex-wrap gap-1.5">
+ {usedByAgents.map((agent) => (
+ <span
+ key={agent.id}
+ className="inline-flex items-center rounded-full border border-border bg-background px-2 py-0.5 text-xs text-foreground"
+ >
+ {agent.name}
+ </span>
+ ))}
+ </div>
+ <label className="mt-3 flex items-start justify-between gap-3">
+ <span className="text-sm">
+ <span className="font-medium text-foreground">
+ Switch these agents to the copy
+ </span>
+ <span className="mt-0.5 block text-xs text-muted-foreground">
+ {reassign
+ ? "These agents will run your copy instead of the original."
+ : "These agents keep running the original — your copy won't change what they do."}
+ </span>
+ </span>
+ <ToggleSwitch
+ checked={reassign}
+ onCheckedChange={setReassign}
+ disabled={busy}
+ aria-label="Switch these agents to the copy"
+ />
+ </label>
+ </>
+ ) : (
+ <p className="mt-1 text-xs text-muted-foreground">
+ Nothing is assigned to it, so your copy won't change any agent's
+ behaviour.
+ </p>
+ )}
+ </div>
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => onOpenChange(false)}
+ disabled={busy}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ variant={reusableFork ? "outline" : "default"}
+ onClick={() => forkMutation.mutate()}
+ disabled={busy}
+ >
+ {busy ? <Loader2 className="mr-1.5 h-4 w-4 animate-spin" /> : null}
+ {reusableFork ? "Create another copy" : forkLabel}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/ui/src/components/skill-studio/SkillProvenance.tsx b/ui/src/components/skill-studio/SkillProvenance.tsx
new file mode 100644
index 0000000000..5d4f1dbb01
--- /dev/null
+++ b/ui/src/components/skill-studio/SkillProvenance.tsx
@@ -0,0 +1,85 @@
+import { useQuery } from "@tanstack/react-query";
+import { FolderGit2, GitFork } from "lucide-react";
+import type { CompanySkillDetail } from "@paperclipai/shared";
+import { Link } from "@/lib/router";
+import { companySkillsApi } from "@/api/companySkills";
+import { queryKeys } from "@/lib/queryKeys";
+import { skillStudioRoute } from "@/lib/company-skill-routes";
+import { formatLineageLabel } from "@/lib/skill-fork";
+import { Button } from "@/components/ui/button";
+
+/**
+ * Lineage chip for forked skills (PAP-13112, plan §3.1): "Forked from
+ * `owner/repo` @ `<short-sha>`" linking back to the original. The fork row only
+ * carries `forkedFromSkillId`, so the original's source locator/ref are fetched
+ * on demand; if the original is gone we still link by id with a soft label.
+ */
+export function SkillLineageChip({
+ companyId,
+ forkedFromSkillId,
+}: {
+ companyId: string;
+ forkedFromSkillId: string | null;
+}) {
+ const originalQuery = useQuery({
+ queryKey: queryKeys.companySkills.detail(companyId, forkedFromSkillId ?? ""),
+ queryFn: () => companySkillsApi.detail(companyId, forkedFromSkillId!),
+ enabled: Boolean(companyId && forkedFromSkillId),
+ staleTime: 60_000,
+ });
+
+ if (!forkedFromSkillId) return null;
+
+ const original = originalQuery.data;
+ const label = original ? formatLineageLabel(original) : "the original skill";
+
+ return (
+ <Link
+ to={skillStudioRoute(forkedFromSkillId)}
+ className="inline-flex max-w-full items-center gap-1.5 rounded-full border border-border bg-muted px-2.5 py-0.5 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ title={`Forked from ${label}`}
+ >
+ <GitFork className="h-3 w-3 shrink-0" />
+ <span className="truncate">
+ Forked from <span className="font-medium text-foreground">{label}</span>
+ </span>
+ </Link>
+ );
+}
+
+/**
+ * Persistent source notice for repo-synced (`project_scan`) skills (PAP-13112,
+ * plan §3.3). These stay editable, but their saves land as uncommitted writes
+ * in the user's project checkout — disclosed here, with a secondary path to
+ * fork instead of touching the tree. No behaviour change (§3.3, Dotta 07-08).
+ */
+export function ProjectScanNotice({
+ skill,
+ onEditACopy,
+}: {
+ skill: CompanySkillDetail;
+ onEditACopy: () => void;
+}) {
+ const location = skill.sourcePath ?? skill.sourceLabel ?? "the project working tree";
+
+ return (
+ <div className="flex flex-wrap items-start gap-2 border-b border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
+ <FolderGit2 className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <span>
+ This skill lives in <span className="font-mono text-foreground">{location}</span>.
+ Saves write to the project working tree and are not committed.
+ </span>{" "}
+ <Button
+ type="button"
+ variant="link"
+ size="sm"
+ className="h-auto p-0 text-xs"
+ onClick={onEditACopy}
+ >
+ Edit a copy instead
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/ui/src/components/ui/resizable-panels.tsx b/ui/src/components/ui/resizable-panels.tsx
new file mode 100644
index 0000000000..dac8d716f2
--- /dev/null
+++ b/ui/src/components/ui/resizable-panels.tsx
@@ -0,0 +1,61 @@
+import { Group, Panel, Separator } from "react-resizable-panels";
+import type { GroupProps, PanelProps, SeparatorProps } from "react-resizable-panels";
+import { cn } from "@/lib/utils";
+
+/**
+ * Thin design-system wrapper over `react-resizable-panels` (PAP-12962 D2 — the
+ * only net-new shared primitive Skill Studio adds). Re-exports the library's
+ * Group / Panel / Separator with Paperclip token styling and a comfortable
+ * (≥8px) resize hit-slop so a split view can be dropped in anywhere.
+ *
+ * Sizes accept the library's units: bare numbers/`"37.5%"` are percentages,
+ * `"280px"` is a pixel floor (used here for the min-width contract).
+ */
+
+export function ResizablePanelGroup({ className, ...props }: GroupProps) {
+ return (
+ <Group
+ className={cn("flex h-full w-full data-[orientation=vertical]:flex-col", className)}
+ // Keep hit targets generous on both coarse (touch) and fine (mouse) input.
+ resizeTargetMinimumSize={{ coarse: 24, fine: 12 }}
+ {...props}
+ />
+ );
+}
+ResizablePanelGroup.displayName = "ResizablePanelGroup";
+
+export function ResizablePanel({ className, ...props }: PanelProps) {
+ return <Panel className={cn("h-full min-h-0 overflow-hidden", className)} {...props} />;
+}
+ResizablePanel.displayName = "ResizablePanel";
+
+/**
+ * A 1px visible divider centred inside a wider transparent hit target
+ * (Fitts's Law). Resize is instantaneous — the only transition is the hover
+ * colour, which is harmless under `prefers-reduced-motion`.
+ */
+export function ResizableHandle({ className, orientation = "horizontal", ...props }: SeparatorProps & {
+ orientation?: "horizontal" | "vertical";
+}) {
+ const vertical = orientation === "vertical";
+ return (
+ <Separator
+ className={cn(
+ "group relative flex items-center justify-center bg-transparent outline-none",
+ "focus-visible:ring-1 focus-visible:ring-ring",
+ vertical ? "h-2 w-full cursor-row-resize" : "w-2 h-full cursor-col-resize",
+ className,
+ )}
+ {...props}
+ >
+ <span
+ aria-hidden
+ className={cn(
+ "bg-border transition-colors group-hover:bg-ring group-data-[dragging]:bg-ring",
+ vertical ? "h-px w-full" : "w-px h-full",
+ )}
+ />
+ </Separator>
+ );
+}
+ResizableHandle.displayName = "ResizableHandle";
diff --git a/ui/src/index.css b/ui/src/index.css
index 78631c1643..950418dd74 100644
--- a/ui/src/index.css
+++ b/ui/src/index.css
@@ -1470,8 +1470,7 @@ span.paperclip-mention-chip[data-mention-kind="external-object"] {
--hex-eab308: #eab308; /* ActivityCharts.tsx — priority 'medium'; also the 0.5-0.8 success-rate bar tint. */
--hex-6b7280: #6b7280; /* ActivityCharts.tsx — priority 'low' + unknown-status statusColors fallback. */
--hex-10b981: #10b981; /* ActivityCharts.tsx — >=0.8 success-rate bar tint; also the run-activity 'succeeded' segment. */
- --hex-f59e0b: #f59e0b; /* ActivityCharts.tsx — run-activity 'recovered' segment (independent run-outcome series; same value as --status-task-todo by coincidence, decoupled on purpose). */
- --hex-737373: #737373; /* ActivityCharts.tsx — run-activity 'other' segment (neutral). */
+ --hex-737373: #737373; /* ActivityCharts.tsx — run activity "other" segment tint. */
--project-none: #64748b; /* Semantic rename of --hex-64748b (DECISION-SHEET.md A3, value unchanged). 'No project assigned' muted-slate fallback (TOKEN-AUDIT.md 1.3) across Routines/MarkdownEditor/RoutineRunVariablesDialog/RoutineList/IssueColumns/editable-sections; also ActivityCharts.tsx status 'backlog'. */
--project-seed: #6366f1; /* Semantic rename of --hex-6366f1 (DECISION-SHEET.md A3, value unchanged). Project-color-fallback indigo seed default (ProjectDetail/PipelineSettings/IssueProperties/NewIssueDialog) — new-project-color-picker-seed family per TOKEN-AUDIT.md 1.3. */
--liveness-blue: #2563eb; /* DECISION-SHEET.md A6: IssueChatThread.tsx human-message 'liveness blue' bubble (PAP-95 rev 5). Same value as --status-task-in_progress by coincidence, decoupled on purpose so a future status-hue change doesn't drag the chat bubble along. */
@@ -1648,6 +1647,7 @@ span.paperclip-mention-chip[data-mention-kind="external-object"] {
--sz-calc-31: calc(100vh - 16rem); /* Extracted from ui/src/pages/CompanyImport.tsx (h-[calc(100vh-16rem)]). */
--sz-calc-32: min(28rem,70vh); /* Extracted from ui/src/pages/CompanySkills.tsx (max-h-[min(28rem,70vh)]). */
--sz-11_5rem: 11.5rem; /* Extracted from ui/src/pages/CompanySkills.tsx (min-h-[11.5rem]). */
+ --sz-11_75rem: 11.75rem; /* SkillStudio.tsx file/input browser cap: five min-h-9 rows plus p-1 vertical padding. */
--sz-calc-33: calc(100dvh - 6rem); /* Extracted from ui/src/pages/CompanySkills.tsx (h-[calc(100dvh-6rem)]). */
--sz-calc-34: clamp(14rem,45vh,28rem); /* Extracted from ui/src/pages/CompanySkills.tsx (h-[clamp(14rem,45vh,28rem)]). */
--sz-400px: 400px; /* Extracted from ui/src/pages/CompanySkills.tsx (min-h-[400px]). */
diff --git a/ui/src/lib/agent-skills-state.test.ts b/ui/src/lib/agent-skills-state.test.ts
index c3f3257990..ffa8e04218 100644
--- a/ui/src/lib/agent-skills-state.test.ts
+++ b/ui/src/lib/agent-skills-state.test.ts
@@ -1,5 +1,76 @@
import { describe, expect, it } from "vitest";
-import { applyAgentSkillSnapshot, isReadOnlyUnmanagedSkillEntry } from "./agent-skills-state";
+import {
+ applyAgentSkillSnapshot,
+ isReadOnlyUnmanagedSkillEntry,
+ sameSkillSelection,
+ shouldScheduleSkillAutosave,
+} from "./agent-skills-state";
+
+describe("sameSkillSelection", () => {
+ it("treats selections as order-independent sets", () => {
+ expect(sameSkillSelection(["a", "b", "c"], ["c", "a", "b"])).toBe(true);
+ });
+
+ it("detects added or removed keys", () => {
+ expect(sameSkillSelection(["a", "b"], ["a"])).toBe(false);
+ expect(sameSkillSelection(["a"], ["a", "b"])).toBe(false);
+ });
+});
+
+describe("shouldScheduleSkillAutosave", () => {
+ it("does not re-save when the server returns the same set in a different order", () => {
+ // Server preserves stale keys but groups them at the end; the draft keeps the
+ // user's order. Same set → already saved, no re-fire (would loop otherwise).
+ expect(
+ shouldScheduleSkillAutosave({
+ draft: ["paperclip", "stale/removed/skill", "ascii-art"],
+ lastSaved: ["paperclip", "ascii-art", "stale/removed/skill"],
+ failedDraft: null,
+ }),
+ ).toBe(false);
+ });
+
+ it("does not save when the draft already matches what was saved", () => {
+ expect(
+ shouldScheduleSkillAutosave({
+ draft: ["paperclip"],
+ lastSaved: ["paperclip"],
+ failedDraft: null,
+ }),
+ ).toBe(false);
+ });
+
+ it("saves when the draft diverges from the last saved state", () => {
+ expect(
+ shouldScheduleSkillAutosave({
+ draft: ["paperclip", "ascii-art"],
+ lastSaved: ["paperclip"],
+ failedDraft: null,
+ }),
+ ).toBe(true);
+ });
+
+ it("holds a payload that just failed to prevent a retry storm (PAP-13222)", () => {
+ const draft = ["paperclip", "stale/removed/skill"];
+ expect(
+ shouldScheduleSkillAutosave({
+ draft,
+ lastSaved: ["paperclip"],
+ failedDraft: [...draft],
+ }),
+ ).toBe(false);
+ });
+
+ it("resumes saving once the user edits the draft after a failure", () => {
+ expect(
+ shouldScheduleSkillAutosave({
+ draft: ["paperclip", "ascii-art"],
+ lastSaved: ["paperclip"],
+ failedDraft: ["paperclip", "stale/removed/skill"],
+ }),
+ ).toBe(true);
+ });
+});
describe("applyAgentSkillSnapshot", () => {
it("hydrates the initial snapshot without arming autosave", () => {
diff --git a/ui/src/lib/agent-skills-state.ts b/ui/src/lib/agent-skills-state.ts
index d5a697a651..e39a43aeab 100644
--- a/ui/src/lib/agent-skills-state.ts
+++ b/ui/src/lib/agent-skills-state.ts
@@ -16,6 +16,24 @@ export function arraysEqual(a: string[], b: string[]): boolean {
return a.every((value, index) => value === b[index]);
}
+/**
+ * Order-independent equality for a desired-skill selection. A skill selection is
+ * conceptually a set, and the server may return keys in a different order than
+ * the client sent them (it canonicalizes references and re-groups stale keys).
+ * Comparing as sets keeps "is this saved?" honest across those reorderings —
+ * without it, a persisted-but-reordered response reads as "still dirty" and the
+ * autosave re-fires forever (a benign-looking sibling of the PAP-13222 storm).
+ */
+export function sameSkillSelection(a: string[], b: string[]): boolean {
+ const setA = new Set(a);
+ const setB = new Set(b);
+ if (setA.size !== setB.size) return false;
+ for (const key of setA) {
+ if (!setB.has(key)) return false;
+ }
+ return true;
+}
+
export function applyAgentSkillSnapshot(
state: AgentSkillDraftState,
desiredSkills: string[],
@@ -30,6 +48,23 @@ export function applyAgentSkillSnapshot(
};
}
+/**
+ * Decide whether the autosave effect should (re)schedule a sync for the current
+ * draft. Returns false when the draft is already saved, or when it exactly
+ * matches a payload that just failed — the latter is what prevents the infinite
+ * 422 retry storm (PAP-13222). A failed payload only becomes sendable again once
+ * the user edits the draft into something new.
+ */
+export function shouldScheduleSkillAutosave(params: {
+ draft: string[];
+ lastSaved: string[];
+ failedDraft: string[] | null;
+}): boolean {
+ if (sameSkillSelection(params.draft, params.lastSaved)) return false;
+ if (params.failedDraft && sameSkillSelection(params.draft, params.failedDraft)) return false;
+ return true;
+}
+
export function isReadOnlyUnmanagedSkillEntry(
entry: AgentSkillEntry,
companySkillKeys: Set<string>,
diff --git a/ui/src/lib/company-routes.test.ts b/ui/src/lib/company-routes.test.ts
index 9a86268ab6..5b6f5e4a37 100644
--- a/ui/src/lib/company-routes.test.ts
+++ b/ui/src/lib/company-routes.test.ts
@@ -79,6 +79,17 @@ describe("company routes", () => {
expect(toCompanyRelativePath("/PAP/timeline")).toBe("/timeline");
});
+ it("treats Skill Studio create mode as an unprefixed board route", () => {
+ expect(isBoardPathWithoutPrefix("/skills/studio/new")).toBe(true);
+ expect(extractCompanyPrefixFromPath("/skills/studio/new")).toBeNull();
+ expect(applyCompanyPrefix("/skills/studio/new?forkFrom=skill-1", "PAP")).toBe(
+ "/PAP/skills/studio/new?forkFrom=skill-1",
+ );
+ expect(toCompanyRelativePath("/PAP/skills/studio/new?forkFrom=skill-1")).toBe(
+ "/skills/studio/new?forkFrom=skill-1",
+ );
+ });
+
it("preserves artifact deep-link anchors when applying the company prefix", () => {
expect(applyCompanyPrefix("/issues/PAP-10205#work-product-wp-1", "PAP")).toBe(
"/PAP/issues/PAP-10205#work-product-wp-1",
diff --git a/ui/src/lib/company-skill-routes.test.ts b/ui/src/lib/company-skill-routes.test.ts
index 2065bd57eb..4eb3fb5dbc 100644
--- a/ui/src/lib/company-skill-routes.test.ts
+++ b/ui/src/lib/company-skill-routes.test.ts
@@ -4,6 +4,7 @@ import {
parseSkillRoute,
resolveSkillRouteToken,
skillRoute,
+ skillStudioNewRoute,
type CompanySkillRouteSubject,
} from "./company-skill-routes";
@@ -77,4 +78,11 @@ describe("company skill routes", () => {
});
expect(parseSkillRoute(undefined)).toEqual({ skillToken: null, filePath: "SKILL.md", hasExplicitFilePath: false });
});
+
+ it("builds Studio create targets for blank and forked skills", () => {
+ expect(skillStudioNewRoute()).toBe("/skills/studio/new");
+ expect(skillStudioNewRoute("skill/with spaces")).toBe(
+ "/skills/studio/new?forkFrom=skill%2Fwith%20spaces",
+ );
+ });
});
diff --git a/ui/src/lib/company-skill-routes.ts b/ui/src/lib/company-skill-routes.ts
index b9a42fb964..66ab5b3515 100644
--- a/ui/src/lib/company-skill-routes.ts
+++ b/ui/src/lib/company-skill-routes.ts
@@ -187,6 +187,15 @@ export function skillRoute(
return effectiveFilePath ? `${basePath}/files/${encodeSkillFilePath(effectiveFilePath)}` : basePath;
}
+export function skillStudioRoute(skillId: string) {
+ return `/skills/studio/${encodeURIComponent(skillId)}`;
+}
+
+export function skillStudioNewRoute(forkFromSkillId?: string | null) {
+ const basePath = "/skills/studio/new";
+ return forkFromSkillId ? `${basePath}?forkFrom=${encodeURIComponent(forkFromSkillId)}` : basePath;
+}
+
export function withRouteSkill(
skills: CompanySkillRouteSubject[],
skill: CompanySkillRouteSubject,
diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts
index c53aee2417..7e228137a7 100644
--- a/ui/src/lib/queryKeys.ts
+++ b/ui/src/lib/queryKeys.ts
@@ -6,11 +6,15 @@ export const queryKeys = {
},
companySkills: {
list: (companyId: string) => ["company-skills", companyId] as const,
+ listRecent: (companyId: string) =>
+ ["company-skills", companyId, "recent-updated"] 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,
+ forkPrecheck: (companyId: string, skillId: string) =>
+ ["company-skills", companyId, skillId, "fork-precheck"] as const,
file: (companyId: string, skillId: string, relativePath: string) =>
["company-skills", companyId, skillId, "file", relativePath] as const,
catalog: (filters: { kind?: string; category?: string; q?: string } = {}) =>
@@ -18,6 +22,14 @@ export const queryKeys = {
catalogDetail: (catalogRef: string) => ["company-skills", "catalog", "detail", catalogRef] as const,
catalogFile: (catalogRef: string, relativePath: string) =>
["company-skills", "catalog", "file", catalogRef, relativePath] as const,
+ testInputs: (companyId: string, skillId: string) =>
+ ["company-skills", companyId, skillId, "test-inputs"] as const,
+ testRunTemplates: (companyId: string) =>
+ ["company-skills", companyId, "test-run-templates"] as const,
+ testRuns: (companyId: string, skillId: string, inputId?: string | null) =>
+ ["company-skills", companyId, skillId, "test-runs", inputId ?? "__all-inputs__"] as const,
+ testRunDetail: (companyId: string, skillId: string, runId: string) =>
+ ["company-skills", companyId, skillId, "test-run", runId] as const,
},
teamCatalog: {
catalog: (filters: { kind?: string; category?: string; q?: string } = {}) =>
diff --git a/ui/src/lib/recent-skills.ts b/ui/src/lib/recent-skills.ts
new file mode 100644
index 0000000000..b44527b82e
--- /dev/null
+++ b/ui/src/lib/recent-skills.ts
@@ -0,0 +1,17 @@
+import {
+ readRecentSelectionIds,
+ trackRecentSelectionId,
+} from "./recent-selections";
+
+// Per-browser record of skills recently opened in Skill Studio, powering the
+// "Recently visited" section of the Studio landing (PAP-13150). Same
+// localStorage-list pattern as recent-projects.ts / recent-assignees.ts.
+const STORAGE_KEY = "paperclip:recent-studio-skills";
+
+export function getRecentStudioSkillIds(): string[] {
+ return readRecentSelectionIds(STORAGE_KEY);
+}
+
+export function trackRecentStudioSkill(skillId: string): void {
+ trackRecentSelectionId(STORAGE_KEY, skillId);
+}
diff --git a/ui/src/lib/skill-create.test.ts b/ui/src/lib/skill-create.test.ts
new file mode 100644
index 0000000000..0e9e3351ba
--- /dev/null
+++ b/ui/src/lib/skill-create.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from "vitest";
+import type { CompanySkillDetail } from "@paperclipai/shared";
+import {
+ buildBlankSkillDraft,
+ buildForkSkillDraft,
+ defaultSkillMarkdown,
+ normalizeSkillDraftSlug,
+ skillCreateDraftToPayload,
+ splitCategoryDraft,
+} from "./skill-create";
+
+function skill(overrides: Partial<CompanySkillDetail> = {}): CompanySkillDetail {
+ return {
+ id: "skill-1",
+ companyId: "company-1",
+ key: "paperclip/demo-skill",
+ slug: "demo-skill",
+ name: "Demo Skill",
+ description: "A demo skill.",
+ markdown: "---\nname: Demo Skill\ndescription: Existing\n---\n\n# Demo Skill\n",
+ sourceType: "local_path",
+ sourceLocator: null,
+ sourceRef: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ iconUrl: null,
+ color: null,
+ tagline: "Existing tagline",
+ authorName: null,
+ homepageUrl: null,
+ categories: ["engineering", "review"],
+ sharingScope: "company",
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 0,
+ installCount: 0,
+ forkCount: 0,
+ currentVersionId: null,
+ 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: null,
+ starredByCurrentActor: false,
+ existingForks: [],
+ ...overrides,
+ };
+}
+
+describe("skill create helpers", () => {
+ it("normalizes slugs and category drafts", () => {
+ expect(normalizeSkillDraftSlug(" My Fancy_SKILL!! ")).toBe("my-fancy-skill");
+ expect(splitCategoryDraft(" Review, memory tools, review, , Agent_QA ")).toEqual([
+ "Review",
+ "memory tools",
+ "Agent_QA",
+ ]);
+ });
+
+ it("keeps commas as draft delimiters while allowing spaces inside category names", () => {
+ expect(splitCategoryDraft(" AI Tools, Developer Experience, ai tools, ")).toEqual([
+ "AI Tools",
+ "Developer Experience",
+ ]);
+ });
+
+ it("builds blank drafts with default SKILL.md frontmatter", () => {
+ const draft = buildBlankSkillDraft();
+
+ expect(draft.name).toBe("");
+ expect(draft.slug).toBe("");
+ expect(draft.sharingScope).toBe("company");
+ expect(draft.markdown).toContain("name: New Skill");
+ expect(draft.markdown).toContain("Describe when agents should use this skill.");
+ });
+
+ it("builds fork drafts from the source skill metadata", () => {
+ const draft = buildForkSkillDraft(skill({ color: "#123456" }));
+
+ expect(draft.name).toBe("Demo Skill Fork");
+ expect(draft.slug).toBe("demo-skill-fork");
+ expect(draft.color).toBe("#123456");
+ expect(draft.categories).toEqual(["engineering", "review"]);
+ expect(draft.forkedFromSkillId).toBe("skill-1");
+ expect(draft.forkedFromName).toBe("Demo Skill");
+ expect(draft.markdown).toContain("name: Demo Skill Fork");
+ });
+
+ it("converts drafts to create payloads with fallback slug and markdown", () => {
+ const draft = {
+ ...buildBlankSkillDraft(),
+ name: "Code Review",
+ tagline: "Review repository changes.",
+ markdown: "",
+ categories: ["review"],
+ sharingScope: "private" as const,
+ };
+
+ expect(skillCreateDraftToPayload(draft)).toMatchObject({
+ name: "Code Review",
+ slug: "code-review",
+ description: "Review repository changes.",
+ tagline: "Review repository changes.",
+ categories: ["review"],
+ sharingScope: "private",
+ forkedFromSkillId: null,
+ markdown: defaultSkillMarkdown("Code Review", "Review repository changes."),
+ });
+ });
+});
diff --git a/ui/src/lib/skill-create.ts b/ui/src/lib/skill-create.ts
new file mode 100644
index 0000000000..6087fbcabc
--- /dev/null
+++ b/ui/src/lib/skill-create.ts
@@ -0,0 +1,132 @@
+import type {
+ CompanySkillCreateRequest,
+ CompanySkillDetail,
+ CompanySkillSharingScope,
+} from "@paperclipai/shared";
+
+export const SKILL_CREATE_ACCENTS = [
+ "#6366f1", "#0ea5e9", "#10b981", "#f59e0b", "#ef4444",
+ "#8b5cf6", "#ec4899", "#14b8a6", "#f97316", "#22c55e",
+ "#3b82f6", "#a855f7",
+];
+
+export 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;
+};
+
+export function normalizeSkillDraftSlug(value: string) {
+ return value
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 80);
+}
+
+export function splitCategoryDraft(value: string) {
+ const seen = new Set<string>();
+ const categories: string[] = [];
+ for (const entry of value.split(",")) {
+ const category = entry.trim().replace(/\s+/g, " ");
+ if (!category) continue;
+ const key = category.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ categories.push(category);
+ }
+ return categories;
+}
+
+export 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");
+}
+
+export 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 SKILL_CREATE_ACCENTS[hash % SKILL_CREATE_ACCENTS.length]!;
+}
+
+export function buildBlankSkillDraft(): SkillCreateDraft {
+ return {
+ name: "",
+ slug: "",
+ tagline: "",
+ description: "",
+ color: SKILL_CREATE_ACCENTS[0]!,
+ categories: [],
+ markdown: defaultSkillMarkdown("", ""),
+ sharingScope: "company",
+ forkedFromSkillId: null,
+ forkedFromName: null,
+ };
+}
+
+export 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,
+ };
+}
+
+export function skillCreateDraftToPayload(draft: SkillCreateDraft): CompanySkillCreateRequest {
+ const effectiveSlug = draft.slug.trim() || normalizeSkillDraftSlug(draft.name);
+ const effectiveMarkdown = draft.markdown.trim().length > 0
+ ? draft.markdown
+ : defaultSkillMarkdown(draft.name, draft.tagline);
+
+ return {
+ 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,
+ };
+}
diff --git a/ui/src/lib/skill-fork.test.ts b/ui/src/lib/skill-fork.test.ts
new file mode 100644
index 0000000000..19bf48b5a4
--- /dev/null
+++ b/ui/src/lib/skill-fork.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, it } from "vitest";
+import type {
+ CompanySkillForkSummary,
+ CompanySkillOriginalSummary,
+ CompanySkillUsageAgent,
+} from "@paperclipai/shared";
+import {
+ agentUsageSentence,
+ formatForkSourceName,
+ formatLineageLabel,
+ isProjectScanSkill,
+ pickReusableFork,
+ reassignTargetIds,
+ shortSha,
+} from "./skill-fork";
+
+function original(
+ over: Partial<CompanySkillOriginalSummary> = {},
+): CompanySkillOriginalSummary {
+ return {
+ id: "orig-1",
+ name: "Deep Research",
+ slug: "deep-research",
+ sourceType: "github",
+ sourceLocator: "https://github.com/anthropics/skills",
+ sourceRef: "0123456789abcdef0123456789abcdef01234567",
+ ...over,
+ };
+}
+
+function fork(over: Partial<CompanySkillForkSummary> = {}): CompanySkillForkSummary {
+ return {
+ ...original(),
+ id: "fork-1",
+ key: "deep-research-fork",
+ forkedFromSkillId: "orig-1",
+ forkedFromCompanyId: "co-1",
+ currentVersionId: "v1",
+ createdByCurrentActor: true,
+ diverged: false,
+ createdAt: new Date("2026-07-09T00:00:00Z"),
+ updatedAt: new Date("2026-07-09T00:00:00Z"),
+ ...over,
+ };
+}
+
+describe("shortSha", () => {
+ it("shortens a full hex sha to 7 chars", () => {
+ expect(shortSha("0123456789abcdef0123456789abcdef01234567")).toBe("0123456");
+ });
+ it("leaves branch/tag names intact", () => {
+ expect(shortSha("main")).toBe("main");
+ expect(shortSha("v1.2.0")).toBe("v1.2.0");
+ });
+ it("returns null for empty/nullish refs", () => {
+ expect(shortSha(null)).toBeNull();
+ expect(shortSha("")).toBeNull();
+ expect(shortSha(" ")).toBeNull();
+ });
+});
+
+describe("formatForkSourceName", () => {
+ it("extracts owner/repo from a github url", () => {
+ expect(
+ formatForkSourceName({ sourceType: "github", sourceLocator: "https://github.com/anthropics/skills" }),
+ ).toBe("anthropics/skills");
+ });
+ it("extracts owner/repo from github shorthand with subpath and ref", () => {
+ expect(
+ formatForkSourceName({ sourceType: "github", sourceLocator: "anthropics/skills/some/path#main" }),
+ ).toBe("anthropics/skills");
+ });
+ it("strips .git and ssh scheme", () => {
+ expect(
+ formatForkSourceName({ sourceType: "github", sourceLocator: "[email protected]:anthropics/skills.git" }),
+ ).toBe("anthropics/skills");
+ });
+ it("cleans a url source", () => {
+ expect(
+ formatForkSourceName({ sourceType: "url", sourceLocator: "https://example.com/skill/" }),
+ ).toBe("example.com/skill");
+ });
+ it("falls back to a source-type label when no locator", () => {
+ expect(formatForkSourceName({ sourceType: "skills_sh", sourceLocator: null })).toBe("skills.sh");
+ expect(formatForkSourceName({ sourceType: "catalog", sourceLocator: null })).toBe("the catalog");
+ });
+});
+
+describe("formatLineageLabel", () => {
+ it("includes short sha when a hex ref is pinned", () => {
+ expect(formatLineageLabel(original())).toBe("anthropics/skills @ 0123456");
+ });
+ it("omits the sha clause when no ref is present", () => {
+ expect(formatLineageLabel(original({ sourceRef: null }))).toBe("anthropics/skills");
+ });
+});
+
+describe("pickReusableFork", () => {
+ it("returns an un-diverged fork by the current actor", () => {
+ const reusable = fork({ id: "reuse-me" });
+ expect(pickReusableFork([reusable])?.id).toBe("reuse-me");
+ });
+ it("ignores diverged forks", () => {
+ expect(pickReusableFork([fork({ diverged: true })])).toBeNull();
+ });
+ it("ignores forks created by other actors", () => {
+ expect(pickReusableFork([fork({ createdByCurrentActor: false })])).toBeNull();
+ });
+ it("returns null with no forks", () => {
+ expect(pickReusableFork([])).toBeNull();
+ });
+});
+
+describe("agentUsageSentence", () => {
+ it("handles zero", () => {
+ expect(agentUsageSentence(0)).toBe("No agents currently use this skill");
+ });
+ it("uses singular verb agreement for one agent", () => {
+ expect(agentUsageSentence(1)).toBe("1 agent currently uses this skill");
+ });
+ it("uses plural for many", () => {
+ expect(agentUsageSentence(3)).toBe("3 agents currently use this skill");
+ });
+});
+
+describe("reassignTargetIds", () => {
+ it("maps usage agents to their ids", () => {
+ const agents: CompanySkillUsageAgent[] = [
+ { id: "a1", name: "One", urlKey: "one", adapterType: "claude", desired: true, actualState: null, versionId: null },
+ { id: "a2", name: "Two", urlKey: "two", adapterType: "codex", desired: true, actualState: null, versionId: null },
+ ];
+ expect(reassignTargetIds(agents)).toEqual(["a1", "a2"]);
+ });
+});
+
+describe("isProjectScanSkill", () => {
+ it("detects project_scan metadata", () => {
+ expect(isProjectScanSkill({ sourceKind: "project_scan" })).toBe(true);
+ });
+ it("ignores other source kinds / missing metadata", () => {
+ expect(isProjectScanSkill({ sourceKind: "managed_local" })).toBe(false);
+ expect(isProjectScanSkill(null)).toBe(false);
+ expect(isProjectScanSkill(undefined)).toBe(false);
+ expect(isProjectScanSkill({})).toBe(false);
+ });
+});
diff --git a/ui/src/lib/skill-fork.ts b/ui/src/lib/skill-fork.ts
new file mode 100644
index 0000000000..4f2adb214b
--- /dev/null
+++ b/ui/src/lib/skill-fork.ts
@@ -0,0 +1,119 @@
+import type {
+ CompanySkillForkSummary,
+ CompanySkillOriginalSummary,
+ CompanySkillSourceType,
+ CompanySkillUsageAgent,
+} from "@paperclipai/shared";
+
+/**
+ * Pure logic for the Skill Studio "Edit a copy" fork flow (PAP-13112). Kept
+ * free of React so the dialog's decision logic — lineage labelling, existing-
+ * copy detection, agent-reassignment targeting — is unit-testable in isolation
+ * (plan §3 / §4.2 of PAP-13070).
+ */
+
+/**
+ * Shorten a git commit SHA to 7 characters for display. Branch/tag names and
+ * anything that is not a hex object id are returned unchanged so a pinned
+ * `main`/`v1.2.0` ref still reads sensibly in the lineage chip.
+ */
+export function shortSha(ref: string | null | undefined): string | null {
+ if (!ref) return null;
+ const trimmed = ref.trim();
+ if (!trimmed) return null;
+ return /^[0-9a-f]{8,40}$/i.test(trimmed) ? trimmed.slice(0, 7) : trimmed;
+}
+
+function sourceTypeFallbackLabel(sourceType: CompanySkillSourceType): string {
+ switch (sourceType) {
+ case "github":
+ return "GitHub";
+ case "skills_sh":
+ return "skills.sh";
+ case "url":
+ return "a URL";
+ case "catalog":
+ return "the catalog";
+ case "local_path":
+ return "a local path";
+ default:
+ return "its source";
+ }
+}
+
+/** Extract `owner/repo` from a GitHub URL or `owner/repo[/subpath][#ref]` shorthand. */
+function githubOwnerRepo(locator: string): string | null {
+ let value = locator
+ .replace(/^git@github\.com:/i, "")
+ .replace(/^https?:\/\/github\.com\//i, "");
+ value = value.split("#")[0].split("?")[0].replace(/\.git$/i, "");
+ const segments = value.split("/").filter(Boolean);
+ return segments.length >= 2 ? `${segments[0]}/${segments[1]}` : null;
+}
+
+function prettyUrl(locator: string): string {
+ return locator.replace(/^https?:\/\//i, "").replace(/\/+$/, "");
+}
+
+/**
+ * Human-readable source name for a fork's origin — `owner/repo` for GitHub,
+ * a cleaned host/path for URLs, otherwise the raw locator or a source-type
+ * fallback when no locator is recorded.
+ */
+export function formatForkSourceName(source: {
+ sourceType: CompanySkillSourceType;
+ sourceLocator: string | null;
+}): string {
+ const locator = source.sourceLocator?.trim() ?? "";
+ if (!locator) return sourceTypeFallbackLabel(source.sourceType);
+ if (source.sourceType === "github") return githubOwnerRepo(locator) ?? locator;
+ if (source.sourceType === "url") return prettyUrl(locator);
+ return locator;
+}
+
+/**
+ * The lineage chip label: `owner/repo @ <short-sha>` (the `@ sha` clause is
+ * dropped when the source has no pinned ref, e.g. skills.sh / URL sources).
+ */
+export function formatLineageLabel(original: CompanySkillOriginalSummary): string {
+ const name = formatForkSourceName(original);
+ const sha = shortSha(original.sourceRef);
+ return sha ? `${name} @ ${sha}` : name;
+}
+
+/**
+ * Fork-sprawl guard (plan §5): the first existing fork of this skill that the
+ * current actor created and has not yet diverged, so the dialog can offer
+ * "Open your existing copy" instead of minting `-fork-2`, `-fork-3`, … .
+ */
+export function pickReusableFork(
+ existingForks: CompanySkillForkSummary[],
+): CompanySkillForkSummary | null {
+ return (
+ existingForks.find((fork) => fork.createdByCurrentActor && !fork.diverged) ?? null
+ );
+}
+
+/** Unmissable agent-usage sentence for the dialog body (P3 hard requirement). */
+export function agentUsageSentence(count: number): string {
+ if (count <= 0) return "No agents currently use this skill";
+ return `${count} ${count === 1 ? "agent" : "agents"} currently use${count === 1 ? "s" : ""} this skill`;
+}
+
+/** Agent ids to reassign when the "Switch these agents to the copy" toggle is on. */
+export function reassignTargetIds(usedByAgents: CompanySkillUsageAgent[]): string[] {
+ return usedByAgents.map((agent) => agent.id);
+}
+
+/**
+ * Whether a skill is repo-synced (`project_scan`) — editable, but its saves
+ * write directly into the user's project working tree (plan §3.3). Detected via
+ * the skill's `metadata.sourceKind`.
+ */
+export function isProjectScanSkill(
+ metadata: Record<string, unknown> | null | undefined,
+): boolean {
+ if (!metadata || typeof metadata !== "object") return false;
+ const raw = (metadata as Record<string, unknown>).sourceKind;
+ return typeof raw === "string" && raw.trim() === "project_scan";
+}
diff --git a/ui/src/lib/skill-studio.test.ts b/ui/src/lib/skill-studio.test.ts
new file mode 100644
index 0000000000..65bfd1037a
--- /dev/null
+++ b/ui/src/lib/skill-studio.test.ts
@@ -0,0 +1,779 @@
+import { describe, expect, it } from "vitest";
+import type {
+ CompanySkillLastEditor,
+ CompanySkillListItem,
+ CompanySkillTestRunStatus,
+ CompanySkillTestRunTemplate,
+ IssueAttachment,
+ IssueDocument,
+ IssueWorkProduct,
+} from "@paperclipai/shared";
+import {
+ buildReRunRequest,
+ buildCreateRunRequest,
+ DEFAULT_TEST_RUN_TEMPLATE_ID,
+ EMPTY_SAVED_INPUT_DRAFT_STATE,
+ evaluateRunGate,
+ findOutputDocument,
+ findRunOutputDocument,
+ getRunAdditionalDocuments,
+ getRunMediaGalleryItems,
+ getRunRawAttachments,
+ INLINE_INTERACTION_KINDS,
+ isAgentSelectable,
+ isInteractionAnswerable,
+ isRunActive,
+ isTerminalRunStatus,
+ orderRecentlyUpdatedSkills,
+ orderRecentlyVisitedSkills,
+ skillEditorAvatar,
+ routeInteraction,
+ runBadgeStatus,
+ runOutputMode,
+ runHarnessUnavailableCopy,
+ runShortId,
+ parseRunTemplateSelection,
+ resolveRunTemplateSelection,
+ savedInputDraftDirty,
+ selectedSavedInputDraft,
+ serializeRunTemplateSelection,
+ shouldPollRun,
+ showRunErrorCard,
+ syncSavedInputDraftState,
+ testTaskLinkState,
+} from "./skill-studio";
+
+const ALL_STATUSES: CompanySkillTestRunStatus[] = [
+ "queued",
+ "running",
+ "succeeded",
+ "failed",
+ "cancelled",
+];
+
+function makeRunDocument(overrides: Partial<IssueDocument> & { id: string; key: string }): IssueDocument {
+ const { id, key, ...documentOverrides } = overrides;
+ return {
+ id,
+ companyId: "company-1",
+ issueId: "issue-1",
+ key,
+ title: overrides.title ?? null,
+ format: "markdown",
+ latestRevisionId: "revision-1",
+ latestRevisionNumber: 1,
+ createdByAgentId: null,
+ createdByUserId: null,
+ updatedByAgentId: null,
+ updatedByUserId: null,
+ lockedAt: null,
+ lockedByAgentId: null,
+ lockedByUserId: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ updatedAt: new Date("2026-01-01T00:00:00Z"),
+ body: overrides.body ?? "",
+ ...documentOverrides,
+ };
+}
+
+function makeRunAttachment(overrides: Partial<IssueAttachment> & { id: string }): IssueAttachment {
+ const { id, ...attachmentOverrides } = overrides;
+ return {
+ id,
+ companyId: "company-1",
+ issueId: "issue-1",
+ issueCommentId: null,
+ assetId: `asset-${id}`,
+ provider: "local",
+ objectKey: `attachments/${id}`,
+ contentType: overrides.contentType ?? "text/plain",
+ byteSize: overrides.byteSize ?? 512,
+ sha256: "0".repeat(64),
+ originalFilename: overrides.originalFilename ?? `${id}.txt`,
+ createdByAgentId: null,
+ createdByUserId: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ updatedAt: new Date("2026-01-01T00:00:00Z"),
+ contentPath: overrides.contentPath ?? `/api/attachments/${id}/content`,
+ openPath: overrides.openPath ?? `/api/attachments/${id}/content`,
+ downloadPath: overrides.downloadPath ?? `/api/attachments/${id}/content?download=1`,
+ ...attachmentOverrides,
+ };
+}
+
+function makeArtifactWorkProduct(
+ overrides: Partial<IssueWorkProduct> & {
+ id: string;
+ attachmentId?: string;
+ contentPath?: string;
+ contentType?: string;
+ originalFilename?: string;
+ },
+): IssueWorkProduct {
+ const { id, attachmentId: overrideAttachmentId, contentPath: overrideContentPath, contentType, originalFilename, ...workProductOverrides } = overrides;
+ const attachmentId = overrideAttachmentId ?? `attachment-${id}`;
+ const contentPath = overrideContentPath ?? `/api/attachments/${attachmentId}/content`;
+ return {
+ id,
+ companyId: "company-1",
+ projectId: null,
+ issueId: "issue-1",
+ executionWorkspaceId: null,
+ runtimeServiceId: null,
+ type: "artifact",
+ provider: "paperclip",
+ externalId: null,
+ title: overrides.title ?? `Artifact ${id}`,
+ url: null,
+ status: "active",
+ reviewState: "none",
+ isPrimary: false,
+ healthStatus: "unknown",
+ summary: overrides.summary ?? null,
+ metadata: {
+ attachmentId,
+ contentType: contentType ?? "image/png",
+ byteSize: 1024,
+ contentPath,
+ openPath: contentPath,
+ downloadPath: `${contentPath}?download=1`,
+ originalFilename: originalFilename ?? `${id}.png`,
+ },
+ sourceTrust: null,
+ createdByRunId: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ updatedAt: new Date("2026-01-01T00:00:00Z"),
+ ...workProductOverrides,
+ };
+}
+
+describe("run-status derivation", () => {
+ it("classifies terminal vs non-terminal statuses", () => {
+ expect(isTerminalRunStatus("queued")).toBe(false);
+ expect(isTerminalRunStatus("running")).toBe(false);
+ expect(isTerminalRunStatus("succeeded")).toBe(true);
+ expect(isTerminalRunStatus("failed")).toBe(true);
+ expect(isTerminalRunStatus("cancelled")).toBe(true);
+ });
+
+ it("polls only while non-terminal (V1 2s policy)", () => {
+ expect(shouldPollRun("queued")).toBe(true);
+ expect(shouldPollRun("running")).toBe(true);
+ for (const status of ["succeeded", "failed", "cancelled"] as CompanySkillTestRunStatus[]) {
+ expect(shouldPollRun(status)).toBe(false);
+ }
+ });
+
+ it("isRunActive is the inverse of terminal", () => {
+ for (const status of ALL_STATUSES) {
+ expect(isRunActive({ status })).toBe(!isTerminalRunStatus(status));
+ }
+ });
+
+ it("maps every status onto a StatusBadge status (D6)", () => {
+ for (const status of ALL_STATUSES) {
+ expect(runBadgeStatus(status)).toBe(status);
+ }
+ });
+
+ it("shows an error card only for failed runs (cancelled has none)", () => {
+ expect(showRunErrorCard("failed")).toBe(true);
+ expect(showRunErrorCard("cancelled")).toBe(false);
+ expect(showRunErrorCard("succeeded")).toBe(false);
+ expect(showRunErrorCard("running")).toBe(false);
+ });
+
+ describe("output mode", () => {
+ it("succeeded with output renders the output", () => {
+ expect(runOutputMode({ status: "succeeded", outputBody: "# Result" })).toBe("output");
+ });
+ it("succeeded with no output renders none", () => {
+ expect(runOutputMode({ status: "succeeded", outputBody: "" })).toBe("none");
+ expect(runOutputMode({ status: "succeeded", outputBody: null })).toBe("none");
+ });
+ it("failed with partial output is a draft-at-failure", () => {
+ expect(runOutputMode({ status: "failed", outputBody: "partial" })).toBe("draft");
+ });
+ it("cancelled with partial output is a draft-at-failure", () => {
+ expect(runOutputMode({ status: "cancelled", outputBody: "partial" })).toBe("draft");
+ });
+ it("failed with no output renders none", () => {
+ expect(runOutputMode({ status: "failed", outputBody: " " })).toBe("none");
+ });
+ it("non-terminal with no output is pending, with output shows it streaming", () => {
+ expect(runOutputMode({ status: "running", outputBody: "" })).toBe("pending");
+ expect(runOutputMode({ status: "queued", outputBody: null })).toBe("pending");
+ expect(runOutputMode({ status: "running", outputBody: "live" })).toBe("output");
+ });
+ });
+
+ describe("test-task deep link state", () => {
+ it("is enabled for a live harness issue", () => {
+ expect(testTaskLinkState({ taskExpired: false, harnessIssue: { id: "i1" } })).toEqual({
+ enabled: true,
+ reason: null,
+ });
+ });
+ it("is disabled when the task expired", () => {
+ expect(testTaskLinkState({ taskExpired: true, harnessIssue: { id: "i1" } })).toEqual({
+ enabled: false,
+ reason: "Test task expired",
+ });
+ });
+ it("is disabled when the harness issue was deleted", () => {
+ expect(testTaskLinkState({ taskExpired: false, harnessIssue: null })).toEqual({
+ enabled: false,
+ reason: "Test task expired",
+ });
+ });
+ });
+});
+
+describe("rich run output helpers", () => {
+ it("separates the output document from additional documents and raw attachments", () => {
+ const outputDocument = makeRunDocument({
+ id: "doc-output",
+ key: "output",
+ title: "Output",
+ body: "## Primary result",
+ });
+ const notesDocument = makeRunDocument({
+ id: "doc-notes",
+ key: "notes",
+ title: "Notes",
+ body: "Follow-up notes",
+ });
+ const promotedAttachmentId = "11111111-1111-4111-8111-111111111111";
+ const promotedAttachment = makeRunAttachment({
+ id: promotedAttachmentId,
+ contentType: "image/png",
+ originalFilename: "output.png",
+ });
+ const rawAttachment = makeRunAttachment({
+ id: "attachment-notes",
+ contentType: "text/markdown",
+ originalFilename: "notes.md",
+ });
+ const workProduct = makeArtifactWorkProduct({
+ id: "wp-output",
+ attachmentId: promotedAttachmentId,
+ contentPath: promotedAttachment.contentPath,
+ originalFilename: "output.png",
+ });
+ const detail = {
+ outputDocumentKey: "output",
+ harnessContent: {
+ available: true,
+ unavailableReason: null,
+ documents: [outputDocument, notesDocument],
+ attachments: [promotedAttachment, rawAttachment],
+ workProducts: [workProduct],
+ },
+ };
+
+ expect(findRunOutputDocument(detail)).toBe(outputDocument);
+ expect(getRunAdditionalDocuments(detail)).toEqual([notesDocument]);
+ expect(getRunRawAttachments(detail)).toEqual([rawAttachment]);
+ expect(getRunMediaGalleryItems(detail).map((item) => item.id)).toEqual([promotedAttachment.id]);
+ });
+
+ it("adds media work products to the gallery when no matching attachment is present", () => {
+ const videoAttachmentId = "22222222-2222-4222-8222-222222222222";
+ const workProduct = makeArtifactWorkProduct({
+ id: "wp-video",
+ attachmentId: videoAttachmentId,
+ contentType: "video/webm",
+ contentPath: `/api/attachments/${videoAttachmentId}/content`,
+ originalFilename: "demo.webm",
+ });
+ const detail = {
+ outputDocumentKey: "output",
+ harnessContent: {
+ available: true,
+ unavailableReason: null,
+ documents: [],
+ attachments: [],
+ workProducts: [workProduct],
+ },
+ };
+
+ expect(getRunMediaGalleryItems(detail)).toEqual([
+ expect.objectContaining({
+ id: "work-product-wp-video",
+ contentPath: `/api/attachments/${videoAttachmentId}/content`,
+ contentType: "video/webm",
+ originalFilename: "demo.webm",
+ }),
+ ]);
+ });
+
+ it("reports an unavailable deleted harness while leaving rich collections quiet", () => {
+ const detail = {
+ outputDocumentKey: "output",
+ harnessContent: {
+ available: false,
+ unavailableReason: "deleted" as const,
+ documents: [],
+ attachments: [],
+ workProducts: [],
+ },
+ };
+
+ expect(runHarnessUnavailableCopy(detail)).toEqual({
+ title: "Test task deleted",
+ body: "Stored run snapshots are still shown. Harness documents, attachments, and work products are no longer available.",
+ });
+ expect(getRunAdditionalDocuments(detail)).toEqual([]);
+ expect(getRunRawAttachments(detail)).toEqual([]);
+ expect(getRunMediaGalleryItems(detail)).toEqual([]);
+ });
+});
+
+describe("disabled-Run matrix", () => {
+ const ready = { hasAgent: true, hasInput: true, skillFileCount: 3 };
+
+ it("enables Run when agent + input + files are all present", () => {
+ expect(evaluateRunGate(ready)).toEqual({ disabled: false, reason: null });
+ });
+
+ it("blocks on zero skill files first", () => {
+ expect(evaluateRunGate({ ...ready, skillFileCount: 0 })).toEqual({
+ disabled: true,
+ reason: "This skill has no files to test",
+ });
+ });
+
+ it("blocks when no agent is selected", () => {
+ expect(evaluateRunGate({ ...ready, hasAgent: false })).toEqual({
+ disabled: true,
+ reason: "Pick an agent to run",
+ });
+ });
+
+ it("blocks when the input is empty", () => {
+ expect(evaluateRunGate({ ...ready, hasInput: false })).toEqual({
+ disabled: true,
+ reason: "Add or paste input text to run",
+ });
+ });
+
+ it("blocks when skill editor edits are unsaved", () => {
+ expect(evaluateRunGate({ ...ready, hasUnsavedSkillEdits: true })).toEqual({
+ disabled: true,
+ reason: "Save skill edits before running",
+ });
+ });
+
+ it("blocks when a run is already in flight", () => {
+ expect(evaluateRunGate({ ...ready, runInFlight: true })).toEqual({
+ disabled: true,
+ reason: "A run is already in progress",
+ });
+ });
+
+ it("zero files takes priority over missing agent and input", () => {
+ expect(
+ evaluateRunGate({ hasAgent: false, hasInput: false, skillFileCount: 0 }).reason,
+ ).toBe("This skill has no files to test");
+ });
+
+ it("missing agent takes priority over missing input", () => {
+ expect(
+ evaluateRunGate({ hasAgent: false, hasInput: false, skillFileCount: 2 }).reason,
+ ).toBe("Pick an agent to run");
+ });
+});
+
+describe("saved input editor draft state", () => {
+ const savedInput = { id: "input-1", content: "existing content" };
+
+ it("populates the editor when a selected input record arrives after initial render", () => {
+ const state = syncSavedInputDraftState(EMPTY_SAVED_INPUT_DRAFT_STATE, savedInput);
+
+ expect(selectedSavedInputDraft(state, savedInput)).toBe("existing content");
+ expect(savedInputDraftDirty(state, savedInput)).toBe(false);
+ });
+
+ it("switches draft state when a different saved input is selected", () => {
+ const first = syncSavedInputDraftState(EMPTY_SAVED_INPUT_DRAFT_STATE, savedInput);
+ const secondInput = { id: "input-2", content: "second body" };
+ const second = syncSavedInputDraftState({ ...first, draft: "local edit" }, secondInput);
+
+ expect(second).toEqual({
+ inputId: "input-2",
+ draft: "second body",
+ baselineContent: "second body",
+ });
+ });
+
+ it("adopts background refetch content while the local draft is clean", () => {
+ const initial = syncSavedInputDraftState(EMPTY_SAVED_INPUT_DRAFT_STATE, savedInput);
+ const updated = syncSavedInputDraftState(initial, {
+ id: "input-1",
+ content: "server update",
+ });
+
+ expect(selectedSavedInputDraft(updated, { id: "input-1", content: "server update" })).toBe("server update");
+ expect(savedInputDraftDirty(updated, { id: "input-1", content: "server update" })).toBe(false);
+ });
+
+ it("preserves a dirty local draft across background refetches", () => {
+ const initial = syncSavedInputDraftState(EMPTY_SAVED_INPUT_DRAFT_STATE, savedInput);
+ const dirty = { ...initial, draft: "local edit" };
+ const afterRefetch = syncSavedInputDraftState(dirty, {
+ id: "input-1",
+ content: "server update",
+ });
+
+ expect(selectedSavedInputDraft(afterRefetch, { id: "input-1", content: "server update" })).toBe("local edit");
+ expect(savedInputDraftDirty(afterRefetch, { id: "input-1", content: "server update" })).toBe(true);
+ });
+});
+
+describe("interaction inline-vs-fallback routing", () => {
+ it("renders ask_user_questions and request_confirmation inline", () => {
+ expect(routeInteraction("ask_user_questions")).toBe("inline");
+ expect(routeInteraction("request_confirmation")).toBe("inline");
+ expect(INLINE_INTERACTION_KINDS.has("ask_user_questions")).toBe(true);
+ });
+
+ it("routes every other kind to the fallback summary row", () => {
+ for (const kind of [
+ "suggest_tasks",
+ "request_checkbox_confirmation",
+ "request_board_approval",
+ "some_future_kind",
+ ]) {
+ expect(routeInteraction(kind)).toBe("fallback");
+ }
+ });
+
+ it("only answers inline interactions that are still pending", () => {
+ expect(isInteractionAnswerable({ kind: "ask_user_questions", status: "pending" })).toBe(true);
+ expect(isInteractionAnswerable({ kind: "ask_user_questions", status: "answered" })).toBe(false);
+ expect(isInteractionAnswerable({ kind: "request_confirmation", status: "accepted" })).toBe(false);
+ // Fallback kinds are never answerable inline even while pending.
+ expect(isInteractionAnswerable({ kind: "suggest_tasks", status: "pending" })).toBe(false);
+ });
+});
+
+describe("agent picker + run labels", () => {
+ it("marks paused agents as unselectable", () => {
+ expect(isAgentSelectable({ status: "active" })).toBe(true);
+ expect(isAgentSelectable({ status: "idle" })).toBe(true);
+ expect(isAgentSelectable({ status: "paused" })).toBe(false);
+ });
+
+ it("builds a short run id", () => {
+ expect(runShortId({ id: "abcdef01-2345-6789-abcd-ef0123456789" })).toBe("#abcdef0");
+ });
+
+ it("finds the output document by the run's output key", () => {
+ const detail = {
+ outputDocumentKey: "output",
+ documents: [
+ { key: "notes", title: "Notes", updatedAt: new Date(), body: "n" },
+ { key: "output", title: "Output", updatedAt: new Date(), body: "o" },
+ ],
+ };
+ expect(findOutputDocument(detail)?.body).toBe("o");
+ expect(findOutputDocument({ outputDocumentKey: "missing", documents: detail.documents })).toBeNull();
+ });
+
+ describe("buildReRunRequest", () => {
+ it("reproduces a saved-input run from its own snapshots (never live picker state)", () => {
+ const req = buildReRunRequest({
+ agentId: "agent-9",
+ inputId: "input-3",
+ inputSnapshot: "snapshotted text",
+ skillVersionId: "ver-7",
+ templateId: "template-1",
+ templateName: "Focused smoke",
+ templateBody: "Original {{skillName}}",
+ });
+ expect(req).toEqual({
+ agentId: "agent-9",
+ inputId: "input-3",
+ content: undefined,
+ skillVersionId: "ver-7",
+ templateSnapshot: {
+ templateId: "template-1",
+ templateName: "Focused smoke",
+ templateBody: "Original {{skillName}}",
+ },
+ });
+ });
+
+ it("replays an ad-hoc run via its input snapshot as literal content", () => {
+ const req = buildReRunRequest({
+ agentId: "agent-1",
+ inputId: null,
+ inputSnapshot: "ad-hoc paste body",
+ skillVersionId: "ver-2",
+ templateId: null,
+ templateName: null,
+ templateBody: null,
+ });
+ expect(req.inputId).toBeUndefined();
+ expect(req.content).toBe("ad-hoc paste body");
+ expect(req.agentId).toBe("agent-1");
+ expect(req.skillVersionId).toBe("ver-2");
+ expect(req.templateSnapshot).toEqual({
+ templateId: null,
+ templateName: null,
+ templateBody: null,
+ });
+ });
+
+ it("always carries the run's agent id so a re-run never posts a null agent", () => {
+ const req = buildReRunRequest({
+ agentId: "agent-42",
+ inputId: null,
+ inputSnapshot: "x",
+ skillVersionId: "v",
+ templateId: "built-in:default-test-template",
+ templateName: "Default test template",
+ templateBody: "Default",
+ });
+ expect(req.agentId).toBe("agent-42");
+ });
+
+ it("preserves the viewed run's template snapshot instead of live template state", () => {
+ const req = buildReRunRequest({
+ agentId: "agent-42",
+ inputId: null,
+ inputSnapshot: "x",
+ skillVersionId: "v",
+ templateId: "template-old",
+ templateName: "Old template name",
+ templateBody: "Old body {{skillName}}",
+ });
+
+ expect(req.templateSnapshot).toEqual({
+ templateId: "template-old",
+ templateName: "Old template name",
+ templateBody: "Old body {{skillName}}",
+ });
+ });
+ });
+});
+
+describe("advanced run template helpers", () => {
+ const defaultTemplate: CompanySkillTestRunTemplate = {
+ id: DEFAULT_TEST_RUN_TEMPLATE_ID,
+ companyId: "company-1",
+ name: "Default test template",
+ description: "Default",
+ body: "Default {{skillName}}",
+ builtIn: true,
+ createdByAgentId: null,
+ createdByUserId: null,
+ updatedByAgentId: null,
+ updatedByUserId: null,
+ deletedAt: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ updatedAt: new Date("2026-01-01T00:00:00Z"),
+ };
+ const customTemplate: CompanySkillTestRunTemplate = {
+ ...defaultTemplate,
+ id: "template-1",
+ name: "Focused smoke",
+ description: null,
+ body: "Custom {{skillName}}",
+ builtIn: false,
+ };
+
+ it("serializes the No template selection distinctly from default", () => {
+ const serialized = serializeRunTemplateSelection(null);
+
+ expect(parseRunTemplateSelection(serialized)).toBeNull();
+ expect(parseRunTemplateSelection(null)).toBe(DEFAULT_TEST_RUN_TEMPLATE_ID);
+ expect(parseRunTemplateSelection("template-1")).toBe("template-1");
+ });
+
+ it("keeps valid server-backed selections and the explicit No template choice", () => {
+ expect(resolveRunTemplateSelection(customTemplate.id, [defaultTemplate, customTemplate])).toEqual({
+ selection: "template-1",
+ template: customTemplate,
+ recovered: false,
+ });
+ expect(resolveRunTemplateSelection(null, [defaultTemplate])).toEqual({
+ selection: null,
+ template: null,
+ recovered: false,
+ });
+ });
+
+ it("recovers stale local selections to the server-backed default template", () => {
+ expect(resolveRunTemplateSelection("deleted-template", [defaultTemplate, customTemplate])).toEqual({
+ selection: DEFAULT_TEST_RUN_TEMPLATE_ID,
+ template: defaultTemplate,
+ recovered: true,
+ });
+ });
+
+ it("builds run-create payloads with the selected template id", () => {
+ expect(
+ buildCreateRunRequest({
+ agentId: "agent-1",
+ inputId: "input-1",
+ content: null,
+ templateId: customTemplate.id,
+ }),
+ ).toEqual({
+ agentId: "agent-1",
+ inputId: "input-1",
+ content: null,
+ templateId: "template-1",
+ });
+
+ expect(
+ buildCreateRunRequest({
+ agentId: "agent-1",
+ inputId: null,
+ content: "ad-hoc",
+ templateId: null,
+ }).templateId,
+ ).toBeNull();
+ });
+});
+
+describe("studio landing recency helpers", () => {
+ function makeSkill(
+ overrides: Partial<CompanySkillListItem> & { id: string },
+ ): CompanySkillListItem {
+ return {
+ companyId: "company-1",
+ key: overrides.id,
+ slug: overrides.id,
+ name: overrides.id,
+ description: null,
+ sourceType: "local_path",
+ sourceLocator: null,
+ sourceRef: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [],
+ 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: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ updatedAt: new Date("2026-01-01T00:00:00Z"),
+ attachedAgentCount: 0,
+ editable: true,
+ editableReason: null,
+ sourceLabel: null,
+ sourceBadge: "local",
+ sourcePath: null,
+ catalogKind: null,
+ originHash: null,
+ packageName: null,
+ packageVersion: null,
+ ...overrides,
+ };
+ }
+
+ describe("orderRecentlyVisitedSkills", () => {
+ it("orders by recency, drops stale/foreign ids, and caps at the limit", () => {
+ const skills = [makeSkill({ id: "a" }), makeSkill({ id: "b" }), makeSkill({ id: "c" })];
+ const result = orderRecentlyVisitedSkills(skills, ["c", "missing", "a"]);
+ expect(result.map((s) => s.id)).toEqual(["c", "a"]);
+ });
+
+ it("dedupes repeated ids and respects the limit", () => {
+ const skills = Array.from({ length: 8 }, (_, i) => makeSkill({ id: `s${i}` }));
+ const recent = ["s0", "s0", "s1", "s2", "s3", "s4", "s5"];
+ const result = orderRecentlyVisitedSkills(skills, recent, 5);
+ expect(result.map((s) => s.id)).toEqual(["s0", "s1", "s2", "s3", "s4"]);
+ });
+
+ it("returns empty when nothing matches", () => {
+ expect(orderRecentlyVisitedSkills([makeSkill({ id: "a" })], ["x", "y"])).toEqual([]);
+ });
+ });
+
+ describe("orderRecentlyUpdatedSkills", () => {
+ it("sorts by updatedAt desc and excludes the visited ids", () => {
+ const skills = [
+ makeSkill({ id: "old", updatedAt: new Date("2026-01-01T00:00:00Z") }),
+ makeSkill({ id: "new", updatedAt: new Date("2026-03-01T00:00:00Z") }),
+ makeSkill({ id: "mid", updatedAt: new Date("2026-02-01T00:00:00Z") }),
+ ];
+ const result = orderRecentlyUpdatedSkills(skills, ["mid"]);
+ expect(result.map((s) => s.id)).toEqual(["new", "old"]);
+ });
+
+ it("handles ISO-string updatedAt from the wire and caps at the limit", () => {
+ const skills = Array.from({ length: 12 }, (_, i) =>
+ makeSkill({
+ id: `s${i}`,
+ // later index -> more recent
+ updatedAt: new Date(2026, 0, i + 1).toISOString() as unknown as Date,
+ }),
+ );
+ const result = orderRecentlyUpdatedSkills(skills, []);
+ expect(result).toHaveLength(10);
+ expect(result[0]!.id).toBe("s11");
+ });
+
+ it("breaks updatedAt ties by name", () => {
+ const when = new Date("2026-01-01T00:00:00Z");
+ const skills = [
+ makeSkill({ id: "z", name: "Zebra", updatedAt: when }),
+ makeSkill({ id: "a", name: "Apple", updatedAt: when }),
+ ];
+ expect(orderRecentlyUpdatedSkills(skills, []).map((s) => s.name)).toEqual([
+ "Apple",
+ "Zebra",
+ ]);
+ });
+ });
+
+ describe("skillEditorAvatar", () => {
+ const userEditor: CompanySkillLastEditor = {
+ kind: "user",
+ id: "user-1",
+ name: "Ada Lovelace",
+ imageUrl: "https://example.com/ada.png",
+ };
+
+ it("returns image + initials for a human editor", () => {
+ expect(skillEditorAvatar(userEditor)).toEqual({
+ name: "Ada Lovelace",
+ imageUrl: "https://example.com/ada.png",
+ initials: "AL",
+ });
+ });
+
+ it("derives two-letter initials from a single name", () => {
+ expect(skillEditorAvatar({ ...userEditor, name: "Cher" })?.initials).toBe("CH");
+ });
+
+ it("falls back to a placeholder name when unnamed", () => {
+ expect(skillEditorAvatar({ ...userEditor, name: null })).toEqual({
+ name: "Unknown editor",
+ imageUrl: "https://example.com/ada.png",
+ initials: "UE",
+ });
+ });
+
+ it("returns null for agent edits and unattributed syncs", () => {
+ expect(
+ skillEditorAvatar({ kind: "agent", id: "a1", name: "Bot", imageUrl: null }),
+ ).toBeNull();
+ expect(skillEditorAvatar(null)).toBeNull();
+ expect(skillEditorAvatar(undefined)).toBeNull();
+ });
+ });
+});
diff --git a/ui/src/lib/skill-studio.ts b/ui/src/lib/skill-studio.ts
new file mode 100644
index 0000000000..8b7ac2ab8f
--- /dev/null
+++ b/ui/src/lib/skill-studio.ts
@@ -0,0 +1,555 @@
+import type {
+ CompanySkillLastEditor,
+ CompanySkillListItem,
+ CompanySkillTestInput,
+ CompanySkillTestRun,
+ CompanySkillTestRunCreateRequest,
+ CompanySkillTestRunDetail,
+ CompanySkillTestRunHarnessContentUnavailableReason,
+ CompanySkillTestRunStatus,
+ CompanySkillTestRunTemplate,
+ IssueAttachment,
+ IssueDocument,
+} from "@paperclipai/shared";
+import {
+ getIssueOutputs,
+ getPromotedOutputAttachmentIds,
+ isImageContentType,
+ isVideoLikeOutput,
+} from "./issue-output";
+
+/**
+ * Pure logic for the Skill Studio UI (PAP-12962). Kept free of React so the
+ * three behavioural contracts the acceptance criteria call out — run-status
+ * derivation, the disabled-Run matrix, and interaction inline-vs-fallback
+ * routing — are unit-testable in isolation.
+ */
+
+export const TERMINAL_RUN_STATUSES: readonly CompanySkillTestRunStatus[] = [
+ "succeeded",
+ "failed",
+ "cancelled",
+];
+
+export const DEFAULT_TEST_RUN_TEMPLATE_ID = "built-in:default-test-template";
+export const NO_TEST_RUN_TEMPLATE_STORAGE_VALUE = "__paperclip_no_template__";
+
+export function isTerminalRunStatus(status: CompanySkillTestRunStatus): boolean {
+ return TERMINAL_RUN_STATUSES.includes(status);
+}
+
+/** V1 poll policy: poll every 2s while a run is non-terminal, stop on terminal. */
+export function shouldPollRun(status: CompanySkillTestRunStatus): boolean {
+ return !isTerminalRunStatus(status);
+}
+
+/**
+ * Map a test-run status onto the shared `StatusBadge` status vocabulary so the
+ * Studio never invents a bespoke chip (spec D6). `queued` aligns with the
+ * pending/yellow treatment.
+ */
+export type RunBadgeStatus = "queued" | "running" | "succeeded" | "failed" | "cancelled";
+
+export function runBadgeStatus(status: CompanySkillTestRunStatus): RunBadgeStatus {
+ return status;
+}
+
+/**
+ * What the right-pane output region should render for a run.
+ * - `output` — a completed run with output body.
+ * - `draft` — a failed/cancelled run that still produced partial output
+ * ("draft at failure").
+ * - `pending` — non-terminal run, output not ready yet.
+ * - `none` — terminal run with no output at all.
+ */
+export type RunOutputMode = "output" | "draft" | "pending" | "none";
+
+export function runOutputMode(run: {
+ status: CompanySkillTestRunStatus;
+ outputBody?: string | null;
+}): RunOutputMode {
+ const hasOutput = Boolean(run.outputBody && run.outputBody.trim().length > 0);
+ if (!isTerminalRunStatus(run.status)) {
+ return hasOutput ? "output" : "pending";
+ }
+ if (run.status === "succeeded") {
+ return hasOutput ? "output" : "none";
+ }
+ // failed / cancelled
+ return hasOutput ? "draft" : "none";
+}
+
+/** Failed runs get an error card at the top of the detail view; cancelled do not. */
+export function showRunErrorCard(status: CompanySkillTestRunStatus): boolean {
+ return status === "failed";
+}
+
+/**
+ * Whether the "Open test task ↗" deep link is live. A retention-expired or
+ * hard-deleted harness issue leaves the run row intact (self-contained
+ * snapshots) but disables the link with a "Test task expired" tooltip.
+ */
+export function testTaskLinkState(run: {
+ taskExpired: boolean;
+ harnessIssue?: { id: string } | null;
+}): { enabled: boolean; reason: string | null } {
+ if (run.taskExpired || !run.harnessIssue) {
+ return { enabled: false, reason: "Test task expired" };
+ }
+ return { enabled: true, reason: null };
+}
+
+// ---------------------------------------------------------------------------
+// Disabled-Run matrix (contract §7.1 "Buttons")
+// ---------------------------------------------------------------------------
+
+export interface RunGateInput {
+ /** An agent is selected in the picker (paused agents are never selectable). */
+ hasAgent: boolean;
+ /** The active input (saved or ad-hoc paste) has non-whitespace content. */
+ hasInput: boolean;
+ /** Number of files in the skill under test. */
+ skillFileCount: number;
+ /** A run is already in flight from this surface (optional guard). */
+ runInFlight?: boolean;
+ /** The editor has unsaved content that is not yet on disk or in a version. */
+ hasUnsavedSkillEdits?: boolean;
+}
+
+export interface RunGateResult {
+ disabled: boolean;
+ /** Tooltip copy naming the reason, or null when the Run button is enabled. */
+ reason: string | null;
+}
+
+/**
+ * Evaluate the Run button's disabled state. Reasons are checked in priority
+ * order and the first blocking condition wins, so the tooltip always names a
+ * single actionable reason (recognition over recall).
+ */
+export function evaluateRunGate(input: RunGateInput): RunGateResult {
+ if (input.skillFileCount <= 0) {
+ return { disabled: true, reason: "This skill has no files to test" };
+ }
+ if (!input.hasAgent) {
+ return { disabled: true, reason: "Pick an agent to run" };
+ }
+ if (!input.hasInput) {
+ return { disabled: true, reason: "Add or paste input text to run" };
+ }
+ if (input.hasUnsavedSkillEdits) {
+ return { disabled: true, reason: "Save skill edits before running" };
+ }
+ if (input.runInFlight) {
+ return { disabled: true, reason: "A run is already in progress" };
+ }
+ return { disabled: false, reason: null };
+}
+
+// ---------------------------------------------------------------------------
+// Saved input editor state
+// ---------------------------------------------------------------------------
+
+export interface SavedInputDraftState {
+ inputId: string | null;
+ draft: string;
+ baselineContent: string;
+}
+
+export const EMPTY_SAVED_INPUT_DRAFT_STATE: SavedInputDraftState = {
+ inputId: null,
+ draft: "",
+ baselineContent: "",
+};
+
+/**
+ * Keep the saved-input editor synchronized with the selected input record while
+ * preserving local dirty edits across background refetches. This covers the
+ * deep-link case where `selectedInputId` is already set before the input rows
+ * arrive, and the normal switch-input case where the selected row changes.
+ */
+export function syncSavedInputDraftState(
+ previous: SavedInputDraftState,
+ selectedInput: Pick<CompanySkillTestInput, "id" | "content"> | null,
+): SavedInputDraftState {
+ if (!selectedInput) {
+ return previous.inputId === null
+ ? previous
+ : EMPTY_SAVED_INPUT_DRAFT_STATE;
+ }
+
+ if (previous.inputId !== selectedInput.id) {
+ return {
+ inputId: selectedInput.id,
+ draft: selectedInput.content,
+ baselineContent: selectedInput.content,
+ };
+ }
+
+ if (previous.baselineContent === selectedInput.content) {
+ return previous;
+ }
+
+ if (previous.draft === previous.baselineContent) {
+ return {
+ inputId: selectedInput.id,
+ draft: selectedInput.content,
+ baselineContent: selectedInput.content,
+ };
+ }
+
+ return previous;
+}
+
+export function selectedSavedInputDraft(
+ state: SavedInputDraftState,
+ selectedInput: Pick<CompanySkillTestInput, "id" | "content"> | null,
+): string {
+ if (!selectedInput) return "";
+ return state.inputId === selectedInput.id ? state.draft : selectedInput.content;
+}
+
+export function savedInputDraftDirty(
+ state: SavedInputDraftState,
+ selectedInput: Pick<CompanySkillTestInput, "id" | "content"> | null,
+): boolean {
+ return Boolean(
+ selectedInput
+ && state.inputId === selectedInput.id
+ && state.draft !== selectedInput.content,
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Interaction inline-vs-fallback routing (board 12)
+// ---------------------------------------------------------------------------
+
+/**
+ * Interaction kinds that render as inline, answerable cards inside the Studio.
+ * Answering posts to the real interaction on the hidden harness task; every
+ * other kind is shown as a non-dropped summary row that links out to the task.
+ */
+export const INLINE_INTERACTION_KINDS: ReadonlySet<string> = new Set([
+ "ask_user_questions",
+ "request_confirmation",
+]);
+
+export type InteractionRendering = "inline" | "fallback";
+
+export function routeInteraction(kind: string): InteractionRendering {
+ return INLINE_INTERACTION_KINDS.has(kind) ? "inline" : "fallback";
+}
+
+/** An interaction is answerable inline only while it is still pending. */
+export function isInteractionAnswerable(interaction: { kind: string; status: string }): boolean {
+ return routeInteraction(interaction.kind) === "inline" && interaction.status === "pending";
+}
+
+// ---------------------------------------------------------------------------
+// Agent picker helpers
+// ---------------------------------------------------------------------------
+
+export interface AgentPickerItem {
+ id: string;
+ status: string;
+}
+
+/** Paused agents are muted and unselectable in the picker. */
+export function isAgentSelectable(agent: { status: string }): boolean {
+ return agent.status !== "paused";
+}
+
+// ---------------------------------------------------------------------------
+// Run label helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Short, stable run identifier for history rows (`#` + first 7 of the id),
+ * mirroring how the run detail header labels a run.
+ */
+export function runShortId(run: Pick<CompanySkillTestRun, "id">): string {
+ return `#${run.id.replace(/-/g, "").slice(0, 7)}`;
+}
+
+export function isRunActive(run: Pick<CompanySkillTestRun, "status">): boolean {
+ return !isTerminalRunStatus(run.status);
+}
+
+// ---------------------------------------------------------------------------
+// Advanced run template helpers
+// ---------------------------------------------------------------------------
+
+export type RunTemplateSelection = string | null;
+
+export interface RunTemplateSelectionResolution {
+ selection: RunTemplateSelection;
+ template: CompanySkillTestRunTemplate | null;
+ recovered: boolean;
+}
+
+export function serializeRunTemplateSelection(selection: RunTemplateSelection): string {
+ return selection === null ? NO_TEST_RUN_TEMPLATE_STORAGE_VALUE : selection;
+}
+
+export function parseRunTemplateSelection(value: string | null): RunTemplateSelection {
+ if (value === NO_TEST_RUN_TEMPLATE_STORAGE_VALUE) return null;
+ return value && value.trim() ? value : DEFAULT_TEST_RUN_TEMPLATE_ID;
+}
+
+export function resolveRunTemplateSelection(
+ selection: RunTemplateSelection,
+ templates: readonly CompanySkillTestRunTemplate[],
+): RunTemplateSelectionResolution {
+ if (selection === null) {
+ return { selection: null, template: null, recovered: false };
+ }
+
+ const template = templates.find((candidate) => candidate.id === selection) ?? null;
+ if (template) {
+ return { selection, template, recovered: false };
+ }
+
+ const fallback =
+ templates.find((candidate) => candidate.id === DEFAULT_TEST_RUN_TEMPLATE_ID)
+ ?? templates[0]
+ ?? null;
+
+ return {
+ selection: fallback?.id ?? null,
+ template: fallback,
+ recovered: true,
+ };
+}
+
+export function buildCreateRunRequest(input: {
+ agentId: string;
+ inputId: string | null;
+ content: string | null;
+ templateId: RunTemplateSelection;
+}): CompanySkillTestRunCreateRequest {
+ return {
+ agentId: input.agentId,
+ inputId: input.inputId,
+ content: input.content,
+ templateId: input.templateId,
+ };
+}
+
+/** The output document, if the run detail carries one under its output key. */
+export function findOutputDocument(detail: Pick<CompanySkillTestRunDetail, "documents" | "outputDocumentKey">) {
+ return detail.documents.find((doc) => doc.key === detail.outputDocumentKey) ?? null;
+}
+
+type RunRichOutputDetail = Pick<CompanySkillTestRunDetail, "outputDocumentKey" | "harnessContent">;
+
+export interface RunHarnessUnavailableCopy {
+ title: string;
+ body: string;
+}
+
+export interface RunMediaGalleryItem {
+ id: string;
+ contentPath: string;
+ openPath?: string;
+ downloadPath?: string;
+ contentType: string;
+ originalFilename: string | null;
+}
+
+function runHarnessUnavailableTitle(reason: CompanySkillTestRunHarnessContentUnavailableReason | null) {
+ if (reason === "expired") return "Test task expired";
+ if (reason === "deleted") return "Test task deleted";
+ return "Test task unavailable";
+}
+
+export function runHarnessUnavailableCopy(
+ detail: Pick<CompanySkillTestRunDetail, "harnessContent">,
+): RunHarnessUnavailableCopy | null {
+ if (detail.harnessContent.available) return null;
+ return {
+ title: runHarnessUnavailableTitle(detail.harnessContent.unavailableReason),
+ body: "Stored run snapshots are still shown. Harness documents, attachments, and work products are no longer available.",
+ };
+}
+
+export function findRunOutputDocument(detail: RunRichOutputDetail): IssueDocument | null {
+ return detail.harnessContent.documents.find((doc) => doc.key === detail.outputDocumentKey) ?? null;
+}
+
+export function getRunAdditionalDocuments(detail: RunRichOutputDetail): IssueDocument[] {
+ const outputDocument = findRunOutputDocument(detail);
+ return detail.harnessContent.documents.filter((doc) => {
+ if (doc.key === detail.outputDocumentKey) return false;
+ if (outputDocument && doc.id === outputDocument.id) return false;
+ return true;
+ });
+}
+
+export function getRunRawAttachments(detail: RunRichOutputDetail): IssueAttachment[] {
+ const promotedOutputAttachmentIds = getPromotedOutputAttachmentIds(detail.harnessContent.workProducts);
+ return detail.harnessContent.attachments.filter((attachment) => !promotedOutputAttachmentIds.has(attachment.id));
+}
+
+export function getRunMediaGalleryItems(detail: RunRichOutputDetail): RunMediaGalleryItem[] {
+ const items: RunMediaGalleryItem[] = [];
+ const seen = new Set<string>();
+
+ const mark = (attachmentId: string | null | undefined, contentPath: string) => {
+ if (attachmentId) seen.add(`attachment:${attachmentId}`);
+ seen.add(`content:${contentPath}`);
+ };
+ const hasSeen = (attachmentId: string | null | undefined, contentPath: string) => (
+ Boolean(attachmentId && seen.has(`attachment:${attachmentId}`)) ||
+ seen.has(`content:${contentPath}`)
+ );
+
+ for (const attachment of detail.harnessContent.attachments) {
+ if (
+ !isImageContentType(attachment.contentType) &&
+ !isVideoLikeOutput(attachment.contentType, attachment.originalFilename)
+ ) {
+ continue;
+ }
+ items.push(attachment);
+ mark(attachment.id, attachment.contentPath);
+ }
+
+ for (const output of getIssueOutputs(detail.harnessContent.workProducts).items) {
+ const meta = output.metadata;
+ if (!meta) continue;
+ const isMedia = isImageContentType(meta.contentType) ||
+ isVideoLikeOutput(meta.contentType, meta.originalFilename);
+ if (!isMedia || hasSeen(meta.attachmentId, meta.contentPath)) continue;
+ items.push({
+ id: `work-product-${output.id}`,
+ contentPath: meta.contentPath,
+ openPath: meta.openPath,
+ downloadPath: meta.downloadPath,
+ contentType: meta.contentType,
+ originalFilename: meta.originalFilename ?? output.title,
+ });
+ mark(meta.attachmentId, meta.contentPath);
+ }
+
+ return items;
+}
+
+/**
+ * Build the create-run request for a Re-run of an existing run. Re-run must
+ * reproduce the VIEWED run's snapshots — its agent, its input (saved input by
+ * id, or the ad-hoc snapshot as literal content), and its pinned skill version
+ * — rather than whatever the picker holds this session. Reading these off the
+ * run detail is the fix for the Bug A regression that posted `agentId: null`
+ * from empty picker state (PAP-13001).
+ */
+export function buildReRunRequest(
+ detail: Pick<
+ CompanySkillTestRun,
+ "agentId"
+ | "inputId"
+ | "inputSnapshot"
+ | "skillVersionId"
+ | "templateId"
+ | "templateName"
+ | "templateBody"
+ >,
+): CompanySkillTestRunCreateRequest {
+ return {
+ agentId: detail.agentId,
+ inputId: detail.inputId ?? undefined,
+ content: detail.inputId ? undefined : detail.inputSnapshot,
+ skillVersionId: detail.skillVersionId,
+ templateSnapshot: {
+ templateId: detail.templateId,
+ templateName: detail.templateName,
+ templateBody: detail.templateBody,
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Studio landing — recently visited + recently updated (PAP-13150)
+// ---------------------------------------------------------------------------
+
+export const RECENT_VISITED_SKILL_LIMIT = 5;
+export const RECENT_UPDATED_SKILL_LIMIT = 10;
+
+/**
+ * Intersect the per-browser recently-visited ids with the fetched skills list,
+ * most-recent-first, capped at `limit`. Stale/foreign ids that no longer match
+ * a live skill drop out automatically (they simply miss the lookup).
+ */
+export function orderRecentlyVisitedSkills(
+ skills: CompanySkillListItem[],
+ recentIds: string[],
+ limit = RECENT_VISITED_SKILL_LIMIT,
+): CompanySkillListItem[] {
+ const byId = new Map(skills.map((skill) => [skill.id, skill]));
+ const ordered: CompanySkillListItem[] = [];
+ const seen = new Set<string>();
+ for (const id of recentIds) {
+ if (seen.has(id)) continue;
+ const skill = byId.get(id);
+ if (!skill) continue;
+ ordered.push(skill);
+ seen.add(id);
+ if (ordered.length >= limit) break;
+ }
+ return ordered;
+}
+
+function updatedAtMs(skill: Pick<CompanySkillListItem, "updatedAt">): number {
+ const value = skill.updatedAt as unknown;
+ const time =
+ value instanceof Date ? value.getTime() : new Date(value as string).getTime();
+ return Number.isNaN(time) ? 0 : time;
+}
+
+/**
+ * Top `limit` skills by `updatedAt` desc, excluding anything already surfaced in
+ * the visited section (dedupe by id). Ties break by name so ordering is stable.
+ */
+export function orderRecentlyUpdatedSkills(
+ skills: CompanySkillListItem[],
+ excludeIds: Iterable<string>,
+ limit = RECENT_UPDATED_SKILL_LIMIT,
+): CompanySkillListItem[] {
+ const excluded = new Set(excludeIds);
+ return skills
+ .filter((skill) => !excluded.has(skill.id))
+ .slice()
+ .sort((a, b) => {
+ const delta = updatedAtMs(b) - updatedAtMs(a);
+ return delta !== 0 ? delta : a.name.localeCompare(b.name);
+ })
+ .slice(0, limit);
+}
+
+export interface SkillEditorAvatar {
+ name: string;
+ imageUrl: string | null;
+ initials: string;
+}
+
+function editorInitials(name: string): string {
+ const parts = name.trim().split(/\s+/).filter(Boolean);
+ if (parts.length === 0) return "?";
+ if (parts.length === 1) return parts[0]!.slice(0, 2).toUpperCase();
+ return (parts[0]![0]! + parts[parts.length - 1]![0]!).toUpperCase();
+}
+
+/**
+ * Gate the last-editor avatar to human edits only. Agent edits and
+ * unattributed syncs (`kind !== "user"`, or no editor) render nothing.
+ */
+export function skillEditorAvatar(
+ lastEditor: CompanySkillLastEditor | null | undefined,
+): SkillEditorAvatar | null {
+ if (!lastEditor || lastEditor.kind !== "user") return null;
+ const name = lastEditor.name?.trim() || "Unknown editor";
+ return {
+ name,
+ imageUrl: lastEditor.imageUrl,
+ initials: editorInitials(name),
+ };
+}
diff --git a/ui/src/lib/status-colors.ts b/ui/src/lib/status-colors.ts
index 42a7de40c8..f96808db89 100644
--- a/ui/src/lib/status-colors.ts
+++ b/ui/src/lib/status-colors.ts
@@ -95,6 +95,8 @@ export const statusBadge: Record<string, string> = {
info: "bg-sky-100 text-sky-700 dark:bg-sky-900/50 dark:text-sky-300",
terminated: "bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300",
pending: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/50 dark:text-yellow-300",
+ // Skill Studio test-run "queued" aligns with pending (yellow). PAP-12962 D6.
+ queued: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/50 dark:text-yellow-300",
// Approval statuses
pending_approval: "bg-amber-100 text-amber-700 dark:bg-amber-900/50 dark:text-amber-300",
diff --git a/ui/src/lib/worktree-branding.ts b/ui/src/lib/worktree-branding.ts
index d4781ded4d..bfa5a9a2b6 100644
--- a/ui/src/lib/worktree-branding.ts
+++ b/ui/src/lib/worktree-branding.ts
@@ -51,6 +51,16 @@ function pickReadableTextColor(background: string): string {
return whiteContrast >= blackContrast ? READABLE_TEXT_LIGHT : READABLE_TEXT_DARK;
}
+/**
+ * True when the UI is served by an isolated git-worktree preview instance
+ * (`PAPERCLIP_IN_WORKTREE=true` on the server). Unlike {@link getWorktreeUiBranding}
+ * this only depends on the enabled flag, so it stays reliable even if the
+ * worktree name/color branding is absent.
+ */
+export function isWorktreeRuntime(): boolean {
+ return readMetaContent("paperclip-worktree-enabled") === "true";
+}
+
export function getWorktreeUiBranding(): WorktreeUiBranding | null {
if (readMetaContent("paperclip-worktree-enabled") !== "true") return null;
diff --git a/ui/src/pages/AgentDetail.tsx b/ui/src/pages/AgentDetail.tsx
index dea43a2d4f..5563a5f492 100644
--- a/ui/src/pages/AgentDetail.tsx
+++ b/ui/src/pages/AgentDetail.tsx
@@ -7,7 +7,6 @@ import {
type ClaudeLoginResult,
type AgentPermissionUpdate,
} from "../api/agents";
-import { companySkillsApi } from "../api/companySkills";
import { budgetsApi } from "../api/budgets";
import { heartbeatsApi } from "../api/heartbeats";
import { instanceSettingsApi } from "../api/instanceSettings";
@@ -23,7 +22,7 @@ import { useCompany } from "../context/CompanyContext";
import { useToastActions } from "../context/ToastContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { queryKeys } from "../lib/queryKeys";
-import { resolveSkillSummaryText } from "../lib/company-skill-summary";
+import { AgentSkillsTab } from "./agent-skills/AgentSkillsTab";
import { AgentConfigForm } from "../components/AgentConfigForm";
import { PageTabBar } from "../components/PageTabBar";
import { adapterLabels, roleLabels, help } from "../components/agent-config-primitives";
@@ -85,8 +84,6 @@ import { RunTranscriptView, type TranscriptMode } from "../components/transcript
import {
isUuidLike,
type Agent,
- type AgentSkillEntry,
- type AgentSkillSnapshot,
type AgentDetail as AgentDetailRecord,
type BudgetPolicySummary,
type HeartbeatRun,
@@ -108,11 +105,6 @@ import {
useResourceMemberships,
} from "../hooks/useResourceMemberships";
import { Badge } from "@/components/ui/badge";
-import {
- applyAgentSkillSnapshot,
- arraysEqual,
- isReadOnlyUnmanagedSkillEntry,
-} from "../lib/agent-skills-state";
const runStatusIcons: Record<string, { icon: typeof CheckCircle2; color: string }> = {
succeeded: { icon: CheckCircle2, color: "text-green-600 dark:text-green-400" },
@@ -2608,417 +2600,6 @@ function PromptEditorSkeleton() {
);
}
-export function AgentSkillsTab({
- agent,
- companyId,
-}: {
- agent: Agent;
- companyId?: string;
-}) {
- type SkillRow = {
- id: string;
- key: string;
- name: string;
- description: string | null;
- detail: string | null;
- locationLabel: string | null;
- originLabel: string | null;
- linkTo: string | null;
- readOnly: boolean;
- adapterEntry: AgentSkillEntry | null;
- };
-
- const queryClient = useQueryClient();
- const [skillDraft, setSkillDraft] = useState<string[]>([]);
- const [lastSavedSkills, setLastSavedSkills] = useState<string[]>([]);
- const [unmanagedOpen, setUnmanagedOpen] = useState(false);
- const lastSavedSkillsRef = useRef<string[]>([]);
- const hasHydratedSkillSnapshotRef = useRef(false);
- const skipNextSkillAutosaveRef = useRef(true);
-
- const { data: skillSnapshot, isLoading } = useQuery({
- queryKey: queryKeys.agents.skills(agent.id),
- queryFn: () => agentsApi.skills(agent.id, companyId),
- enabled: Boolean(companyId),
- });
-
- const { data: companySkills } = useQuery({
- queryKey: queryKeys.companySkills.list(companyId ?? ""),
- queryFn: () => companySkillsApi.list(companyId!),
- enabled: Boolean(companyId),
- });
-
- const syncSkills = useMutation({
- mutationFn: (desiredSkills: string[]) => agentsApi.syncSkills(agent.id, desiredSkills, companyId),
- onSuccess: async (snapshot) => {
- queryClient.setQueryData(queryKeys.agents.skills(agent.id), snapshot);
- lastSavedSkillsRef.current = snapshot.desiredSkills;
- setLastSavedSkills(snapshot.desiredSkills);
- await Promise.all([
- queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.id) }),
- queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.urlKey) }),
- ]);
- },
- });
-
- useEffect(() => {
- setSkillDraft([]);
- setLastSavedSkills([]);
- lastSavedSkillsRef.current = [];
- hasHydratedSkillSnapshotRef.current = false;
- skipNextSkillAutosaveRef.current = true;
- }, [agent.id]);
-
- useEffect(() => {
- if (!skillSnapshot) return;
- const nextState = applyAgentSkillSnapshot(
- {
- draft: skillDraft,
- lastSaved: lastSavedSkillsRef.current,
- hasHydratedSnapshot: hasHydratedSkillSnapshotRef.current,
- },
- skillSnapshot.desiredSkills,
- );
- skipNextSkillAutosaveRef.current = nextState.shouldSkipAutosave;
- hasHydratedSkillSnapshotRef.current = nextState.hasHydratedSnapshot;
- setSkillDraft(nextState.draft);
- lastSavedSkillsRef.current = nextState.lastSaved;
- setLastSavedSkills(nextState.lastSaved);
- }, [skillDraft, skillSnapshot]);
-
- useEffect(() => {
- if (!skillSnapshot) return;
- if (skipNextSkillAutosaveRef.current) {
- skipNextSkillAutosaveRef.current = false;
- return;
- }
- if (syncSkills.isPending) return;
- if (arraysEqual(skillDraft, lastSavedSkillsRef.current)) return;
-
- const timeout = window.setTimeout(() => {
- if (!arraysEqual(skillDraft, lastSavedSkillsRef.current)) {
- syncSkills.mutate(skillDraft);
- }
- }, 250);
-
- return () => window.clearTimeout(timeout);
- }, [skillDraft, skillSnapshot, syncSkills.isPending, syncSkills.mutate]);
-
- const companySkillByKey = useMemo(
- () => new Map((companySkills ?? []).map((skill) => [skill.key, skill])),
- [companySkills],
- );
- const companySkillKeys = useMemo(
- () => new Set((companySkills ?? []).map((skill) => skill.key)),
- [companySkills],
- );
- const adapterEntryByKey = useMemo(
- () => new Map((skillSnapshot?.entries ?? []).map((entry) => [entry.key, entry])),
- [skillSnapshot],
- );
- const optionalSkillRows = useMemo<SkillRow[]>(
- () =>
- (companySkills ?? []).map((skill) => ({
- id: skill.id,
- key: skill.key,
- name: skill.name,
- description: skill.description,
- detail: adapterEntryByKey.get(skill.key)?.detail ?? null,
- locationLabel: adapterEntryByKey.get(skill.key)?.locationLabel ?? null,
- originLabel: adapterEntryByKey.get(skill.key)?.originLabel ?? null,
- linkTo: `/skills/${skill.id}`,
- readOnly: false,
- adapterEntry: adapterEntryByKey.get(skill.key) ?? null,
- })),
- [adapterEntryByKey, companySkills],
- );
- const unmanagedSkillRows = useMemo<SkillRow[]>(
- () =>
- (skillSnapshot?.entries ?? [])
- .filter((entry) => isReadOnlyUnmanagedSkillEntry(entry, companySkillKeys))
- .map((entry) => ({
- id: `external:${entry.key}`,
- key: entry.key,
- name: entry.runtimeName ?? entry.key,
- description: null,
- detail: entry.detail ?? null,
- locationLabel: entry.locationLabel ?? null,
- originLabel: entry.originLabel ?? null,
- linkTo: null,
- readOnly: true,
- adapterEntry: entry,
- })),
- [companySkillKeys, skillSnapshot],
- );
- const installedSkillRows = useMemo(
- () => optionalSkillRows.filter((skill) => skillDraft.includes(skill.key)),
- [optionalSkillRows, skillDraft],
- );
- const otherSkillRows = useMemo(
- () => optionalSkillRows.filter((skill) => !skillDraft.includes(skill.key)),
- [optionalSkillRows, skillDraft],
- );
- const desiredOnlyMissingSkills = useMemo(
- () => skillDraft.filter((key) => !companySkillByKey.has(key)),
- [companySkillByKey, skillDraft],
- );
- const skillApplicationLabel = useMemo(() => {
- switch (skillSnapshot?.mode) {
- case "persistent":
- return "Kept in the workspace";
- case "ephemeral":
- return "Applied when the agent runs";
- case "unsupported":
- return "Tracked only";
- default:
- return "Unknown";
- }
- }, [skillSnapshot?.mode]);
- const unsupportedSkillMessage = useMemo(() => {
- if (skillSnapshot?.mode !== "unsupported") return null;
- if (
- agent.adapterType === "acpx_local" &&
- typeof agent.adapterConfig.agent === "string" &&
- agent.adapterConfig.agent === "custom"
- ) {
- return "Paperclip cannot manage skills for custom ACP commands yet.";
- }
- if (agent.adapterType === "openclaw_gateway") {
- return "Paperclip cannot manage OpenClaw skills here. Visit your OpenClaw instance to manage this agent's skills.";
- }
- return "Paperclip cannot manage skills for this adapter yet. Manage them in the adapter directly.";
- }, [agent.adapterConfig.agent, agent.adapterType, skillSnapshot?.mode]);
- const hasUnsavedChanges = !arraysEqual(skillDraft, lastSavedSkills);
- const saveStatusLabel = syncSkills.isPending
- ? "Saving changes..."
- : hasUnsavedChanges
- ? "Saving soon..."
- : null;
-
- return (
- <div className="max-w-4xl space-y-5">
- <div className="flex flex-wrap items-center justify-between gap-3">
- <Link
- to="/skills"
- className="text-sm font-medium text-foreground underline-offset-4 no-underline transition-colors hover:text-foreground/70 hover:underline"
- >
- View company skills library
- </Link>
- {saveStatusLabel ? (
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- {syncSkills.isPending ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : null}
- <span>{saveStatusLabel}</span>
- </div>
- ) : null}
- </div>
-
- {skillSnapshot?.warnings.length ? (
- <div className="space-y-1 rounded-xl border border-amber-300/60 bg-amber-50/60 px-4 py-3 text-sm text-amber-800 dark:border-amber-500/30 dark:bg-amber-950/20 dark:text-amber-200">
- {skillSnapshot.warnings.map((warning) => (
- <div key={warning}>{warning}</div>
- ))}
- </div>
- ) : null}
-
- {unsupportedSkillMessage ? (
- <div className="rounded-xl border border-border px-4 py-3 text-sm text-muted-foreground">
- {unsupportedSkillMessage}
- </div>
- ) : null}
-
- {isLoading ? (
- <PageSkeleton variant="list" />
- ) : (
- <>
- {(() => {
- const renderSkillRow = (skill: SkillRow) => {
- const summaryText = resolveSkillSummaryText(skill, { fallbackKey: true });
- const rowClassName = cn(
- "flex items-start gap-3 border-b border-border px-3 py-3 text-sm last:border-b-0",
- skill.readOnly ? "bg-muted/20" : "hover:bg-accent/20",
- );
- const body = (
- <div className="min-w-0 flex-1">
- <div className="flex items-center justify-between gap-3">
- <div className="min-w-0">
- <span className="truncate font-medium">{skill.name}</span>
- </div>
- {skill.linkTo ? (
- <Link
- to={skill.linkTo}
- className="shrink-0 text-xs text-muted-foreground no-underline hover:text-foreground"
- >
- View
- </Link>
- ) : null}
- </div>
- {summaryText && (
- <MarkdownBody className="mt-1 text-xs text-muted-foreground prose-p:my-1 prose-ul:my-1 prose-ol:my-1 prose-li:my-0 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
- {summaryText}
- </MarkdownBody>
- )}
- {skill.readOnly && skill.originLabel && (
- <p className="mt-1 text-xs text-muted-foreground">{skill.originLabel}</p>
- )}
- {skill.readOnly && skill.locationLabel && (
- <p className="mt-1 text-xs text-muted-foreground">Location: {skill.locationLabel}</p>
- )}
- {skill.detail && (
- <p className="mt-1 text-xs text-muted-foreground">{skill.detail}</p>
- )}
- </div>
- );
-
- if (skill.readOnly) {
- return (
- <div key={skill.id} className={rowClassName}>
- <span className="mt-1 h-2 w-2 rounded-full bg-muted-foreground/40" />
- {body}
- </div>
- );
- }
-
- const checked = skillDraft.includes(skill.key);
- const disabled = skillSnapshot?.mode === "unsupported";
- const checkbox = (
- <input
- type="checkbox"
- checked={checked}
- disabled={disabled}
- onChange={(event) => {
- const next = event.target.checked
- ? Array.from(new Set([...skillDraft, skill.key]))
- : skillDraft.filter((value) => value !== skill.key);
- setSkillDraft(next);
- }}
- className="mt-0.5 disabled:cursor-not-allowed disabled:opacity-60"
- />
- );
-
- return (
- <label key={skill.id} className={rowClassName}>
- {skillSnapshot?.mode === "unsupported" ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <span>{checkbox}</span>
- </TooltipTrigger>
- <TooltipContent side="top">
- {unsupportedSkillMessage ?? "Manage skills in the adapter directly."}
- </TooltipContent>
- </Tooltip>
- ) : (
- checkbox
- )}
- {body}
- </label>
- );
- };
-
- const renderSkillSection = (
- title: string,
- rows: SkillRow[],
- emptyMessage?: string,
- ) => {
- if (rows.length === 0 && !emptyMessage) return null;
- return (
- <section className="border-y border-border">
- <div className="border-b border-border bg-muted/40 px-3 py-2">
- <span className="text-xs font-medium text-muted-foreground">
- {title}
- </span>
- </div>
- {rows.length > 0 ? (
- rows.map(renderSkillRow)
- ) : (
- <div className="px-3 py-3 text-sm text-muted-foreground">
- {emptyMessage}
- </div>
- )}
- </section>
- );
- };
-
- if (optionalSkillRows.length === 0 && unmanagedSkillRows.length === 0) {
- return (
- <section className="border-y border-border">
- <div className="px-3 py-6 text-sm text-muted-foreground">
- Import skills into the company library first, then attach them here.
- </div>
- </section>
- );
- }
-
- return (
- <>
- {optionalSkillRows.length > 0
- ? renderSkillSection(
- "Installed skills",
- installedSkillRows,
- "No company-library skills installed on this agent.",
- )
- : null}
-
- {renderSkillSection("Other skills", otherSkillRows)}
-
-
- {unmanagedSkillRows.length > 0 && (
- <section className="border-y border-border">
- <div
- role="button"
- tabIndex={0}
- className="flex cursor-pointer items-center gap-2 border-b border-border bg-muted/40 px-3 py-2 select-none"
- onClick={() => setUnmanagedOpen((v) => !v)}
- onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setUnmanagedOpen((v) => !v); } }}
- >
- <span className="text-xs font-medium text-muted-foreground">
- ({unmanagedSkillRows.length}) User-installed skills, not managed by Paperclip
- </span>
- {unmanagedOpen ? <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" /> : <ChevronRight className="h-3.5 w-3.5 text-muted-foreground" />}
- </div>
- {unmanagedOpen && unmanagedSkillRows.map(renderSkillRow)}
- </section>
- )}
- </>
- );
- })()}
-
- {desiredOnlyMissingSkills.length > 0 && (
- <div className="rounded-xl border border-amber-300/60 bg-amber-50/60 px-4 py-3 text-sm text-amber-800 dark:border-amber-500/30 dark:bg-amber-950/20 dark:text-amber-200">
- <div className="font-medium">Requested skills missing from the company library</div>
- <div className="mt-1 text-xs">
- {desiredOnlyMissingSkills.join(", ")}
- </div>
- </div>
- )}
-
- <section className="border-t border-border pt-4">
- <div className="grid gap-2 text-sm sm:grid-cols-2">
- <div className="flex items-center justify-between gap-3 border-b border-border/60 py-2">
- <span className="text-muted-foreground">Adapter</span>
- <span className="font-medium">{adapterLabels[agent.adapterType] ?? agent.adapterType}</span>
- </div>
- <div className="flex items-center justify-between gap-3 border-b border-border/60 py-2">
- <span className="text-muted-foreground">Skills applied</span>
- <span>{skillApplicationLabel}</span>
- </div>
- <div className="flex items-center justify-between gap-3 border-b border-border/60 py-2">
- <span className="text-muted-foreground">Selected skills</span>
- <span>{skillDraft.length}</span>
- </div>
- </div>
-
- {syncSkills.isError && (
- <p className="mt-3 text-xs text-destructive">
- {syncSkills.error instanceof Error ? syncSkills.error.message : "Failed to update skills"}
- </p>
- )}
- </section>
- </>
- )}
- </div>
- );
-}
-
/* ---- Runs Tab ---- */
function RunListItem({ run, isSelected, agentId }: { run: HeartbeatRun; isSelected: boolean; agentId: string }) {
diff --git a/ui/src/pages/CompanySkills.test.tsx b/ui/src/pages/CompanySkills.test.tsx
index 5770f7fa4f..4171bd60bd 100644
--- a/ui/src/pages/CompanySkills.test.tsx
+++ b/ui/src/pages/CompanySkills.test.tsx
@@ -5,7 +5,7 @@ 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";
+import { DiscoveryGrid, SkillDetailPage, getSkillVersionDiffSelection } from "./CompanySkills";
vi.mock("@/lib/router", () => ({
Link: ({ children, to, ...props }: { children: ReactNode; to: string }) => (
@@ -40,7 +40,7 @@ vi.mock("@/components/ui/dialog", () => ({
vi.mock("@/components/ui/dropdown-menu", () => ({
DropdownMenu: ({ children }: { children: ReactNode }) => <>{children}</>,
- DropdownMenuContent: () => null,
+ DropdownMenuContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuItem: ({ children, onSelect }: { children: ReactNode; onSelect?: () => void }) => (
<button type="button" onClick={onSelect}>{children}</button>
),
@@ -226,6 +226,44 @@ async function renderSkillDetail(
return container;
}
+async function renderDiscoveryGrid(props: Partial<ComponentProps<typeof DiscoveryGrid>> = {}) {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root?.render(
+ <DiscoveryGrid
+ tab="all"
+ tabCounts={{ all: 0, installed: 0, catalog: 0, bundled: 0 }}
+ onTabChange={vi.fn()}
+ categories={[]}
+ categoryTotal={0}
+ activeCategory={null}
+ onCategoryChange={vi.fn()}
+ search=""
+ onSearchChange={vi.fn()}
+ sort="agents"
+ onSortChange={vi.fn()}
+ cards={[]}
+ onOpenCard={vi.fn()}
+ loading={false}
+ error={null}
+ totalCount={0}
+ onCreate={vi.fn()}
+ onImport={vi.fn()}
+ onBrowseCatalog={vi.fn()}
+ onScan={vi.fn()}
+ scanPending={false}
+ scanStatus={null}
+ {...props}
+ />,
+ );
+ });
+
+ return container;
+}
+
function buttonsNamed(node: ParentNode, name: string) {
return Array.from(node.querySelectorAll("button")).filter((button) => button.textContent?.trim() === name);
}
@@ -268,6 +306,27 @@ describe("getSkillVersionDiffSelection", () => {
});
});
+describe("DiscoveryGrid Studio entry points", () => {
+ it("links the header Studio button to Skill Studio", async () => {
+ const node = await renderDiscoveryGrid();
+ const studioLink = Array.from(node.querySelectorAll("a")).find((link) =>
+ link.textContent?.includes("Studio"),
+ );
+
+ expect(studioLink?.getAttribute("href")).toBe("/skills/studio");
+ });
+
+ it("uses the create callback from the New menu and empty state", async () => {
+ const onCreate = vi.fn();
+ const node = await renderDiscoveryGrid({ onCreate });
+
+ await click(buttonsNamed(node, "Create new skill")[0] as HTMLButtonElement);
+ await click(buttonsNamed(node, "Create a skill")[0] as HTMLButtonElement);
+
+ expect(onCreate).toHaveBeenCalledTimes(2);
+ });
+});
+
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");
@@ -299,7 +358,7 @@ describe("SkillDetailPage versions tab", () => {
});
describe("SkillDetailPage settings", () => {
- it("saves normalized category edits from the settings dialog", async () => {
+ it("saves category edits with spaces from the settings dialog", async () => {
const v1 = makeVersion(1, "# Demo Skill");
const onUpdateSettings = vi.fn();
const node = await renderSkillDetail([v1], {
@@ -318,12 +377,12 @@ describe("SkillDetailPage settings", () => {
expect(categoryInput.value).toBe("engineering");
- await inputValue(categoryInput, " Memory, review, memory ,,");
+ await inputValue(categoryInput, " Memory Tools, review, memory tools ,,");
await click(saveButton);
expect(onUpdateSettings).toHaveBeenCalledWith({
sharingScope: "company",
- categories: ["memory", "review"],
+ categories: ["Memory Tools", "review"],
});
});
diff --git a/ui/src/pages/CompanySkills.tsx b/ui/src/pages/CompanySkills.tsx
index 25224aca94..a3e9a25180 100644
--- a/ui/src/pages/CompanySkills.tsx
+++ b/ui/src/pages/CompanySkills.tsx
@@ -8,7 +8,6 @@ import type {
CatalogSkillFileDetail,
CatalogSkillSource,
CompanySkillCompatibility,
- CompanySkillCreateRequest,
CompanySkillDetail,
CompanySkillFileDetail,
CompanySkillFileInventoryEntry,
@@ -67,10 +66,17 @@ import { resolveSkillSummaryText } from "../lib/company-skill-summary";
import {
parseSkillRoute,
skillRoute,
+ skillStudioNewRoute,
+ skillStudioRoute,
withRouteSkill,
resolveSkillRouteToken,
type CompanySkillRouteSubject,
} from "../lib/company-skill-routes";
+import {
+ normalizeSkillDraftSlug,
+ splitCategoryDraft,
+} from "../lib/skill-create";
+import { SkillCardIcon } from "../components/SkillCardIcon";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
@@ -99,6 +105,7 @@ import {
Link2,
Lock,
ExternalLink,
+ FlaskConical,
Paperclip,
Pause,
Pencil,
@@ -543,47 +550,7 @@ export type DiscoveryCard = {
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.
-// token-extraction: allowlisted — skill.color is persisted/compared JS data (SkillCreateDraft), not just a rendered value; a var() string would corrupt it.
-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 (
- <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>
- );
-}
+export { SkillCardIcon } from "../components/SkillCardIcon";
function discoveryVersionLabel(skill: {
packageVersion: string | null;
@@ -607,24 +574,6 @@ function uniqueCategories(values: (string | null | undefined)[]): string[] {
return out;
}
-function normalizeSkillDraftSlug(value: string) {
- return value
- .trim()
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-+|-+$/g, "")
- .slice(0, 80);
-}
-
-function splitCategoryDraft(value: string) {
- return Array.from(
- new Set(value
- .split(",")
- .map((entry) => normalizeSkillDraftSlug(entry))
- .filter(Boolean)),
- );
-}
-
function categorySetKey(categories: string[]) {
return [...categories].sort().join(",");
}
@@ -635,32 +584,6 @@ function skillSettingsToastBody(skill: Pick<CompanySkillDetail, "categories" | "
return `${sharing} | ${categories}`;
}
-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.
@@ -1083,6 +1006,12 @@ export function DiscoveryGrid({
>
<RefreshCw className={cn("h-4 w-4", scanPending && "animate-spin")} />
</Button>
+ <Button asChild variant="outline" size="sm">
+ <Link to="/skills/studio">
+ <FlaskConical className="h-3.5 w-3.5" />
+ Studio
+ </Link>
+ </Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button size="sm" variant="default">
@@ -1222,314 +1151,6 @@ export function DiscoveryGrid({
);
}
-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,
- tagline: draft.tagline || 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-(--sz-calc-34) resize-y font-mono text-xs"
- />
- </div>
- ) : (
- <div className="space-y-4 text-sm">
- <div className="grid grid-cols-(--gtc-26) 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,
@@ -2598,6 +2219,7 @@ export function SkillDetailPage({
updateSettingsPending,
onDelete,
deletePending,
+ studioHref,
}: {
detail: CompanySkillDetail | null | undefined;
catalogSource?: CatalogSkillSource | null;
@@ -2637,6 +2259,7 @@ export function SkillDetailPage({
updateSettingsPending: boolean;
onDelete: () => void;
deletePending: boolean;
+ studioHref?: string;
}) {
const [diffOpen, setDiffOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
@@ -2690,6 +2313,7 @@ export function SkillDetailPage({
}
const skill = detail;
+ const resolvedStudioHref = studioHref ?? skillStudioRoute(skill.id);
const source = sourceMeta(skill.sourceBadge, skill.sourceLabel);
const SourceIcon = source.icon;
const body = file?.markdown ? stripFrontmatter(file.content) : file?.content ?? "";
@@ -2977,24 +2601,10 @@ export function SkillDetailPage({
<SkillCardIcon
card={{
key: detail.key,
- skillId: detail.id,
- catalogRef: null,
name: detail.name,
slug: detail.slug,
- author: detail.authorName ?? source.label,
- version: null,
- tagline: detail.tagline,
- 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}
/>
@@ -3055,6 +2665,12 @@ export function SkillDetailPage({
"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">
+ <Button variant="outline" size="sm" asChild>
+ <Link to={resolvedStudioHref}>
+ <FlaskConical className="mr-1.5 h-3.5 w-3.5" />
+ Open in Studio
+ </Link>
+ </Button>
<div className="flex items-center overflow-hidden rounded-md border border-border">
<Tooltip>
<TooltipTrigger asChild>
@@ -3455,6 +3071,12 @@ function SkillPane({
)}
</div>
<div className="flex flex-wrap items-center justify-end gap-2">
+ <Button variant="outline" size="sm" asChild>
+ <Link to={skillStudioRoute(detail.id)}>
+ <FlaskConical className="mr-1.5 h-3.5 w-3.5" />
+ Open in Studio
+ </Link>
+ </Button>
<Button
variant="ghost"
size="sm"
@@ -3718,9 +3340,6 @@ export function CompanySkills() {
}>({ open: false, catalogSkill: null, conflict: null, defaultSlug: null, defaultForce: false, defaultAction: "install", error: null });
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 routeSkillToken = parsedRoute.skillToken;
@@ -3793,12 +3412,6 @@ export function CompanySkills() {
setCatalogSelectedPath(path);
}
- function openCreateWizard(initialDraft: SkillCreateDraft = buildBlankSkillDraft()) {
- setCreateDraft(initialDraft);
- setCreateError(null);
- setCreateDialogOpen(true);
- }
-
useEffect(() => {
setBreadcrumbs([
{ label: "Skills", href: "/skills" },
@@ -3973,31 +3586,6 @@ export function CompanySkills() {
},
});
- const createSkill = useMutation({
- mutationFn: (payload: CompanySkillCreateRequest) => companySkillsApi.create(selectedCompanyId!, payload),
- onSuccess: async (skill) => {
- await queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) });
- navigate(routeForSkill(skill));
- setCreateDialogOpen(false);
- setCreateError(null);
- setCreateDraft(buildBlankSkillDraft());
- pushToast({
- tone: "success",
- 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: message,
- });
- },
- });
-
const scanProjects = useMutation({
mutationFn: () => companySkillsApi.scanProjects(selectedCompanyId!),
onMutate: () => {
@@ -4557,26 +4145,6 @@ export function CompanySkills() {
}}
/>
- <Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
- <DialogContent className="flex max-h-(--sz-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>
-
<Dialog open={importDialogOpen} onOpenChange={setImportDialogOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
@@ -4643,7 +4211,7 @@ export function CompanySkills() {
loading={skillsQuery.isLoading || catalogListQuery.isLoading}
error={skillsQuery.error?.message ?? catalogListQuery.error?.message ?? null}
totalCount={discoveryCards.length}
- onCreate={() => openCreateWizard()}
+ onCreate={() => navigate(skillStudioNewRoute())}
onImport={() => setImportDialogOpen(true)}
onBrowseCatalog={() => setDiscoveryTab("catalog")}
onScan={() => scanProjects.mutate()}
@@ -4697,11 +4265,12 @@ export function CompanySkills() {
installUpdatePending={installUpdate.isPending}
onToggleStar={() => toggleStar.mutate()}
starPending={toggleStar.isPending}
- onFork={() => activeDetail && openCreateWizard(buildForkSkillDraft(activeDetail))}
+ onFork={() => activeDetail && navigate(skillStudioNewRoute(activeDetail.id))}
onUpdateSettings={(updates) => activeDetail && updateSkillSettings.mutate({ skillId: activeDetail.id, updates })}
updateSettingsPending={updateSkillSettings.isPending}
onDelete={openDeleteDialog}
deletePending={deleteSkill.isPending}
+ studioHref={skillStudioRoute(selectedSkillId)}
/>
) : selectedCatalogRef ? (
// Catalog / optional / bundled skills open as a regular full page in the
diff --git a/ui/src/pages/DesignGuide.tsx b/ui/src/pages/DesignGuide.tsx
index 6b4e5eaec2..361f86369b 100644
--- a/ui/src/pages/DesignGuide.tsx
+++ b/ui/src/pages/DesignGuide.tsx
@@ -29,6 +29,11 @@ import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
+import {
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+} from "@/components/ui/resizable-panels";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import {
@@ -403,8 +408,8 @@ export function DesignGuide() {
<div className="flex flex-wrap gap-2">
{[
"avatar", "badge", "breadcrumb", "button", "card", "checkbox", "collapsible",
- "command", "dialog", "dropdown-menu", "input", "label", "popover", "scroll-area",
- "select", "separator", "sheet", "skeleton", "tabs", "textarea", "tooltip",
+ "command", "dialog", "dropdown-menu", "input", "label", "popover", "resizable-panels",
+ "scroll-area", "select", "separator", "sheet", "skeleton", "tabs", "textarea", "tooltip",
].map((name) => (
<Badge key={name} variant="outline" className="font-mono text-(length:--text-nano)">
{name}
@@ -1780,6 +1785,36 @@ export function DesignGuide() {
</p>
<EnvironmentVariablesEditorShowcase />
</Section>
+
+ <Section title="Resizable Panels">
+ <p className="text-sm text-muted-foreground">
+ Design-system wrapper over <span className="font-mono">react-resizable-panels</span>{" "}
+ (Skill Studio D2). Drag a handle to resize; panels accept percentage or pixel
+ (<span className="font-mono">minSize="240px"</span>) constraints and the middle panel is
+ collapsible. Use anywhere a split view is needed.
+ </p>
+ <div className="h-48 max-w-2xl overflow-hidden rounded-md border border-border">
+ <ResizablePanelGroup>
+ <ResizablePanel id="a" minSize="120px" className="bg-muted/30">
+ <div className="flex h-full items-center justify-center text-xs text-muted-foreground">
+ Panel A
+ </div>
+ </ResizablePanel>
+ <ResizableHandle />
+ <ResizablePanel id="b" minSize="120px" collapsible collapsedSize="40px" className="bg-muted/10">
+ <div className="flex h-full items-center justify-center text-xs text-muted-foreground">
+ Panel B (collapsible)
+ </div>
+ </ResizablePanel>
+ <ResizableHandle />
+ <ResizablePanel id="c" minSize="120px" className="bg-muted/30">
+ <div className="flex h-full items-center justify-center text-xs text-muted-foreground">
+ Panel C
+ </div>
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ </div>
+ </Section>
</div>
);
}
diff --git a/ui/src/pages/InstanceExperimentalSettings.test.tsx b/ui/src/pages/InstanceExperimentalSettings.test.tsx
index 2cfd1f4cfb..2882941978 100644
--- a/ui/src/pages/InstanceExperimentalSettings.test.tsx
+++ b/ui/src/pages/InstanceExperimentalSettings.test.tsx
@@ -67,9 +67,28 @@ function defaultExperimentalSettings(): InstanceExperimentalSettingsPayload {
enableIssueGraphLivenessAutoRecovery: false,
issueGraphLivenessAutoRecoveryLookbackHours: 24,
enableWorkspaceBranchReconcileForward: false,
+ enableWorktreeRunExecution: false,
};
}
+const WORKTREE_RUN_EXECUTION_TOGGLE_SELECTOR =
+ 'button[aria-label="Toggle worktree run execution setting"]';
+
+function setWorktreeRuntimeMeta(enabled: boolean) {
+ const name = "paperclip-worktree-enabled";
+ let meta = document.querySelector<HTMLMetaElement>(`meta[name="${name}"]`);
+ if (enabled) {
+ if (!meta) {
+ meta = document.createElement("meta");
+ meta.setAttribute("name", name);
+ document.head.appendChild(meta);
+ }
+ meta.setAttribute("content", "true");
+ } else if (meta) {
+ meta.remove();
+ }
+}
+
describe("InstanceExperimentalSettings — Conference Room Chat card (PAP-11233)", () => {
let container: HTMLDivElement;
let root: Root | null = null;
@@ -109,6 +128,7 @@ describe("InstanceExperimentalSettings — Conference Room Chat card (PAP-11233)
});
root = null;
container.remove();
+ setWorktreeRuntimeMeta(false);
vi.clearAllMocks();
});
@@ -222,6 +242,38 @@ describe("InstanceExperimentalSettings — Conference Room Chat card (PAP-11233)
expect(toggle?.getAttribute("aria-checked")).toBe("true");
});
+ it("hides the worktree run-execution toggle when not running in a worktree", async () => {
+ setWorktreeRuntimeMeta(false);
+ await renderPage();
+
+ const headings = [...container.querySelectorAll("section h2")].map((h) => h.textContent);
+ expect(headings).not.toContain("Run tasks in this worktree");
+ expect(container.querySelector(WORKTREE_RUN_EXECUTION_TOGGLE_SELECTOR)).toBeNull();
+ });
+
+ it("renders and patches the worktree run-execution toggle when in a worktree", async () => {
+ setWorktreeRuntimeMeta(true);
+ await renderPage();
+
+ expect(container.textContent).toContain("Run tasks in this worktree");
+ expect(container.textContent).toContain(
+ "isolated git-worktree preview instance",
+ );
+
+ const toggle = container.querySelector<HTMLButtonElement>(WORKTREE_RUN_EXECUTION_TOGGLE_SELECTOR);
+ expect(toggle?.getAttribute("aria-checked")).toBe("false");
+
+ await act(async () => {
+ toggle?.click();
+ });
+ await flushReact();
+
+ expect(mockInstanceSettingsApi.updateExperimental).toHaveBeenCalledWith({
+ enableWorktreeRunExecution: true,
+ });
+ expect(toggle?.getAttribute("aria-checked")).toBe("true");
+ });
+
it("renders and patches the Server Info Debug View experimental toggle", async () => {
await renderPage();
diff --git a/ui/src/pages/InstanceExperimentalSettings.tsx b/ui/src/pages/InstanceExperimentalSettings.tsx
index 7a0eecbdfd..5aa72810f2 100644
--- a/ui/src/pages/InstanceExperimentalSettings.tsx
+++ b/ui/src/pages/InstanceExperimentalSettings.tsx
@@ -7,6 +7,7 @@ import type {
PatchInstanceExperimentalSettings,
} from "@paperclipai/shared";
import { instanceSettingsApi } from "@/api/instanceSettings";
+import { isWorktreeRuntime } from "../lib/worktree-branding";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { queryKeys } from "../lib/queryKeys";
import { ToggleSwitch } from "@/components/ui/toggle-switch";
@@ -231,6 +232,8 @@ export function InstanceExperimentalSettings() {
);
}
+ const inWorktree = isWorktreeRuntime();
+ const enableWorktreeRunExecution = experimentalQuery.data?.enableWorktreeRunExecution === true;
const enableEnvironments = experimentalQuery.data?.enableEnvironments === true;
const enableIsolatedWorkspaces = experimentalQuery.data?.enableIsolatedWorkspaces === true;
// Streamlined left navigation is now the standard sidebar (PAP-12472); the
@@ -318,6 +321,29 @@ export function InstanceExperimentalSettings() {
</div>
)}
+ {inWorktree ? (
+ <Card className="block p-5">
+ <div className="flex items-start justify-between gap-4">
+ <div className="space-y-1.5">
+ <h2 className="text-sm font-semibold">Run tasks in this worktree</h2>
+ <p className="max-w-2xl text-sm text-muted-foreground">
+ This is an isolated git-worktree preview instance. By default it does not execute agent runs; tasks stay
+ queued so previews never self-run work. Turn this on to let the heartbeat scheduler execute runs here.
+ This setting only affects this worktree instance and is ignored outside a worktree.
+ </p>
+ </div>
+ <ToggleSwitch
+ checked={enableWorktreeRunExecution}
+ onCheckedChange={(checked) =>
+ toggleMutation.mutate({ enableWorktreeRunExecution: checked })
+ }
+ disabled={toggleMutation.isPending}
+ aria-label="Toggle worktree run execution setting"
+ />
+ </div>
+ </Card>
+ ) : null}
+
<Card className="block p-5">
<div className="flex items-start justify-between gap-4">
<div className="space-y-1.5">
diff --git a/ui/src/pages/SkillStudio.test.tsx b/ui/src/pages/SkillStudio.test.tsx
new file mode 100644
index 0000000000..6c13216750
--- /dev/null
+++ b/ui/src/pages/SkillStudio.test.tsx
@@ -0,0 +1,580 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type {
+ CompanySkillDetail,
+ CompanySkillLastEditor,
+ CompanySkillListItem,
+} from "@paperclipai/shared";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SkillStudio } from "./SkillStudio";
+
+const routeState = vi.hoisted(() => ({
+ pathname: "/skills/studio/new",
+ search: "",
+ skillId: "new" as string | undefined,
+}));
+
+const mockNavigate = vi.hoisted(() => vi.fn());
+const mockSetBreadcrumbs = vi.hoisted(() => vi.fn());
+
+const mockCompanySkillsApi = vi.hoisted(() => ({
+ list: vi.fn(),
+ detail: vi.fn(),
+ create: vi.fn(),
+ file: vi.fn(),
+ updateFile: vi.fn(),
+ deleteFile: vi.fn(),
+ testInputs: vi.fn(),
+ updateTestInput: vi.fn(),
+ deleteTestInput: vi.fn(),
+ createTestInput: vi.fn(),
+ testRunTemplates: vi.fn(),
+ testRuns: vi.fn(),
+ createTestRunTemplate: vi.fn(),
+ updateTestRunTemplate: vi.fn(),
+ deleteTestRunTemplate: vi.fn(),
+ createTestRun: vi.fn(),
+ testRunDetail: vi.fn(),
+ cancelTestRun: vi.fn(),
+ deleteTestRun: vi.fn(),
+ versions: vi.fn(),
+ createVersion: vi.fn(),
+}));
+const mockAgentsApi = vi.hoisted(() => ({
+ list: vi.fn(),
+}));
+const mockIssuesApi = vi.hoisted(() => ({
+ listInteractions: vi.fn(),
+ acceptInteraction: vi.fn(),
+ respondToInteraction: vi.fn(),
+ rejectInteraction: vi.fn(),
+}));
+
+vi.mock("@/lib/router", () => ({
+ Link: ({ children, to, ...props }: { children: ReactNode; to: string }) => (
+ <a href={to} {...props}>{children}</a>
+ ),
+ useLocation: () => ({ pathname: routeState.pathname, search: routeState.search, hash: "" }),
+ useNavigate: () => mockNavigate,
+ useParams: () => ({ skillId: routeState.skillId }),
+ useSearchParams: () => [new URLSearchParams(routeState.search), vi.fn()],
+}));
+
+vi.mock("@/context/BreadcrumbContext", () => ({
+ useBreadcrumbs: () => ({ setBreadcrumbs: mockSetBreadcrumbs }),
+}));
+
+vi.mock("../context/CompanyContext", () => ({
+ useCompany: () => ({ selectedCompanyId: "company-1" }),
+}));
+
+vi.mock("@/api/companySkills", () => ({
+ companySkillsApi: mockCompanySkillsApi,
+}));
+
+vi.mock("@/api/agents", () => ({
+ agentsApi: mockAgentsApi,
+}));
+
+vi.mock("@/api/issues", () => ({
+ issuesApi: mockIssuesApi,
+}));
+
+vi.mock("@/components/SearchableSelect", () => ({
+ SearchableSelect: ({
+ placeholder,
+ renderValue,
+ }: {
+ placeholder: string;
+ renderValue?: (option: null) => ReactNode;
+ }) => <button type="button">{renderValue ? renderValue(null) : placeholder}</button>,
+}));
+
+vi.mock("@/components/MarkdownEditor", () => ({
+ MarkdownEditor: ({ value }: { value: string }) => <textarea readOnly value={value} />,
+}));
+
+vi.mock("@/components/MarkdownBody", () => ({
+ MarkdownBody: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+
+vi.mock("@/components/ui/resizable-panels", () => ({
+ ResizablePanelGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ ResizablePanel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ ResizableHandle: () => <div />,
+}));
+
+vi.mock("./CompanySkills", () => ({
+ SkillCardIcon: ({ card }: { card: { name: string } }) => (
+ <div data-testid="skill-card-icon">{card.name}</div>
+ ),
+}));
+
+// 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;
+}
+
+async function flushReact() {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+}
+
+async function waitFor(assertion: () => void) {
+ let lastError: unknown;
+ for (let attempt = 0; attempt < 25; attempt += 1) {
+ try {
+ assertion();
+ return;
+ } catch (error) {
+ lastError = error;
+ await flushReact();
+ }
+ }
+ throw lastError;
+}
+
+async function renderStudio() {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+
+ await act(async () => {
+ root?.render(
+ <QueryClientProvider client={queryClient}>
+ <SkillStudio />
+ </QueryClientProvider>,
+ );
+ });
+
+ return container;
+}
+
+async function inputValue(input: HTMLInputElement | HTMLTextAreaElement, value: string) {
+ await act(async () => {
+ const proto = input instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
+ const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
+ setter?.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+async function click(button: HTMLButtonElement) {
+ await act(async () => {
+ button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+}
+
+function makeSkill(overrides: Partial<CompanySkillDetail> = {}): CompanySkillDetail {
+ return {
+ id: "source-skill",
+ companyId: "company-1",
+ key: "paperclip/demo-skill",
+ slug: "demo-skill",
+ name: "Demo Skill",
+ description: "A demo skill.",
+ markdown: "---\nname: Demo Skill\ndescription: Existing\n---\n\n# Demo Skill\n",
+ sourceType: "local_path",
+ sourceLocator: null,
+ sourceRef: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ iconUrl: null,
+ color: null,
+ tagline: "Existing tagline",
+ authorName: null,
+ homepageUrl: null,
+ categories: ["engineering"],
+ sharingScope: "company",
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 0,
+ installCount: 0,
+ forkCount: 0,
+ currentVersionId: null,
+ 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: null,
+ starredByCurrentActor: false,
+ existingForks: [],
+ ...overrides,
+ };
+}
+
+function buttonsNamed(node: ParentNode, name: string) {
+ return Array.from(node.querySelectorAll("button")).filter((button) =>
+ button.textContent?.trim() === name,
+ );
+}
+
+beforeEach(() => {
+ routeState.pathname = "/skills/studio/new";
+ routeState.search = "";
+ routeState.skillId = "new";
+ mockNavigate.mockReset();
+ mockSetBreadcrumbs.mockReset();
+ mockCompanySkillsApi.list.mockResolvedValue([]);
+ mockCompanySkillsApi.detail.mockResolvedValue(makeSkill());
+ mockCompanySkillsApi.create.mockResolvedValue({
+ id: "created-skill",
+ name: "Code Review",
+ forkedFromSkillId: null,
+ });
+ mockCompanySkillsApi.file.mockResolvedValue({
+ path: "SKILL.md",
+ content: "---\nname: Demo Skill\ndescription: Existing\n---\n\n# Demo Skill\n",
+ markdown: true,
+ editable: true,
+ editableReason: null,
+ });
+ mockCompanySkillsApi.updateFile.mockResolvedValue({
+ path: "SKILL.md",
+ content: "---\nname: Demo Skill\ndescription: Existing\n---\n\n# Demo Skill\n",
+ markdown: true,
+ editable: true,
+ editableReason: null,
+ });
+ mockCompanySkillsApi.deleteFile.mockResolvedValue({ deletedPaths: [] });
+ mockCompanySkillsApi.testInputs.mockResolvedValue([]);
+ mockCompanySkillsApi.updateTestInput.mockResolvedValue({ id: "input-1", name: "input.md", content: "" });
+ mockCompanySkillsApi.deleteTestInput.mockResolvedValue({ id: "input-1" });
+ mockCompanySkillsApi.createTestInput.mockResolvedValue({ id: "input-1", name: "input.md", content: "" });
+ mockCompanySkillsApi.testRunTemplates.mockResolvedValue([]);
+ mockCompanySkillsApi.testRuns.mockResolvedValue([]);
+ mockCompanySkillsApi.createTestRunTemplate.mockResolvedValue({ id: "template-1", name: "Template" });
+ mockCompanySkillsApi.updateTestRunTemplate.mockResolvedValue({ id: "template-1", name: "Template" });
+ mockCompanySkillsApi.deleteTestRunTemplate.mockResolvedValue({ id: "template-1", name: "Template" });
+ mockCompanySkillsApi.createTestRun.mockResolvedValue({ id: "run-1", status: "queued" });
+ mockCompanySkillsApi.testRunDetail.mockResolvedValue(null);
+ mockCompanySkillsApi.cancelTestRun.mockResolvedValue({ id: "run-1", status: "cancelled" });
+ mockCompanySkillsApi.deleteTestRun.mockResolvedValue({ id: "run-1" });
+ mockCompanySkillsApi.versions.mockResolvedValue([]);
+ mockCompanySkillsApi.createVersion.mockResolvedValue({ id: "version-1" });
+ mockAgentsApi.list.mockResolvedValue([]);
+ mockIssuesApi.listInteractions.mockResolvedValue([]);
+ mockIssuesApi.acceptInteraction.mockResolvedValue({});
+ mockIssuesApi.respondToInteraction.mockResolvedValue({});
+ mockIssuesApi.rejectInteraction.mockResolvedValue({});
+});
+
+afterEach(() => {
+ root?.unmount();
+ root = null;
+ container?.remove();
+ container = null;
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+describe("SkillStudio create mode", () => {
+ it("renders /skills/studio/new as create mode instead of loading skill id new", async () => {
+ const node = await renderStudio();
+
+ await waitFor(() => expect(node.textContent).toContain("Create a new skill"));
+
+ expect(node.textContent).not.toContain("Skill not found.");
+ expect(mockCompanySkillsApi.detail).not.toHaveBeenCalledWith("company-1", "new");
+ expect(mockSetBreadcrumbs).toHaveBeenCalledWith([
+ { label: "Skills", href: "/skills" },
+ { label: "Studio", href: "/skills/studio" },
+ { label: "New skill" },
+ ]);
+ });
+
+ it("prefills fork drafts from the forkFrom query param", async () => {
+ routeState.search = "?forkFrom=source-skill";
+
+ const node = await renderStudio();
+
+ await waitFor(() => expect(node.textContent).toContain("Forking Demo Skill"));
+
+ expect(mockCompanySkillsApi.detail).toHaveBeenCalledWith("company-1", "source-skill");
+ expect((node.querySelector("#skill-name") as HTMLInputElement).value).toBe("Demo Skill Fork");
+ expect((node.querySelector("#skill-slug") as HTMLInputElement).value).toBe("demo-skill-fork");
+ });
+
+ it("creates a skill and navigates to the Studio editor for the new id", async () => {
+ const node = await renderStudio();
+
+ await waitFor(() => expect(node.querySelector("#skill-name")).toBeTruthy());
+ await inputValue(node.querySelector("#skill-name") as HTMLInputElement, "Code Review");
+ await click(buttonsNamed(node, "Create skill")[0] as HTMLButtonElement);
+
+ await waitFor(() => expect(mockCompanySkillsApi.create).toHaveBeenCalled());
+
+ expect(mockCompanySkillsApi.create).toHaveBeenCalledWith(
+ "company-1",
+ expect.objectContaining({
+ name: "Code Review",
+ slug: "code-review",
+ sharingScope: "company",
+ forkedFromSkillId: null,
+ }),
+ );
+ await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith("/skills/studio/created-skill"));
+ });
+
+ it("keeps category commas and spaces editable while creating a skill", async () => {
+ const node = await renderStudio();
+
+ await waitFor(() => expect(node.querySelector("#skill-categories")).toBeTruthy());
+ await inputValue(node.querySelector("#skill-name") as HTMLInputElement, "Code Review");
+ await inputValue(node.querySelector("#skill-categories") as HTMLInputElement, "AI Tools, Developer Experience, ");
+
+ expect((node.querySelector("#skill-categories") as HTMLInputElement).value).toBe("AI Tools, Developer Experience, ");
+
+ await click(buttonsNamed(node, "Create skill")[0] as HTMLButtonElement);
+ await waitFor(() => expect(mockCompanySkillsApi.create).toHaveBeenCalled());
+
+ expect(mockCompanySkillsApi.create).toHaveBeenCalledWith(
+ "company-1",
+ expect.objectContaining({
+ categories: ["AI Tools", "Developer Experience"],
+ }),
+ );
+ });
+});
+
+function makeListItem(
+ overrides: Partial<CompanySkillListItem> & { id: string },
+): CompanySkillListItem {
+ return {
+ companyId: "company-1",
+ key: overrides.id,
+ slug: overrides.id,
+ name: overrides.id,
+ description: null,
+ sourceType: "local_path",
+ sourceLocator: null,
+ sourceRef: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [],
+ 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: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ updatedAt: new Date("2026-01-01T00:00:00Z"),
+ attachedAgentCount: 0,
+ editable: true,
+ editableReason: null,
+ sourceLabel: null,
+ sourceBadge: "local",
+ sourcePath: null,
+ catalogKind: null,
+ originHash: null,
+ packageName: null,
+ packageVersion: null,
+ ...overrides,
+ };
+}
+
+const userEditor = (name: string): CompanySkillLastEditor => ({
+ kind: "user",
+ id: `user-${name}`,
+ name,
+ imageUrl: null,
+});
+const agentEditor: CompanySkillLastEditor = {
+ kind: "agent",
+ id: "agent-1",
+ name: "Bot",
+ imageUrl: null,
+};
+
+function findRowButton(node: ParentNode, name: string): HTMLButtonElement | undefined {
+ return Array.from(node.querySelectorAll("button")).find((button) =>
+ button.textContent?.includes(name),
+ ) as HTMLButtonElement | undefined;
+}
+
+describe("SkillStudio landing", () => {
+ beforeEach(() => {
+ routeState.pathname = "/skills/studio";
+ routeState.search = "";
+ routeState.skillId = undefined;
+ localStorage.clear();
+ });
+
+ it("renders recently-visited and recently-updated sections, gating avatars to humans", async () => {
+ localStorage.setItem("paperclip:recent-studio-skills", JSON.stringify(["visited-1"]));
+ mockCompanySkillsApi.list.mockResolvedValue([
+ makeListItem({
+ id: "visited-1",
+ name: "Visited One",
+ updatedAt: new Date("2026-01-01T00:00:00Z"),
+ lastEditor: userEditor("Ada Lovelace"),
+ }),
+ makeListItem({
+ id: "agent-updated",
+ name: "Agent Updated",
+ updatedAt: new Date("2026-03-01T00:00:00Z"),
+ lastEditor: agentEditor,
+ }),
+ makeListItem({
+ id: "user-updated",
+ name: "User Updated",
+ updatedAt: new Date("2026-02-01T00:00:00Z"),
+ lastEditor: userEditor("Grace Hopper"),
+ }),
+ ]);
+
+ const node = await renderStudio();
+
+ await waitFor(() => expect(node.textContent).toContain("Recently visited"));
+ expect(node.textContent).toContain("Recently updated");
+
+ // Visited section surfaces the visited skill; updated section excludes it.
+ const visitedSection = Array.from(node.querySelectorAll("section")).find((s) =>
+ s.querySelector("h2")?.textContent === "Recently visited",
+ )!;
+ const updatedSection = Array.from(node.querySelectorAll("section")).find((s) =>
+ s.querySelector("h2")?.textContent === "Recently updated",
+ )!;
+ expect(visitedSection.textContent).toContain("Visited One");
+ expect(updatedSection.textContent).not.toContain("Visited One");
+ expect(updatedSection.textContent).toContain("Agent Updated");
+ expect(updatedSection.textContent).toContain("User Updated");
+
+ // Only the two human-edited rows render an avatar (initials fallback); the
+ // agent-edited row renders none.
+ const initials = Array.from(node.querySelectorAll('[data-slot="avatar-fallback"]')).map(
+ (el) => el.textContent,
+ );
+ expect(initials).toEqual(["AL", "GH"]);
+ });
+
+ it("opens the clicked skill in Studio", async () => {
+ mockCompanySkillsApi.list.mockResolvedValue([
+ makeListItem({ id: "user-updated", name: "User Updated", lastEditor: userEditor("Grace Hopper") }),
+ ]);
+
+ const node = await renderStudio();
+
+ await waitFor(() => expect(node.textContent).toContain("User Updated"));
+ const row = findRowButton(node, "User Updated")!;
+ await click(row);
+
+ expect(mockNavigate).toHaveBeenCalledWith(expect.stringContaining("user-updated"));
+ });
+
+ it("falls back to the empty state when there are no skills", async () => {
+ mockCompanySkillsApi.list.mockResolvedValue([]);
+
+ const node = await renderStudio();
+
+ await waitFor(() => expect(node.textContent).toContain("Select a skill to open Studio."));
+ expect(node.textContent).toContain("Create a new skill");
+ expect(node.textContent).not.toContain("Recently updated");
+ });
+
+ it("shows the loading fallback while skills load", async () => {
+ mockCompanySkillsApi.list.mockReturnValue(new Promise(() => {}));
+
+ const node = await renderStudio();
+
+ await waitFor(() => expect(node.textContent).toContain("Loading skills..."));
+ });
+});
+
+describe("SkillStudio editor frontmatter", () => {
+ beforeEach(() => {
+ routeState.pathname = "/skills/studio/source-skill";
+ routeState.search = "";
+ routeState.skillId = "source-skill";
+ });
+
+ it("does not show the frontmatter section when the selected markdown file has no frontmatter", async () => {
+ mockCompanySkillsApi.file.mockResolvedValueOnce({
+ path: "SKILL.md",
+ content: "# Demo Skill\n\nNo YAML block here.\n",
+ markdown: true,
+ editable: true,
+ editableReason: null,
+ });
+
+ const node = await renderStudio();
+
+ await waitFor(() => {
+ expect(mockCompanySkillsApi.file).toHaveBeenCalledWith("company-1", "source-skill", "SKILL.md");
+ });
+ await waitFor(() => {
+ const textareas = Array.from(node.querySelectorAll("textarea"));
+ expect(textareas.some((textarea) => textarea.value.includes("No YAML block here."))).toBe(true);
+ });
+
+ expect(node.querySelector('[data-testid="frontmatter-panel"]')).toBeNull();
+ expect(node.textContent).not.toContain("Add frontmatter");
+ });
+
+ it("shows existing frontmatter collapsed by default", async () => {
+ const node = await renderStudio();
+
+ await waitFor(() => {
+ expect(node.querySelector('[data-testid="frontmatter-panel"]')).toBeTruthy();
+ });
+
+ const toggle = node.querySelector<HTMLButtonElement>('button[aria-controls="frontmatter-panel-body"]');
+ expect(toggle?.getAttribute("aria-expanded")).toBe("false");
+ expect(node.querySelector("#fm-name")).toBeNull();
+ });
+
+ it("offers an 'Edit a copy' CTA on the read-only banner (PAP-13112)", async () => {
+ mockCompanySkillsApi.detail.mockResolvedValueOnce(makeSkill({
+ editable: false,
+ editableReason: "Bundled skill.",
+ }));
+
+ const node = await renderStudio();
+
+ await waitFor(() => expect(node.textContent).toContain("Bundled skill."));
+
+ // The dead-end "Fork" text link is replaced by a primary "Edit a copy"
+ // button that opens the fork-confirm dialog (agent-switch flow).
+ const editCopy = Array.from(node.querySelectorAll("button")).find(
+ (button) => button.textContent?.trim() === "Edit a copy",
+ );
+ expect(editCopy).toBeTruthy();
+ const staleForkLink = Array.from(node.querySelectorAll("a")).find((link) =>
+ link.getAttribute("href")?.includes("/skills/studio/new?forkFrom"),
+ );
+ expect(staleForkLink).toBeUndefined();
+ });
+});
diff --git a/ui/src/pages/SkillStudio.tsx b/ui/src/pages/SkillStudio.tsx
new file mode 100644
index 0000000000..57ffe0e181
--- /dev/null
+++ b/ui/src/pages/SkillStudio.tsx
@@ -0,0 +1,3577 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ AlertTriangle,
+ ArrowLeft,
+ ChevronDown,
+ ChevronRight,
+ Clock,
+ Copy,
+ FileCode,
+ FilePlus,
+ FileText,
+ FolderMinus,
+ FolderPlus,
+ FlaskConical,
+ GitFork,
+ History,
+ MoreHorizontal,
+ Pencil,
+ Play,
+ Plus,
+ RotateCcw,
+ Share2,
+ Trash2,
+} from "lucide-react";
+import type {
+ Agent,
+ CompanySkillDetail,
+ CompanySkillListItem,
+ CompanySkillTestInput,
+ CompanySkillTestRun,
+ CompanySkillTestRunDetail,
+ CompanySkillTestRunTemplate,
+ CompanySkillTestRunTemplateCreateRequest,
+ CompanySkillTestRunTemplateUpdateRequest,
+ CompanySkillVersion,
+ IssueDocument,
+ IssueThreadInteraction,
+ AskUserQuestionsInteraction,
+ AskUserQuestionsAnswer,
+} from "@paperclipai/shared";
+import { Link, useLocation, useNavigate, useParams, useSearchParams } from "@/lib/router";
+import {
+ SearchableSelect,
+ type SearchableSelectGroup,
+ type SearchableSelectOption,
+} from "@/components/SearchableSelect";
+import { useBreadcrumbs } from "@/context/BreadcrumbContext";
+import { useCompany } from "../context/CompanyContext";
+import { useOptionalToastActions } from "../context/ToastContext";
+import { agentsApi } from "@/api/agents";
+import { companySkillsApi } from "@/api/companySkills";
+import { issuesApi } from "@/api/issues";
+import { queryKeys } from "@/lib/queryKeys";
+import { copyTextToClipboard } from "@/lib/clipboard";
+import { skillStudioNewRoute, skillStudioRoute } from "@/lib/company-skill-routes";
+import {
+ buildBlankSkillDraft,
+ buildForkSkillDraft,
+ defaultSkillMarkdown,
+ normalizeSkillDraftSlug,
+ SKILL_CREATE_ACCENTS,
+ skillAccentColor,
+ skillCreateDraftToPayload,
+ splitCategoryDraft,
+ type SkillCreateDraft,
+} from "@/lib/skill-create";
+import { getRecentStudioSkillIds, trackRecentStudioSkill } from "@/lib/recent-skills";
+import { AgentsUsingSkillBadge } from "@/components/skill-studio/AgentsUsingSkillDialog";
+import { ForkSkillDialog } from "@/components/skill-studio/ForkSkillDialog";
+import {
+ ProjectScanNotice,
+ SkillLineageChip,
+} from "@/components/skill-studio/SkillProvenance";
+import { isProjectScanSkill } from "@/lib/skill-fork";
+import { cn, formatCents, relativeTime } from "@/lib/utils";
+import { SkillCardIcon, type DiscoveryCard } from "./CompanySkills";
+import {
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+} from "@/components/ui/resizable-panels";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { Label } from "@/components/ui/label";
+import { Card, CardContent, CardHeader } from "@/components/ui/card";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { FileTree, buildFileTree, type FileTreeNode } from "@/components/FileTree";
+import { MarkdownEditor } from "@/components/MarkdownEditor";
+import { FrontmatterPanel } from "@/components/FrontmatterPanel";
+import { joinFrontmatterBlock, splitFrontmatterBlock } from "@paperclipai/shared";
+import { MarkdownBody } from "@/components/MarkdownBody";
+import { StatusBadge } from "@/components/StatusBadge";
+import { EmptyState } from "@/components/EmptyState";
+import { EntityRow } from "@/components/EntityRow";
+import { FilterBar } from "@/components/FilterBar";
+import { Identity } from "@/components/Identity";
+import { IssueThreadInteractionCard } from "@/components/IssueThreadInteractionCard";
+import { IssueAttachmentsSection } from "@/components/IssueAttachmentsSection";
+import { ImageGalleryModal, type GalleryMediaItem } from "@/components/ImageGalleryModal";
+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
+import { IssueOutputSection } from "@/components/issue-output/IssueOutputSection";
+import { buildLineDiff } from "@/lib/line-diff";
+import {
+ buildCreateRunRequest,
+ buildReRunRequest,
+ DEFAULT_TEST_RUN_TEMPLATE_ID,
+ EMPTY_SAVED_INPUT_DRAFT_STATE,
+ evaluateRunGate,
+ getRunAdditionalDocuments,
+ getRunMediaGalleryItems,
+ getRunRawAttachments,
+ isAgentSelectable,
+ isInteractionAnswerable,
+ isTerminalRunStatus,
+ orderRecentlyUpdatedSkills,
+ orderRecentlyVisitedSkills,
+ skillEditorAvatar,
+ NO_TEST_RUN_TEMPLATE_STORAGE_VALUE,
+ parseRunTemplateSelection,
+ routeInteraction,
+ runBadgeStatus,
+ runHarnessUnavailableCopy,
+ runOutputMode,
+ runShortId,
+ resolveRunTemplateSelection,
+ serializeRunTemplateSelection,
+ savedInputDraftDirty,
+ selectedSavedInputDraft,
+ shouldPollRun,
+ showRunErrorCard,
+ syncSavedInputDraftState,
+ testTaskLinkState,
+ type RunTemplateSelection,
+ type SavedInputDraftState,
+} from "@/lib/skill-studio";
+
+const PANE_STORAGE_KEY = "skillStudio.paneSizes";
+const RUN_TEMPLATE_STORAGE_KEY_PREFIX = "skillStudio.runTemplate";
+const MOBILE_BREAKPOINT = 900;
+const POLL_MS = 2000;
+const EMPTY_RUN_TEMPLATES: CompanySkillTestRunTemplate[] = [];
+
+/**
+ * Surface a mutation rejection as an error toast. Every Studio mutation routes
+ * failures through here so server rejections (409 agent_not_assignable, 422
+ * read-only, …) never get silently swallowed (PAP-13001).
+ */
+function useMutationErrorToast() {
+ const toast = useOptionalToastActions();
+ return useCallback(
+ (title: string) => (error: unknown) => {
+ const body =
+ error instanceof Error && error.message ? error.message : "Please try again.";
+ toast?.pushToast({ tone: "error", title, body });
+ },
+ [toast],
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Pane-size persistence (contract: persist per user `skillStudio.paneSizes`)
+// ---------------------------------------------------------------------------
+
+type PaneLayout = { skill: number; input: number; runs: number };
+const DEFAULT_LAYOUT: PaneLayout = { skill: 37.5, input: 25, runs: 37.5 };
+
+function loadPaneLayout(): PaneLayout {
+ try {
+ const raw = localStorage.getItem(PANE_STORAGE_KEY);
+ if (!raw) return DEFAULT_LAYOUT;
+ const parsed = JSON.parse(raw) as Partial<PaneLayout>;
+ if (
+ typeof parsed?.skill === "number"
+ && typeof parsed?.input === "number"
+ && typeof parsed?.runs === "number"
+ ) {
+ return { skill: parsed.skill, input: parsed.input, runs: parsed.runs };
+ }
+ } catch {
+ /* ignore malformed persisted layout */
+ }
+ return DEFAULT_LAYOUT;
+}
+
+function runTemplateStorageKey(companyId: string) {
+ return `${RUN_TEMPLATE_STORAGE_KEY_PREFIX}.${companyId}`;
+}
+
+function loadRunTemplateSelection(companyId: string): RunTemplateSelection {
+ try {
+ return parseRunTemplateSelection(localStorage.getItem(runTemplateStorageKey(companyId)));
+ } catch {
+ return DEFAULT_TEST_RUN_TEMPLATE_ID;
+ }
+}
+
+function persistRunTemplateSelection(companyId: string, selection: RunTemplateSelection) {
+ try {
+ localStorage.setItem(runTemplateStorageKey(companyId), serializeRunTemplateSelection(selection));
+ } catch {
+ /* storage may be unavailable (private mode) — non-fatal */
+ }
+}
+
+function useIsMobile() {
+ const [isMobile, setIsMobile] = useState(
+ () => typeof window !== "undefined" && window.innerWidth < MOBILE_BREAKPOINT,
+ );
+ useEffect(() => {
+ const onResize = () => setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
+ window.addEventListener("resize", onResize);
+ return () => window.removeEventListener("resize", onResize);
+ }, []);
+ return isMobile;
+}
+
+// ---------------------------------------------------------------------------
+// Root
+// ---------------------------------------------------------------------------
+
+export function SkillStudio() {
+ const { skillId = "" } = useParams<{ skillId: string }>();
+ const location = useLocation();
+ const [searchParams] = useSearchParams();
+ const { selectedCompanyId } = useCompany();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const navigate = useNavigate();
+ const companyId = selectedCompanyId ?? "";
+ const isCreateMode = location.pathname.replace(/\/+$/, "").endsWith("/skills/studio/new");
+ const forkFromSkillId = isCreateMode ? searchParams.get("forkFrom")?.trim() || null : null;
+
+ const skillsQuery = useQuery({
+ queryKey: queryKeys.companySkills.list(companyId),
+ queryFn: () => companySkillsApi.list(companyId, { sort: "alphabetical" }),
+ enabled: Boolean(companyId),
+ });
+
+ const detailQuery = useQuery({
+ queryKey: queryKeys.companySkills.detail(companyId, skillId),
+ queryFn: () => companySkillsApi.detail(companyId, skillId),
+ enabled: Boolean(companyId && skillId && !isCreateMode),
+ });
+ const forkDetailQuery = useQuery({
+ queryKey: queryKeys.companySkills.detail(companyId, forkFromSkillId ?? ""),
+ queryFn: () => companySkillsApi.detail(companyId, forkFromSkillId!),
+ enabled: Boolean(companyId && forkFromSkillId),
+ });
+ const skill = detailQuery.data ?? null;
+
+ useEffect(() => {
+ setBreadcrumbs(
+ isCreateMode
+ ? [
+ { label: "Skills", href: "/skills" },
+ { label: "Studio", href: "/skills/studio" },
+ { label: "New skill" },
+ ]
+ : skill
+ ? [
+ { label: "Skills", href: "/skills" },
+ { label: "Studio", href: "/skills/studio" },
+ { label: skill.name },
+ ]
+ : [
+ { label: "Skills", href: "/skills" },
+ { label: "Studio" },
+ ],
+ );
+ }, [isCreateMode, setBreadcrumbs, skill]);
+
+ // Record a per-browser visit whenever a skill successfully opens, powering the
+ // landing's "Recently visited" section (PAP-13150).
+ useEffect(() => {
+ if (skill?.id) trackRecentStudioSkill(skill.id);
+ }, [skill?.id]);
+
+ if (!companyId) {
+ return <StudioMessage message="Select a company to open Skill Studio." />;
+ }
+ if (isCreateMode) {
+ return (
+ <StudioCreateMode
+ companyId={companyId}
+ skills={skillsQuery.data ?? []}
+ skillsLoading={skillsQuery.isLoading}
+ forkFromSkillId={forkFromSkillId}
+ forkSkill={forkDetailQuery.data ?? null}
+ forkLoading={forkDetailQuery.isLoading}
+ forkError={forkDetailQuery.isError}
+ onSelectSkill={(nextSkillId) => navigate(skillStudioRoute(nextSkillId))}
+ />
+ );
+ }
+ if (!skillId) {
+ return (
+ <StudioLanding
+ companyId={companyId}
+ skills={skillsQuery.data ?? []}
+ skillsLoading={skillsQuery.isLoading}
+ onSelectSkill={(nextSkillId) => navigate(skillStudioRoute(nextSkillId))}
+ onCreateNew={() => navigate(skillStudioNewRoute())}
+ />
+ );
+ }
+ if (detailQuery.isLoading) {
+ return <StudioMessage message="Loading skill…" />;
+ }
+ if (detailQuery.isError || !detailQuery.data) {
+ return <StudioMessage message="Skill not found." />;
+ }
+
+ return (
+ <StudioShell
+ companyId={companyId}
+ skill={detailQuery.data}
+ skills={skillsQuery.data ?? []}
+ skillsLoading={skillsQuery.isLoading}
+ />
+ );
+}
+
+function StudioCreateMode({
+ companyId,
+ skills,
+ skillsLoading,
+ forkFromSkillId,
+ forkSkill,
+ forkLoading,
+ forkError,
+ onSelectSkill,
+}: {
+ companyId: string;
+ skills: CompanySkillListItem[];
+ skillsLoading: boolean;
+ forkFromSkillId: string | null;
+ forkSkill: CompanySkillDetail | null;
+ forkLoading: boolean;
+ forkError: boolean;
+ onSelectSkill: (skillId: string) => void;
+}) {
+ return (
+ <TooltipProvider delayDuration={200}>
+ <div className="flex h-full min-h-0 flex-col">
+ <header className="flex items-center gap-3 border-b border-border px-3 py-2">
+ <SkillSwitcher
+ skill={null}
+ skills={skills}
+ loading={skillsLoading}
+ onSelectSkill={onSelectSkill}
+ emptyLabel="New skill"
+ />
+ </header>
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <StudioNewSkillPanel
+ companyId={companyId}
+ forkFromSkillId={forkFromSkillId}
+ forkSkill={forkSkill}
+ forkLoading={forkLoading}
+ forkError={forkError}
+ />
+ </div>
+ </div>
+ </TooltipProvider>
+ );
+}
+
+function StudioNewSkillPanel({
+ companyId,
+ forkFromSkillId,
+ forkSkill,
+ forkLoading,
+ forkError,
+}: {
+ companyId: string;
+ forkFromSkillId: string | null;
+ forkSkill: CompanySkillDetail | null;
+ forkLoading: boolean;
+ forkError: boolean;
+}) {
+ const navigate = useNavigate();
+ const queryClient = useQueryClient();
+ const toast = useOptionalToastActions();
+ const initialDraft = useMemo(
+ () => (forkSkill ? buildForkSkillDraft(forkSkill) : buildBlankSkillDraft()),
+ [forkSkill],
+ );
+ const [draft, setDraft] = useState<SkillCreateDraft>(initialDraft);
+ const [slugDirty, setSlugDirty] = useState(initialDraft.slug.trim().length > 0);
+ const [categoryDraft, setCategoryDraft] = useState(initialDraft.categories.join(", "));
+ const parsedCategories = splitCategoryDraft(categoryDraft);
+ const effectiveSlug = draft.slug.trim() || normalizeSkillDraftSlug(draft.name);
+ const nameValid = draft.name.trim().length > 0;
+
+ useEffect(() => {
+ setDraft(initialDraft);
+ setSlugDirty(initialDraft.slug.trim().length > 0);
+ setCategoryDraft(initialDraft.categories.join(", "));
+ }, [initialDraft]);
+
+ function patchDraft(patch: Partial<SkillCreateDraft>) {
+ setDraft((current) => ({ ...current, ...patch }));
+ }
+
+ const createSkill = useMutation({
+ mutationFn: () => companySkillsApi.create(companyId, skillCreateDraftToPayload({
+ ...draft,
+ categories: parsedCategories,
+ })),
+ onSuccess: async (skill) => {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(companyId) });
+ toast?.pushToast({
+ tone: "success",
+ title: skill.forkedFromSkillId ? "Skill fork created" : "Skill created",
+ body: `${skill.name} is now editable in the Paperclip workspace.`,
+ });
+ navigate(skillStudioRoute(skill.id));
+ },
+ onError: (error) => {
+ toast?.pushToast({
+ tone: "error",
+ title: "Skill creation failed",
+ body: error instanceof Error ? error.message : "Failed to create skill.",
+ });
+ },
+ });
+
+ if (forkFromSkillId && forkLoading) {
+ return <StudioMessage message="Loading fork source..." />;
+ }
+
+ const previewCard: DiscoveryCard = {
+ key: effectiveSlug || draft.name || "new-skill",
+ skillId: null,
+ catalogRef: null,
+ name: draft.name || "New Skill",
+ slug: effectiveSlug || "skill",
+ author: "you",
+ version: null,
+ tagline: draft.tagline || null,
+ description: draft.tagline,
+ categories: parsedCategories,
+ iconUrl: null,
+ color: draft.color,
+ starCount: 0,
+ agentCount: 0,
+ forkCount: 0,
+ installed: false,
+ required: false,
+ forkedFrom: Boolean(draft.forkedFromSkillId),
+ updatedAt: Date.now(),
+ };
+
+ return (
+ <div className="mx-auto flex w-full max-w-4xl flex-col gap-6 px-4 py-6">
+ <div className="space-y-1">
+ <h1 className="text-lg font-semibold text-foreground">
+ {draft.forkedFromSkillId ? "Fork skill" : "Create a new skill"}
+ </h1>
+ <p className="text-sm text-muted-foreground">
+ Create an editable company skill and open it directly in Studio.
+ </p>
+ </div>
+
+ {draft.forkedFromName ? (
+ <div className="flex items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2 text-sm text-muted-foreground">
+ <GitFork className="h-4 w-4" />
+ Forking {draft.forkedFromName}
+ </div>
+ ) : forkError ? (
+ <div className="flex items-center gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
+ <AlertTriangle className="h-4 w-4" />
+ Fork source not found. You can still create a blank skill.
+ </div>
+ ) : null}
+
+ <section className="space-y-3">
+ <div>
+ <h2 className="text-sm font-medium text-foreground">Basics</h2>
+ <p className="text-xs text-muted-foreground">Name the skill and set the route-safe slug.</p>
+ </div>
+ <div className="grid gap-3 md:grid-cols-2">
+ <div className="space-y-1.5">
+ <Label htmlFor="skill-name">Name</Label>
+ <Input
+ id="skill-name"
+ 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="Code review"
+ />
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="skill-slug">Slug</Label>
+ <Input
+ id="skill-slug"
+ value={draft.slug}
+ onChange={(event) => {
+ const nextSlug = normalizeSkillDraftSlug(event.target.value);
+ setSlugDirty(nextSlug.length > 0);
+ patchDraft({ slug: nextSlug });
+ }}
+ placeholder="code-review"
+ className="font-mono"
+ />
+ </div>
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="skill-tagline">Tagline</Label>
+ <Textarea
+ id="skill-tagline"
+ 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="Review repository changes for correctness, tests, and maintainability."
+ className="min-h-20"
+ />
+ </div>
+ </section>
+
+ <section className="space-y-3">
+ <div>
+ <h2 className="text-sm font-medium text-foreground">Appearance</h2>
+ <p className="text-xs text-muted-foreground">Tune how the skill appears in the store and Studio switcher.</p>
+ </div>
+ <div className="flex items-center gap-3">
+ <SkillCardIcon card={previewCard} size={48} />
+ <div className="min-w-0">
+ <div className="truncate text-sm font-medium">{previewCard.name}</div>
+ <div className="truncate text-xs text-muted-foreground">{draft.tagline || "No tagline yet."}</div>
+ </div>
+ </div>
+ <div className="space-y-2">
+ <Label>Color</Label>
+ <div className="flex flex-wrap items-center gap-2">
+ {SKILL_CREATE_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
+ aria-label="Hex color"
+ value={draft.color}
+ onChange={(event) => patchDraft({ color: event.target.value })}
+ className="h-7 w-28 font-mono text-xs"
+ />
+ </div>
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="skill-categories">Categories</Label>
+ <Input
+ id="skill-categories"
+ value={categoryDraft}
+ onChange={(event) => setCategoryDraft(event.target.value)}
+ placeholder="engineering, review, memory"
+ />
+ </div>
+ </section>
+
+ <section className="space-y-3">
+ <div>
+ <h2 className="text-sm font-medium text-foreground">Sharing</h2>
+ <p className="text-xs text-muted-foreground">Choose who can discover this skill inside Paperclip.</p>
+ </div>
+ <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</span>
+ <span className="mt-1 block text-xs">Coming later.</span>
+ </button>
+ </div>
+ </section>
+
+ <details className="rounded-md border border-border px-3 py-2">
+ <summary className="cursor-pointer text-sm font-medium text-foreground">Starter content</summary>
+ <Textarea
+ value={draft.markdown}
+ onChange={(event) => patchDraft({ markdown: event.target.value })}
+ className="mt-3 min-h-(--sz-22rem) resize-y font-mono text-xs"
+ />
+ </details>
+
+ <div className="flex items-center justify-end gap-2 border-t border-border pt-4">
+ <Button variant="ghost" onClick={() => navigate("/skills/studio")} disabled={createSkill.isPending}>
+ Cancel
+ </Button>
+ <Button onClick={() => createSkill.mutate()} disabled={createSkill.isPending || !nameValid}>
+ <FilePlus className="h-4 w-4" />
+ {createSkill.isPending ? "Creating..." : draft.forkedFromSkillId ? "Create fork" : "Create skill"}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function StudioMessage({ message }: { message: string }) {
+ return (
+ <div className="flex h-full min-h-(--sz-60vh) items-center justify-center text-sm text-muted-foreground">
+ {message}
+ </div>
+ );
+}
+
+function StudioEmptyState({
+ skills,
+ skillsLoading,
+ onSelectSkill,
+ onCreateNew,
+}: {
+ skills: CompanySkillListItem[];
+ skillsLoading: boolean;
+ onSelectSkill: (skillId: string) => void;
+ onCreateNew: () => void;
+}) {
+ return (
+ <TooltipProvider delayDuration={200}>
+ <div className="flex h-full min-h-0 flex-col">
+ <header className="flex items-center gap-3 border-b border-border px-3 py-2">
+ <SkillSwitcher
+ skill={null}
+ skills={skills}
+ loading={skillsLoading}
+ onSelectSkill={onSelectSkill}
+ emptyLabel="Select skill"
+ />
+ </header>
+ <div className="flex flex-1 items-center justify-center">
+ <EmptyState
+ icon={FileCode}
+ message={skillsLoading ? "Loading skills..." : "Select a skill to open Studio."}
+ action="Create a new skill"
+ onAction={onCreateNew}
+ />
+ </div>
+ </div>
+ </TooltipProvider>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Landing — recently visited + recently updated (PAP-13150)
+// ---------------------------------------------------------------------------
+
+function StudioLanding({
+ companyId,
+ skills,
+ skillsLoading,
+ onSelectSkill,
+ onCreateNew,
+}: {
+ companyId: string;
+ skills: CompanySkillListItem[];
+ skillsLoading: boolean;
+ onSelectSkill: (skillId: string) => void;
+ onCreateNew: () => void;
+}) {
+ // Recency-sorted list, enriched with the last human editor (PAP-13149) — the
+ // source for both landing sections. Kept separate from the alphabetical
+ // switcher list so each cache stays sorted the way its consumer expects.
+ const recentQuery = useQuery({
+ queryKey: queryKeys.companySkills.listRecent(companyId),
+ queryFn: () => companySkillsApi.list(companyId, { sort: "recent", include: ["lastEditor"] }),
+ enabled: Boolean(companyId),
+ });
+ const recentSkills = recentQuery.data ?? [];
+
+ const visited = useMemo(
+ () => orderRecentlyVisitedSkills(recentSkills, getRecentStudioSkillIds()),
+ [recentSkills],
+ );
+ const updated = useMemo(
+ () => orderRecentlyUpdatedSkills(recentSkills, visited.map((skill) => skill.id)),
+ [recentSkills, visited],
+ );
+
+ // No skills at all (or still loading) -> today's empty/loading fallback.
+ if (recentSkills.length === 0) {
+ return (
+ <StudioEmptyState
+ skills={skills}
+ skillsLoading={skillsLoading || recentQuery.isLoading}
+ onSelectSkill={onSelectSkill}
+ onCreateNew={onCreateNew}
+ />
+ );
+ }
+
+ return (
+ <TooltipProvider delayDuration={200}>
+ <div className="flex h-full min-h-0 flex-col">
+ <header className="flex items-center gap-3 border-b border-border px-3 py-2">
+ <SkillSwitcher
+ skill={null}
+ skills={skills}
+ loading={skillsLoading}
+ onSelectSkill={onSelectSkill}
+ emptyLabel="Select skill"
+ />
+ <Button variant="ghost" size="sm" className="ml-auto" onClick={onCreateNew}>
+ <Plus className="mr-1.5 h-3.5 w-3.5" />
+ New skill
+ </Button>
+ </header>
+ <div className="min-h-0 flex-1 overflow-auto">
+ <div className="mx-auto w-full max-w-3xl space-y-8 px-4 py-8">
+ {visited.length > 0 ? (
+ <StudioLandingSection
+ title="Recently visited"
+ skills={visited}
+ onSelectSkill={onSelectSkill}
+ />
+ ) : null}
+ <StudioLandingSection
+ title="Recently updated"
+ skills={updated}
+ onSelectSkill={onSelectSkill}
+ />
+ </div>
+ </div>
+ </div>
+ </TooltipProvider>
+ );
+}
+
+function StudioLandingSection({
+ title,
+ skills,
+ onSelectSkill,
+}: {
+ title: string;
+ skills: CompanySkillListItem[];
+ onSelectSkill: (skillId: string) => void;
+}) {
+ if (skills.length === 0) return null;
+ return (
+ <section className="space-y-2">
+ <h2 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ {title}
+ </h2>
+ <div className="divide-y divide-border overflow-hidden rounded-md border border-border">
+ {skills.map((skill) => (
+ <StudioLandingRow
+ key={skill.id}
+ skill={skill}
+ onSelect={() => onSelectSkill(skill.id)}
+ />
+ ))}
+ </div>
+ </section>
+ );
+}
+
+function StudioLandingRow({
+ skill,
+ onSelect,
+}: {
+ skill: CompanySkillListItem;
+ onSelect: () => void;
+}) {
+ const editor = skillEditorAvatar(skill.lastEditor);
+ return (
+ <button
+ type="button"
+ onClick={onSelect}
+ className="flex w-full items-center gap-3 px-3 py-2.5 text-left hover:bg-accent"
+ >
+ <SkillLandingIcon skill={skill} />
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-sm font-medium">{skill.name}</span>
+ {skill.tagline ? (
+ <span className="truncate text-xs text-muted-foreground">{skill.tagline}</span>
+ ) : null}
+ </span>
+ <span className="shrink-0 text-xs text-muted-foreground">
+ updated {relativeTime(skill.updatedAt)}
+ </span>
+ {editor ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Avatar size="xs">
+ {editor.imageUrl ? <AvatarImage src={editor.imageUrl} alt="" /> : null}
+ <AvatarFallback>{editor.initials}</AvatarFallback>
+ </Avatar>
+ </TooltipTrigger>
+ <TooltipContent>{editor.name}</TooltipContent>
+ </Tooltip>
+ ) : (
+ <span className="w-5 shrink-0" aria-hidden="true" />
+ )}
+ </button>
+ );
+}
+
+function SkillLandingIcon({ skill }: { skill: CompanySkillListItem }) {
+ if (skill.iconUrl) {
+ return (
+ <img
+ src={skill.iconUrl}
+ alt=""
+ className="h-9 w-9 shrink-0 rounded-md object-cover"
+ />
+ );
+ }
+ const accent = skillAccentColor(skill.key, skill.color);
+ const letter = (skill.slug || skill.name || "?").trim().charAt(0).toUpperCase();
+ return (
+ <span
+ aria-hidden="true"
+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-sm font-semibold text-white"
+ style={{ backgroundColor: accent }}
+ >
+ {letter}
+ </span>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Shell — header + three panes (or mobile tabs)
+// ---------------------------------------------------------------------------
+
+function StudioShell({
+ companyId,
+ skill,
+ skills,
+ skillsLoading,
+}: {
+ companyId: string;
+ skill: CompanySkillDetail;
+ skills: CompanySkillListItem[];
+ skillsLoading: boolean;
+}) {
+ const skillId = skill.id;
+ const isMobile = useIsMobile();
+ const [searchParams, setSearchParams] = useSearchParams();
+ const navigate = useNavigate();
+ const queryClient = useQueryClient();
+
+ // --- selection / cross-pane state ---
+ const [selectedInputId, setSelectedInputId] = useState<string | null>(
+ () => searchParams.get("input"),
+ );
+ const [selectedRunId, setSelectedRunId] = useState<string | null>(
+ () => searchParams.get("run"),
+ );
+ const [adHocMode, setAdHocMode] = useState(false);
+ const [adHocContent, setAdHocContent] = useState("");
+ const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
+ const [skillDirty, setSkillDirty] = useState(false);
+ const [versionSheetOpen, setVersionSheetOpen] = useState(false);
+ const [forkDialogOpen, setForkDialogOpen] = useState(false);
+
+ const layoutRef = useRef<PaneLayout>(loadPaneLayout());
+
+ // Keep deep-link params in sync (?input, ?run).
+ useEffect(() => {
+ const next = new URLSearchParams(searchParams);
+ if (selectedInputId) next.set("input", selectedInputId);
+ else next.delete("input");
+ if (selectedRunId) next.set("run", selectedRunId);
+ else next.delete("run");
+ if (next.toString() !== searchParams.toString()) {
+ setSearchParams(next, { replace: true });
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selectedInputId, selectedRunId]);
+
+ const inputsQuery = useQuery({
+ queryKey: queryKeys.companySkills.testInputs(companyId, skillId),
+ queryFn: () => companySkillsApi.testInputs(companyId, skillId),
+ enabled: Boolean(companyId && skillId),
+ });
+
+ const persistLayout = useCallback((layout: Record<string, number>) => {
+ const next: PaneLayout = {
+ skill: layout.skill ?? layoutRef.current.skill,
+ input: layout.input ?? layoutRef.current.input,
+ runs: layout.runs ?? layoutRef.current.runs,
+ };
+ layoutRef.current = next;
+ try {
+ localStorage.setItem(PANE_STORAGE_KEY, JSON.stringify(next));
+ } catch {
+ /* storage may be unavailable (private mode) — non-fatal */
+ }
+ }, []);
+
+ const inputs = inputsQuery.data ?? [];
+ const selectedInput = inputs.find((i) => i.id === selectedInputId) ?? null;
+
+ const leftPane = (
+ <SkillPane
+ companyId={companyId}
+ skill={skill}
+ onDirtyChange={setSkillDirty}
+ onEditACopy={() => setForkDialogOpen(true)}
+ />
+ );
+ const projectScan = isProjectScanSkill(skill.metadata);
+ const middlePane = (
+ <InputPane
+ companyId={companyId}
+ skillId={skillId}
+ inputs={inputs}
+ loading={inputsQuery.isLoading}
+ selectedInputId={selectedInputId}
+ adHocMode={adHocMode}
+ adHocContent={adHocContent}
+ onAdHocChange={setAdHocContent}
+ onSelectInput={(id) => {
+ setSelectedInputId(id);
+ setAdHocMode(false);
+ }}
+ onSelectAdHoc={() => {
+ setAdHocContent("");
+ setAdHocMode(true);
+ setSelectedInputId(null);
+ }}
+ />
+ );
+ const rightPane = (
+ <RunsPane
+ companyId={companyId}
+ skill={skill}
+ inputs={inputs}
+ selectedInput={selectedInput}
+ adHocMode={adHocMode}
+ adHocContent={adHocContent}
+ selectedRunId={selectedRunId}
+ onSelectRun={setSelectedRunId}
+ selectedAgentId={selectedAgentId}
+ onSelectAgent={setSelectedAgentId}
+ skillDirty={skillDirty}
+ filterInput={selectedInput}
+ onClearFilter={() => setSelectedInputId(null)}
+ />
+ );
+
+ return (
+ <TooltipProvider delayDuration={200}>
+ <div className="flex h-full min-h-0 flex-col">
+ <StudioHeader
+ companyId={companyId}
+ skill={skill}
+ skillDirty={skillDirty}
+ skills={skills}
+ skillsLoading={skillsLoading}
+ onSelectSkill={(nextSkillId) => navigate(skillStudioRoute(nextSkillId))}
+ onOpenVersions={() => setVersionSheetOpen(true)}
+ />
+ {projectScan ? (
+ <ProjectScanNotice skill={skill} onEditACopy={() => setForkDialogOpen(true)} />
+ ) : null}
+ {isMobile ? (
+ <MobileTabs skill={leftPane} input={middlePane} runs={rightPane} />
+ ) : (
+ <ResizablePanelGroup
+ className="flex-1 min-h-0"
+ defaultLayout={{
+ skill: layoutRef.current.skill,
+ input: layoutRef.current.input,
+ runs: layoutRef.current.runs,
+ }}
+ onLayoutChanged={persistLayout}
+ >
+ <ResizablePanel id="skill" minSize="280px" className="border-r border-border">
+ {leftPane}
+ </ResizablePanel>
+ <ResizableHandle />
+ <ResizablePanel
+ id="input"
+ minSize="240px"
+ collapsible
+ collapsedSize="40px"
+ className="border-r border-border"
+ >
+ {middlePane}
+ </ResizablePanel>
+ <ResizableHandle />
+ <ResizablePanel id="runs" minSize="360px">
+ {rightPane}
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ )}
+ </div>
+ <VersionHistorySheet
+ open={versionSheetOpen}
+ onOpenChange={setVersionSheetOpen}
+ companyId={companyId}
+ skill={skill}
+ onRestored={() => {
+ setSkillDirty(false);
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.detail(companyId, skillId),
+ });
+ }}
+ onFilterRuns={(inputId) => setSelectedInputId(inputId)}
+ />
+ <ForkSkillDialog
+ companyId={companyId}
+ skill={skill}
+ open={forkDialogOpen}
+ onOpenChange={setForkDialogOpen}
+ />
+ </TooltipProvider>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Header
+// ---------------------------------------------------------------------------
+
+function StudioHeader({
+ companyId,
+ skill,
+ skillDirty,
+ skills,
+ skillsLoading,
+ onSelectSkill,
+ onOpenVersions,
+}: {
+ companyId: string;
+ skill: CompanySkillDetail;
+ skillDirty: boolean;
+ skills: CompanySkillListItem[];
+ skillsLoading: boolean;
+ onSelectSkill: (skillId: string) => void;
+ onOpenVersions: () => void;
+}) {
+ const version = skill.currentVersion?.revisionNumber ?? null;
+ const toast = useOptionalToastActions();
+ const copyShareLink = useCallback(() => {
+ const href = typeof window !== "undefined" ? window.location.href : "";
+ void copyTextToClipboard(href)
+ .then(() => toast?.pushToast({ tone: "success", title: "Link copied", body: "Skill Studio link copied to clipboard." }))
+ .catch((error) => toast?.pushToast({
+ tone: "error",
+ title: "Copy failed",
+ body: error instanceof Error ? error.message : "Could not copy the link.",
+ }));
+ }, [toast]);
+
+ return (
+ <header className="flex items-center gap-3 border-b border-border px-3 py-2">
+ <SkillSwitcher
+ skill={skill}
+ skills={skills}
+ loading={skillsLoading}
+ onSelectSkill={onSelectSkill}
+ />
+ {version !== null && (
+ <span className="font-mono text-xs text-muted-foreground">v{version}</span>
+ )}
+ {skillDirty ? (
+ <Badge variant="secondary">Unsaved edits</Badge>
+ ) : null}
+ {!skill.editable ? (
+ <Badge variant="secondary">Read-only</Badge>
+ ) : null}
+ {skill.forkedFromSkillId ? (
+ <SkillLineageChip
+ companyId={companyId}
+ forkedFromSkillId={skill.forkedFromSkillId}
+ />
+ ) : null}
+ <AgentsUsingSkillBadge companyId={companyId} skill={skill} />
+ <div className="ml-auto flex items-center gap-1">
+ <Button variant="ghost" size="sm" onClick={onOpenVersions}>
+ <History className="mr-1.5 h-3.5 w-3.5" />
+ Version history
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-sm" aria-label="Studio menu">
+ <MoreHorizontal className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-52">
+ <DropdownMenuItem onClick={copyShareLink}>
+ <Share2 className="mr-2 h-4 w-4" /> Share link
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </header>
+ );
+}
+
+type SkillSwitcherOption = SearchableSelectOption<string> & {
+ skill: CompanySkillListItem | CompanySkillDetail;
+};
+
+function SkillSwitcher({
+ skill,
+ skills,
+ loading,
+ onSelectSkill,
+ emptyLabel = "Select skill",
+}: {
+ skill: CompanySkillDetail | null;
+ skills: CompanySkillListItem[];
+ loading: boolean;
+ onSelectSkill: (skillId: string) => void;
+ emptyLabel?: string;
+}) {
+ const groups = useMemo<readonly SearchableSelectGroup<string, SkillSwitcherOption>[]>(() => {
+ const options: SkillSwitcherOption[] = withCurrentSkill(skills, skill).map((item) => ({
+ key: item.id,
+ value: item.id,
+ label: item.name,
+ title: item.name,
+ searchText: [item.name, item.slug, item.key, item.description ?? ""].join(" "),
+ skill: item,
+ }));
+ return [{ id: "skills", options }];
+ }, [skill, skills]);
+
+ return (
+ <SearchableSelect<string, SkillSwitcherOption>
+ value={skill?.id ?? ""}
+ groups={groups}
+ loading={loading}
+ loadingMessage="Loading skills..."
+ placeholder={emptyLabel}
+ searchPlaceholder="Search skills..."
+ emptyMessage="No matching skills."
+ onValueChange={(value) => {
+ if (value !== skill?.id) onSelectSkill(value);
+ }}
+ triggerClassName="h-8 w-64 border-0 bg-transparent px-0 text-base font-semibold shadow-none hover:bg-accent md:w-80"
+ contentClassName="w-80"
+ contentWidth="auto"
+ renderValue={(option) => option?.label ?? skill?.name ?? emptyLabel}
+ renderOption={(option, { selected }) => (
+ <span className="flex min-w-0 flex-col">
+ <span className={cn("truncate", selected && "font-medium")}>{option.label}</span>
+ <span className="truncate text-(length:--text-micro) text-muted-foreground">
+ {option.skill.slug}
+ </span>
+ </span>
+ )}
+ />
+ );
+}
+
+function withCurrentSkill(
+ skills: CompanySkillListItem[],
+ skill: CompanySkillDetail | null,
+): Array<CompanySkillListItem | CompanySkillDetail> {
+ if (!skill) return skills;
+ return skills.some((candidate) => candidate.id === skill.id) ? skills : [skill, ...skills];
+}
+
+// ---------------------------------------------------------------------------
+// Left — Skill files + editor
+// ---------------------------------------------------------------------------
+
+function SkillPane({
+ companyId,
+ skill,
+ onDirtyChange,
+ onEditACopy,
+}: {
+ companyId: string;
+ skill: CompanySkillDetail;
+ onDirtyChange: (dirty: boolean) => void;
+ onEditACopy: () => void;
+}) {
+ const skillId = skill.id;
+ const queryClient = useQueryClient();
+ const onError = useMutationErrorToast();
+ const paths = useMemo(
+ () => skill.fileInventory.map((f) => f.path),
+ [skill.fileInventory],
+ );
+ const [selectedFile, setSelectedFile] = useState<string>(
+ () => paths.find((p) => /skill\.md$/i.test(p)) ?? paths[0] ?? "SKILL.md",
+ );
+ const [expandedDirs, setExpandedDirs] = useState<Set<string>>(new Set());
+ const [draft, setDraft] = useState<string>("");
+ const [savedContent, setSavedContent] = useState<string>("");
+ const [createDialog, setCreateDialog] = useState<"file" | "folder" | null>(null);
+ const [deleteFolderOpen, setDeleteFolderOpen] = useState(false);
+ // Gate rich-editor onChange until the user actually interacts with the body.
+ // MDXEditor can emit a normalizing onChange on mount, which would otherwise
+ // dirty the file on open and break the byte-identity guarantee (PAP-13156).
+ const bodyInteractedRef = useRef(false);
+
+ const nodes: FileTreeNode[] = useMemo(
+ () => buildFileTree(Object.fromEntries(paths.map((p) => [p, ""]))),
+ [paths],
+ );
+
+ const fileQuery = useQuery({
+ queryKey: queryKeys.companySkills.file(companyId, skillId, selectedFile),
+ queryFn: () => companySkillsApi.file(companyId, skillId, selectedFile),
+ enabled: Boolean(companyId && skillId && selectedFile),
+ });
+
+ useEffect(() => {
+ if (fileQuery.data) {
+ bodyInteractedRef.current = false;
+ setDraft(fileQuery.data.content);
+ setSavedContent(fileQuery.data.content);
+ }
+ }, [fileQuery.data]);
+
+ const dirty = draft !== savedContent;
+ const currentFolder = parentFolder(selectedFile);
+ const pathSet = useMemo(() => new Set(paths), [paths]);
+
+ useEffect(() => {
+ onDirtyChange(dirty);
+ }, [dirty, onDirtyChange]);
+
+ const selectFile = useCallback((path: string) => {
+ if (path === selectedFile) return;
+ if (
+ dirty
+ && typeof window !== "undefined"
+ && !window.confirm("Discard unsaved edits and switch files?")
+ ) {
+ return;
+ }
+ setSelectedFile(path);
+ }, [dirty, selectedFile]);
+
+ const saveMutation = useMutation({
+ mutationFn: () => companySkillsApi.updateFile(companyId, skillId, selectedFile, draft),
+ onSuccess: (updated) => {
+ setSavedContent(updated.content);
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.detail(companyId, skillId),
+ });
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.list(companyId),
+ });
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.versions(companyId, skillId),
+ });
+ },
+ onError: onError("Couldn't save file"),
+ });
+
+ const createMutation = useMutation({
+ mutationFn: ({ path, content }: { path: string; content: string }) =>
+ companySkillsApi.updateFile(companyId, skillId, path, content),
+ onSuccess: (created) => {
+ setSelectedFile(created.path);
+ setDraft(created.content);
+ setSavedContent(created.content);
+ setCreateDialog(null);
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.detail(companyId, skillId),
+ });
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.list(companyId),
+ });
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.versions(companyId, skillId),
+ });
+ },
+ onError: onError("Couldn't create file"),
+ });
+
+ const deleteMutation = useMutation({
+ mutationFn: (input: { path: string; target: "file" | "folder" }) =>
+ companySkillsApi.deleteFile(companyId, skillId, input),
+ onSuccess: (result) => {
+ const deleted = new Set(result.deletedPaths);
+ const remaining = paths.filter((path) => !deleted.has(path));
+ setSelectedFile(remaining.find((path) => /skill\.md$/i.test(path)) ?? remaining[0] ?? "SKILL.md");
+ setDeleteFolderOpen(false);
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.detail(companyId, skillId),
+ });
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.list(companyId),
+ });
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.versions(companyId, skillId),
+ });
+ },
+ onError: onError("Couldn't delete file"),
+ });
+
+ // Read-only skills (bundled Paperclip, remote GitHub, URL, skills.sh) reject
+ // file writes server-side; reflect that up-front instead of letting the user
+ // type into an editor whose Save silently 422s (PAP-13001 Bug B).
+ const readOnly = skill.editable === false || fileQuery.data?.editable === false;
+
+ if (paths.length === 0) {
+ return (
+ <PaneScaffold
+ title={<SkillPaneTitle skillName={skill.name} folder="root" />}
+ action={
+ <SkillFileActions
+ readOnly={readOnly}
+ selectedFile={selectedFile}
+ currentFolder=""
+ canDeleteFile={false}
+ pending={createMutation.isPending || deleteMutation.isPending || dirty}
+ onAddFile={() => setCreateDialog("file")}
+ onAddFolder={() => setCreateDialog("folder")}
+ onDeleteFile={() => {}}
+ onDeleteFolder={() => setDeleteFolderOpen(true)}
+ />
+ }
+ >
+ <EmptyState icon={FileCode} message="This skill has no files yet." />
+ <SkillPathDialog
+ mode={createDialog}
+ open={createDialog !== null}
+ onOpenChange={(open) => {
+ if (!open) setCreateDialog(null);
+ }}
+ currentFolder=""
+ existingPaths={pathSet}
+ pending={createMutation.isPending}
+ onSubmit={(path, content) => createMutation.mutate({ path, content })}
+ />
+ </PaneScaffold>
+ );
+ }
+
+ const isMarkdown = fileQuery.data?.markdown ?? /\.md$/i.test(selectedFile);
+ const markdownBlock = isMarkdown ? splitFrontmatterBlock(draft) : null;
+
+ return (
+ <PaneScaffold
+ title={<SkillPaneTitle skillName={skill.name} folder={currentFolder || "root"} />}
+ action={
+ <SkillFileActions
+ readOnly={readOnly}
+ selectedFile={selectedFile}
+ currentFolder={currentFolder}
+ canDeleteFile={selectedFile !== "SKILL.md"}
+ pending={createMutation.isPending || deleteMutation.isPending || dirty}
+ onAddFile={() => setCreateDialog("file")}
+ onAddFolder={() => setCreateDialog("folder")}
+ onDeleteFile={() => deleteMutation.mutate({ path: selectedFile, target: "file" })}
+ onDeleteFolder={() => setDeleteFolderOpen(true)}
+ />
+ }
+ >
+ <div className="flex min-h-0 flex-1 flex-col">
+ {dirty && !readOnly ? (
+ <div className="flex items-start gap-2 border-b border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500" />
+ <span>Unsaved edits live only in this Studio session. Save to create the next version before running tests or switching files.</span>
+ </div>
+ ) : null}
+ <div className="max-h-(--sz-11_75rem) overflow-auto border-b border-border p-1">
+ <FileTree
+ nodes={nodes}
+ selectedFile={selectedFile}
+ expandedDirs={expandedDirs}
+ onToggleDir={(path) =>
+ setExpandedDirs((prev) => {
+ const next = new Set(prev);
+ if (next.has(path)) next.delete(path);
+ else next.add(path);
+ return next;
+ })
+ }
+ onSelectFile={selectFile}
+ showCheckboxes={false}
+ ariaLabel="Skill files"
+ />
+ </div>
+ {readOnly && (
+ <div className="flex items-start gap-3 border-b border-border bg-muted/40 px-3 py-2.5 text-xs text-muted-foreground">
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500" />
+ <div className="min-w-0 flex-1">
+ <p>
+ {skill.editableReason ?? "This skill is read-only because it comes from an external source."}
+ {" "}Make an editable copy to change it — the original stays untouched.
+ </p>
+ <Button
+ type="button"
+ size="sm"
+ className="mt-2"
+ onClick={onEditACopy}
+ >
+ <GitFork className="mr-1.5 h-3.5 w-3.5" />
+ Edit a copy
+ </Button>
+ </div>
+ </div>
+ )}
+ <div className="flex items-center justify-between gap-2 px-3 py-1.5">
+ <span className="truncate font-mono text-xs text-muted-foreground">
+ {selectedFile}
+ {skill.currentVersion ? ` · v${skill.currentVersion.revisionNumber}` : ""}
+ </span>
+ <div className="flex items-center gap-2">
+ {readOnly ? (
+ <Badge variant="secondary">Read-only</Badge>
+ ) : (
+ <>
+ {dirty && <Badge variant="secondary">Unsaved</Badge>}
+ <Button
+ size="sm"
+ disabled={!dirty || saveMutation.isPending}
+ onClick={() => saveMutation.mutate()}
+ >
+ {saveMutation.isPending ? "Saving…" : "Save"}
+ </Button>
+ </>
+ )}
+ </div>
+ </div>
+ {isMarkdown && markdownBlock?.hasFrontmatter ? (
+ <FrontmatterPanel
+ key={`fm:${selectedFile}`}
+ frontmatterText={markdownBlock.frontmatterText}
+ hasFrontmatter={markdownBlock.hasFrontmatter}
+ fileName={selectedFile}
+ skillSlug={skill.slug}
+ readOnly={readOnly}
+ onChange={(change) => {
+ setDraft((prev) =>
+ joinFrontmatterBlock({
+ frontmatterText: change.frontmatterText,
+ body: splitFrontmatterBlock(prev).body,
+ hasFrontmatter: change.hasFrontmatter,
+ }),
+ );
+ }}
+ />
+ ) : null}
+ <div
+ className="min-h-0 flex-1 overflow-auto px-3 pb-3"
+ onInput={() => {
+ bodyInteractedRef.current = true;
+ }}
+ >
+ {isMarkdown && markdownBlock ? (
+ <MarkdownEditor
+ key={`body:${selectedFile}`}
+ value={markdownBlock.body}
+ onChange={(nextBody) => {
+ // Ignore MDXEditor's on-mount normalization; only apply real edits.
+ if (!bodyInteractedRef.current) return;
+ setDraft((prev) => {
+ const block = splitFrontmatterBlock(prev);
+ return joinFrontmatterBlock({ ...block, body: nextBody });
+ });
+ }}
+ bordered={false}
+ readOnly={readOnly}
+ className="min-h-(--sz-320px)"
+ />
+ ) : (
+ <Textarea
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ readOnly={readOnly}
+ className="min-h-(--sz-320px) font-mono text-xs"
+ spellCheck={false}
+ />
+ )}
+ </div>
+ </div>
+ <SkillPathDialog
+ mode={createDialog}
+ open={createDialog !== null}
+ onOpenChange={(open) => {
+ if (!open) setCreateDialog(null);
+ }}
+ currentFolder={currentFolder}
+ existingPaths={pathSet}
+ pending={createMutation.isPending}
+ onSubmit={(path, content) => createMutation.mutate({ path, content })}
+ />
+ <DeleteFolderDialog
+ open={deleteFolderOpen}
+ onOpenChange={setDeleteFolderOpen}
+ currentFolder={currentFolder}
+ existingPaths={pathSet}
+ pending={deleteMutation.isPending}
+ onSubmit={(path) => deleteMutation.mutate({ path, target: "folder" })}
+ />
+ </PaneScaffold>
+ );
+}
+
+function parentFolder(filePath: string) {
+ const parts = filePath.split("/").filter(Boolean);
+ if (parts.length <= 1) return "";
+ return parts.slice(0, -1).join("/");
+}
+
+function normalizeStudioPath(value: string) {
+ return value
+ .replace(/\\/g, "/")
+ .replace(/^\.\/+/, "")
+ .replace(/^\/+/, "")
+ .split("/")
+ .filter((segment) => segment && segment !== ".")
+ .join("/");
+}
+
+function folderSeedFile(folderPath: string) {
+ return `${folderPath}/README.md`;
+}
+
+function folderSeedContent(folderPath: string) {
+ const label = folderPath.split("/").filter(Boolean).at(-1) ?? "Folder";
+ return `# ${label}\n`;
+}
+
+function SkillPaneTitle({ skillName, folder }: { skillName: string; folder: string }) {
+ return (
+ <span className="flex min-w-0 items-center gap-1.5">
+ <span className="truncate">{skillName}</span>
+ <ChevronRight className="h-3 w-3 shrink-0" />
+ <span className="truncate font-mono normal-case tracking-normal">{folder}</span>
+ </span>
+ );
+}
+
+function SkillFileActions({
+ readOnly,
+ selectedFile,
+ canDeleteFile,
+ pending,
+ onAddFile,
+ onAddFolder,
+ onDeleteFile,
+ onDeleteFolder,
+}: {
+ readOnly: boolean;
+ selectedFile: string;
+ currentFolder: string;
+ canDeleteFile: boolean;
+ pending: boolean;
+ onAddFile: () => void;
+ onAddFolder: () => void;
+ onDeleteFile: () => void;
+ onDeleteFolder: () => void;
+}) {
+ const disabled = readOnly || pending;
+ const deleteDisabled = disabled || !canDeleteFile;
+ return (
+ <div className="flex items-center gap-1">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button variant="ghost" size="icon-sm" disabled={disabled} onClick={onAddFile} aria-label="Add file">
+ <FilePlus className="h-4 w-4" />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Add file</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button variant="ghost" size="icon-sm" disabled={disabled} onClick={onAddFolder} aria-label="Add folder">
+ <FolderPlus className="h-4 w-4" />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Add folder</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ disabled={deleteDisabled}
+ onClick={() => {
+ if (typeof window === "undefined" || window.confirm(`Delete ${selectedFile}?`)) {
+ onDeleteFile();
+ }
+ }}
+ aria-label="Delete file"
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{canDeleteFile ? "Delete file" : "SKILL.md cannot be deleted"}</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button variant="ghost" size="icon-sm" disabled={disabled} onClick={onDeleteFolder} aria-label="Delete folder">
+ <FolderMinus className="h-4 w-4" />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Delete folder</TooltipContent>
+ </Tooltip>
+ </div>
+ );
+}
+
+function SkillPathDialog({
+ mode,
+ open,
+ onOpenChange,
+ currentFolder,
+ existingPaths,
+ pending,
+ onSubmit,
+}: {
+ mode: "file" | "folder" | null;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ currentFolder: string;
+ existingPaths: Set<string>;
+ pending: boolean;
+ onSubmit: (path: string, content: string) => void;
+}) {
+ const [pathValue, setPathValue] = useState("");
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!open || !mode) return;
+ setPathValue(mode === "folder"
+ ? normalizeStudioPath(currentFolder ? `${currentFolder}/new-folder` : "new-folder")
+ : normalizeStudioPath(currentFolder ? `${currentFolder}/new-file.md` : "notes.md"));
+ setError(null);
+ }, [currentFolder, mode, open]);
+
+ const title = mode === "folder" ? "Add folder" : "Add file";
+ const label = mode === "folder" ? "Folder path" : "File path";
+
+ function submit() {
+ if (!mode) return;
+ const normalized = normalizeStudioPath(pathValue);
+ if (!normalized) {
+ setError(`${label} is required.`);
+ return;
+ }
+ if (mode === "file") {
+ if (existingPaths.has(normalized)) {
+ setError("A file already exists at that path.");
+ return;
+ }
+ onSubmit(normalized, "");
+ return;
+ }
+
+ const folderPath = normalized.replace(/\/+$/, "");
+ if ([...existingPaths].some((path) => path.startsWith(`${folderPath}/`))) {
+ setError("A folder already exists at that path.");
+ return;
+ }
+ onSubmit(folderSeedFile(folderPath), folderSeedContent(folderPath));
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription>
+ Saved changes create a new version immediately. External sources are not updated until you publish or install an update.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-2">
+ <Label htmlFor="skill-path-input">{label}</Label>
+ <Input
+ id="skill-path-input"
+ value={pathValue}
+ onChange={(event) => {
+ setPathValue(event.target.value);
+ setError(null);
+ }}
+ placeholder={mode === "folder" ? "references/examples" : "references/examples.md"}
+ />
+ {mode === "folder" ? (
+ <p className="text-xs text-muted-foreground">A README.md seed file is created so the folder appears in the file tree.</p>
+ ) : null}
+ {error ? <p className="text-xs text-destructive">{error}</p> : null}
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button disabled={pending} onClick={submit}>
+ Create
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function DeleteFolderDialog({
+ open,
+ onOpenChange,
+ currentFolder,
+ existingPaths,
+ pending,
+ onSubmit,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ currentFolder: string;
+ existingPaths: Set<string>;
+ pending: boolean;
+ onSubmit: (path: string) => void;
+}) {
+ const [pathValue, setPathValue] = useState("");
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ setPathValue(currentFolder);
+ setError(null);
+ }, [currentFolder, open]);
+
+ function submit() {
+ const normalized = normalizeStudioPath(pathValue).replace(/\/+$/, "");
+ if (!normalized) {
+ setError("Folder path is required.");
+ return;
+ }
+ const matchingFiles = [...existingPaths].filter((path) => path.startsWith(`${normalized}/`));
+ if (matchingFiles.length === 0) {
+ setError("No files exist under that folder.");
+ return;
+ }
+ if (matchingFiles.includes("SKILL.md")) {
+ setError("SKILL.md cannot be deleted.");
+ return;
+ }
+ onSubmit(normalized);
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Delete folder</DialogTitle>
+ <DialogDescription>
+ This removes every skill file under the folder and saves the result as the next version.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-2">
+ <Label htmlFor="skill-folder-delete">Folder path</Label>
+ <Input
+ id="skill-folder-delete"
+ value={pathValue}
+ onChange={(event) => {
+ setPathValue(event.target.value);
+ setError(null);
+ }}
+ placeholder="references/examples"
+ />
+ {error ? <p className="text-xs text-destructive">{error}</p> : null}
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button variant="destructive" disabled={pending} onClick={submit}>
+ Delete
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Middle — Inputs (path-foldered) + editor + save-as-input
+// ---------------------------------------------------------------------------
+
+function InputPane({
+ companyId,
+ skillId,
+ inputs,
+ loading,
+ selectedInputId,
+ adHocMode,
+ adHocContent,
+ onAdHocChange,
+ onSelectInput,
+ onSelectAdHoc,
+}: {
+ companyId: string;
+ skillId: string;
+ inputs: CompanySkillTestInput[];
+ loading: boolean;
+ selectedInputId: string | null;
+ adHocMode: boolean;
+ adHocContent: string;
+ onAdHocChange: (value: string) => void;
+ onSelectInput: (id: string) => void;
+ onSelectAdHoc: () => void;
+}) {
+ const queryClient = useQueryClient();
+ const onError = useMutationErrorToast();
+ const [expandedDirs, setExpandedDirs] = useState<Set<string>>(new Set());
+ const [savedInputDraft, setSavedInputDraft] = useState<SavedInputDraftState>(
+ EMPTY_SAVED_INPUT_DRAFT_STATE,
+ );
+ const [saveDialogOpen, setSaveDialogOpen] = useState(false);
+ const [collapsed, setCollapsed] = useState(false);
+
+ const selectedInput = inputs.find((i) => i.id === selectedInputId) ?? null;
+
+ // In ad-hoc mode the editor is controlled by the shared shell state; otherwise
+ // it edits a local copy of the selected saved input.
+ const savedDraft = selectedSavedInputDraft(savedInputDraft, selectedInput);
+ const draft = adHocMode ? adHocContent : savedDraft;
+ const setDraft = adHocMode
+ ? onAdHocChange
+ : (value: string) => {
+ setSavedInputDraft((previous) => ({
+ inputId: selectedInput?.id ?? previous.inputId,
+ draft: value,
+ baselineContent: selectedInput?.content ?? previous.baselineContent,
+ }));
+ };
+
+ useEffect(() => {
+ if (adHocMode) return;
+ setSavedInputDraft((previous) => syncSavedInputDraftState(previous, selectedInput));
+ }, [adHocMode, selectedInput?.content, selectedInput?.id]);
+
+ useEffect(() => {
+ if (!loading && inputs.length === 0 && !adHocMode && !selectedInputId) {
+ onSelectAdHoc();
+ }
+ }, [adHocMode, inputs.length, loading, onSelectAdHoc, selectedInputId]);
+
+ const nameToId = useMemo(
+ () => new Map(inputs.map((i) => [i.name, i.id])),
+ [inputs],
+ );
+ const nodes: FileTreeNode[] = useMemo(
+ () => buildFileTree(Object.fromEntries(inputs.map((i) => [i.name, i.content]))),
+ [inputs],
+ );
+ const selectedName = selectedInput?.name ?? null;
+ const dirty = !adHocMode && savedInputDraftDirty(savedInputDraft, selectedInput);
+ const canSaveSelectedInput = Boolean(selectedInput && dirty && draft.trim());
+
+ const confirmDiscardDirtyInput = useCallback(() => {
+ if (!dirty) return true;
+ return (
+ typeof window === "undefined"
+ || window.confirm("Discard unsaved changes to this input?")
+ );
+ }, [dirty]);
+
+ const selectSavedInput = useCallback((id: string) => {
+ if (!adHocMode && id === selectedInputId) return;
+ if (!confirmDiscardDirtyInput()) return;
+ onSelectInput(id);
+ }, [adHocMode, confirmDiscardDirtyInput, onSelectInput, selectedInputId]);
+
+ const selectAdHocInput = useCallback(() => {
+ if (!adHocMode && !confirmDiscardDirtyInput()) return;
+ onSelectAdHoc();
+ }, [adHocMode, confirmDiscardDirtyInput, onSelectAdHoc]);
+
+ const updateMutation = useMutation({
+ mutationFn: (payload: { content: string }) =>
+ companySkillsApi.updateTestInput(companyId, skillId, selectedInput!.id, payload),
+ onSuccess: (updated) => {
+ setSavedInputDraft({
+ inputId: updated.id,
+ draft: updated.content,
+ baselineContent: updated.content,
+ });
+ queryClient.setQueryData<CompanySkillTestInput[]>(
+ queryKeys.companySkills.testInputs(companyId, skillId),
+ (current) => current?.map((input) => input.id === updated.id ? updated : input),
+ );
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.testInputs(companyId, skillId),
+ });
+ },
+ onError: onError("Couldn't save input"),
+ });
+ const deleteMutation = useMutation({
+ mutationFn: (inputId: string) => companySkillsApi.deleteTestInput(companyId, skillId, inputId),
+ onSuccess: (deleted) => {
+ if (deleted.id === selectedInputId) {
+ onSelectAdHoc();
+ }
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.testInputs(companyId, skillId),
+ });
+ },
+ onError: onError("Couldn't delete input"),
+ });
+
+ return (
+ <PaneScaffold
+ title={
+ <span className="flex min-w-0 items-center gap-1">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={collapsed ? "Expand input" : "Collapse input"}
+ onClick={() => setCollapsed((current) => !current)}
+ >
+ {collapsed ? (
+ <ChevronRight className="h-3.5 w-3.5" />
+ ) : (
+ <ChevronDown className="h-3.5 w-3.5" />
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{collapsed ? "Expand input" : "Collapse input"}</TooltipContent>
+ </Tooltip>
+ <span>Input</span>
+ </span>
+ }
+ action={
+ <div className="flex items-center gap-1">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" size="icon-sm" onClick={selectAdHocInput} aria-label="New input">
+ <Plus className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>New input</TooltipContent>
+ </Tooltip>
+ </div>
+ }
+ >
+ {collapsed ? (
+ <button
+ type="button"
+ className="flex min-h-(--sz-32px) items-center gap-2 border-b border-border px-3 py-2 text-left text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
+ onClick={() => setCollapsed(false)}
+ >
+ <ChevronRight className="h-3.5 w-3.5" />
+ <span>Input folded</span>
+ </button>
+ ) : (
+ <div className="flex min-h-0 flex-1 flex-col">
+ {loading || inputs.length > 0 ? (
+ <div className="max-h-(--sz-11_75rem) overflow-auto border-b border-border p-1">
+ {loading ? (
+ <div className="p-3 text-xs text-muted-foreground">Loading inputs…</div>
+ ) : (
+ <>
+ {adHocMode && (
+ <div className="flex items-center gap-2 rounded px-2 py-1.5 text-sm italic text-muted-foreground">
+ <FilePlus className="h-3.5 w-3.5" /> New input (not saved)
+ </div>
+ )}
+ <FileTree
+ nodes={nodes}
+ selectedFile={selectedName}
+ expandedDirs={expandedDirs}
+ onToggleDir={(path) =>
+ setExpandedDirs((prev) => {
+ const next = new Set(prev);
+ if (next.has(path)) next.delete(path);
+ else next.add(path);
+ return next;
+ })
+ }
+ onSelectFile={(name) => {
+ const id = nameToId.get(name);
+ if (id) selectSavedInput(id);
+ }}
+ showCheckboxes={false}
+ renderFileExtra={(node) => {
+ const id = nameToId.get(node.path);
+ if (!id) return null;
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
+ aria-label={`Input actions for ${node.name}`}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <MoreHorizontal className="h-3.5 w-3.5" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-44">
+ <DropdownMenuItem
+ onClick={() => {
+ const input = inputs.find((i) => i.id === id);
+ if (input) navigator.clipboard?.writeText(input.content).catch(() => {});
+ }}
+ >
+ <Copy className="mr-2 h-4 w-4" /> Copy content
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => deleteMutation.mutate(id)}
+ >
+ <Trash2 className="mr-2 h-4 w-4" /> Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+ }}
+ ariaLabel="Test inputs"
+ />
+ </>
+ )}
+ </div>
+ ) : null}
+ <div className="flex min-h-0 flex-1">
+ <textarea
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ placeholder="Paste text - treated as a new issue description."
+ aria-label="Skill test input"
+ className="min-h-0 flex-1 resize-none border-0 bg-transparent px-3 py-3 text-sm leading-6 outline-none placeholder:text-muted-foreground focus-visible:ring-0"
+ />
+ </div>
+ <div className="flex items-center gap-2 border-t border-border px-3 py-2">
+ <div className="mr-auto flex min-w-0 items-center gap-2 text-xs text-muted-foreground">
+ <span className="truncate">
+ {selectedInput ? selectedInput.name : adHocMode ? "New input" : "No input selected"}
+ </span>
+ {dirty ? <Badge variant="secondary">Unsaved</Badge> : null}
+ </div>
+ {selectedInput && dirty ? (
+ <>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={updateMutation.isPending}
+ onClick={() => setSavedInputDraft({
+ inputId: selectedInput.id,
+ draft: selectedInput.content,
+ baselineContent: selectedInput.content,
+ })}
+ >
+ Revert
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!canSaveSelectedInput || updateMutation.isPending}
+ onClick={() => updateMutation.mutate({ content: draft })}
+ >
+ {updateMutation.isPending ? "Saving..." : "Save changes"}
+ </Button>
+ </>
+ ) : null}
+ <Button
+ size="sm"
+ disabled={!draft.trim()}
+ onClick={() => setSaveDialogOpen(true)}
+ >
+ Save as input
+ </Button>
+ </div>
+ </div>
+ )}
+ <SaveInputDialog
+ open={saveDialogOpen}
+ onOpenChange={setSaveDialogOpen}
+ companyId={companyId}
+ skillId={skillId}
+ initialContent={draft}
+ onSaved={(input) => {
+ setSaveDialogOpen(false);
+ onSelectInput(input.id);
+ }}
+ />
+ </PaneScaffold>
+ );
+}
+
+function SaveInputDialog({
+ open,
+ onOpenChange,
+ companyId,
+ skillId,
+ initialContent,
+ onSaved,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ companyId: string;
+ skillId: string;
+ initialContent: string;
+ onSaved: (input: CompanySkillTestInput) => void;
+}) {
+ const queryClient = useQueryClient();
+ const [name, setName] = useState("");
+ const [content, setContent] = useState(initialContent);
+
+ useEffect(() => {
+ if (open) {
+ setContent(initialContent);
+ setName("");
+ }
+ }, [open, initialContent]);
+
+ const createMutation = useMutation({
+ mutationFn: () => companySkillsApi.createTestInput(companyId, skillId, { name: name.trim(), content }),
+ onSuccess: (input) => {
+ queryClient.setQueryData<CompanySkillTestInput[]>(
+ queryKeys.companySkills.testInputs(companyId, skillId),
+ (current) => {
+ const withoutDuplicate = (current ?? []).filter((item) => item.id !== input.id);
+ return [...withoutDuplicate, input].sort((a, b) =>
+ a.name.localeCompare(b.name) || Number(new Date(a.createdAt)) - Number(new Date(b.createdAt)),
+ );
+ },
+ );
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.testInputs(companyId, skillId),
+ });
+ onSaved(input);
+ },
+ });
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Save test input</DialogTitle>
+ <DialogDescription>
+ Runs snapshot input at run time — editing later won't change past runs.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-3">
+ <div className="space-y-1">
+ <Label htmlFor="input-name">Name</Label>
+ <Input
+ id="input-name"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="onboarding/happy-path"
+ />
+ <p className="text-xs text-muted-foreground">Use “/” for folders, e.g. onboarding/happy-path</p>
+ </div>
+ <div className="space-y-1">
+ <Label htmlFor="input-content">Content</Label>
+ <Textarea
+ id="input-content"
+ value={content}
+ onChange={(e) => setContent(e.target.value)}
+ className="min-h-(--sz-160px)"
+ />
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button
+ disabled={!name.trim() || !content.trim() || createMutation.isPending}
+ onClick={() => createMutation.mutate()}
+ >
+ Save
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Right — agent picker + Run + history + detail
+// ---------------------------------------------------------------------------
+
+type RunTemplateDialogState =
+ | { mode: "create"; source?: CompanySkillTestRunTemplate | null }
+ | { mode: "edit"; source: CompanySkillTestRunTemplate }
+ | null;
+
+function RunsPane({
+ companyId,
+ skill,
+ inputs,
+ selectedInput,
+ adHocMode,
+ adHocContent,
+ selectedRunId,
+ onSelectRun,
+ selectedAgentId,
+ onSelectAgent,
+ skillDirty,
+ filterInput,
+ onClearFilter,
+}: {
+ companyId: string;
+ skill: CompanySkillDetail;
+ inputs: CompanySkillTestInput[];
+ selectedInput: CompanySkillTestInput | null;
+ adHocMode: boolean;
+ adHocContent: string;
+ selectedRunId: string | null;
+ onSelectRun: (id: string | null) => void;
+ selectedAgentId: string | null;
+ onSelectAgent: (id: string | null) => void;
+ skillDirty: boolean;
+ filterInput: CompanySkillTestInput | null;
+ onClearFilter: () => void;
+}) {
+ const skillId = skill.id;
+ const queryClient = useQueryClient();
+ const onError = useMutationErrorToast();
+ const toast = useOptionalToastActions();
+ const [advancedOpen, setAdvancedOpen] = useState(false);
+ const [selectedTemplateId, setSelectedTemplateId] = useState<RunTemplateSelection>(
+ () => loadRunTemplateSelection(companyId),
+ );
+ const [templateDialog, setTemplateDialog] = useState<RunTemplateDialogState>(null);
+
+ const agentsQuery = useQuery({
+ queryKey: queryKeys.agents.list(companyId),
+ queryFn: () => agentsApi.list(companyId),
+ enabled: Boolean(companyId),
+ });
+ const agents = agentsQuery.data ?? [];
+ const selectedAgent = agents.find((a) => a.id === selectedAgentId) ?? null;
+
+ useEffect(() => {
+ setSelectedTemplateId(loadRunTemplateSelection(companyId));
+ }, [companyId]);
+
+ const updateTemplateSelection = useCallback((selection: RunTemplateSelection) => {
+ setSelectedTemplateId(selection);
+ persistRunTemplateSelection(companyId, selection);
+ }, [companyId]);
+
+ const templatesQuery = useQuery({
+ queryKey: queryKeys.companySkills.testRunTemplates(companyId),
+ queryFn: () => companySkillsApi.testRunTemplates(companyId),
+ enabled: Boolean(companyId),
+ });
+ const templates = templatesQuery.data ?? EMPTY_RUN_TEMPLATES;
+
+ useEffect(() => {
+ if (!templatesQuery.isSuccess) return;
+ const resolution = resolveRunTemplateSelection(selectedTemplateId, templates);
+ if (!resolution.recovered) return;
+ updateTemplateSelection(resolution.selection);
+ toast?.pushToast({
+ tone: "warn",
+ title: "Run template reset",
+ body: "The saved run template is no longer available. Default test template is selected.",
+ dedupeKey: `skill-studio-template-reset:${companyId}`,
+ });
+ }, [
+ companyId,
+ selectedTemplateId,
+ templates,
+ templatesQuery.isSuccess,
+ toast,
+ updateTemplateSelection,
+ ]);
+
+ const filterInputId = filterInput?.id ?? null;
+ const runsQuery = useQuery({
+ queryKey: queryKeys.companySkills.testRuns(companyId, skillId, filterInputId),
+ queryFn: () =>
+ companySkillsApi.testRuns(companyId, skillId, filterInputId ? { inputId: filterInputId } : {}),
+ enabled: Boolean(companyId && skillId),
+ refetchInterval: (query) => {
+ const data = query.state.data as CompanySkillTestRun[] | undefined;
+ return data?.some((r) => shouldPollRun(r.status)) ? POLL_MS : false;
+ },
+ });
+ const runs = runsQuery.data ?? [];
+
+ const hasInput = adHocMode ? adHocContent.trim().length > 0 : Boolean(selectedInput?.content.trim());
+ const gate = evaluateRunGate({
+ hasAgent: Boolean(selectedAgent),
+ hasInput,
+ skillFileCount: skill.fileInventory.length,
+ hasUnsavedSkillEdits: skillDirty,
+ });
+ const templateGateReason = templatesQuery.isLoading
+ ? "Loading run templates"
+ : templatesQuery.isError
+ ? "Run templates couldn't load"
+ : null;
+
+ const createTemplateMutation = useMutation({
+ mutationFn: (payload: CompanySkillTestRunTemplateCreateRequest) =>
+ companySkillsApi.createTestRunTemplate(companyId, payload),
+ onSuccess: (template) => {
+ setTemplateDialog(null);
+ updateTemplateSelection(template.id);
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.testRunTemplates(companyId),
+ });
+ toast?.pushToast({
+ tone: "success",
+ title: "Template saved",
+ body: `${template.name} is ready for Skills Studio runs.`,
+ });
+ },
+ onError: onError("Couldn't save template"),
+ });
+
+ const updateTemplateMutation = useMutation({
+ mutationFn: ({ templateId, payload }: {
+ templateId: string;
+ payload: CompanySkillTestRunTemplateUpdateRequest;
+ }) => companySkillsApi.updateTestRunTemplate(companyId, templateId, payload),
+ onSuccess: (template) => {
+ setTemplateDialog(null);
+ updateTemplateSelection(template.id);
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.testRunTemplates(companyId),
+ });
+ toast?.pushToast({
+ tone: "success",
+ title: "Template updated",
+ body: `${template.name} is ready for Skills Studio runs.`,
+ });
+ },
+ onError: onError("Couldn't update template"),
+ });
+
+ const deleteTemplateMutation = useMutation({
+ mutationFn: (templateId: string) => companySkillsApi.deleteTestRunTemplate(companyId, templateId),
+ onSuccess: (template) => {
+ const fallback = resolveRunTemplateSelection(selectedTemplateId, templates.filter((entry) => entry.id !== template.id));
+ if (selectedTemplateId === template.id || fallback.recovered) {
+ updateTemplateSelection(fallback.selection);
+ }
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.testRunTemplates(companyId),
+ });
+ toast?.pushToast({
+ tone: "success",
+ title: "Template deleted",
+ body: `${template.name} was removed from Skills Studio runs.`,
+ });
+ },
+ onError: onError("Couldn't delete template"),
+ });
+
+ const selectedTemplate = selectedTemplateId === null
+ ? null
+ : templates.find((template) => template.id === selectedTemplateId) ?? null;
+ const selectedTemplateName = selectedTemplateId === null
+ ? "No template"
+ : selectedTemplate?.name ?? "Default test template";
+ const runDisabledReason = gate.reason ?? templateGateReason;
+
+ const createRunMutation = useMutation({
+ mutationFn: () => {
+ if (!templatesQuery.isSuccess) {
+ throw new Error(templateGateReason ?? "Run templates are not ready.");
+ }
+ const resolution = resolveRunTemplateSelection(selectedTemplateId, templates);
+ if (resolution.recovered) {
+ updateTemplateSelection(resolution.selection);
+ throw new Error("Selected run template is no longer available. The selection was reset.");
+ }
+ return companySkillsApi.createTestRun(companyId, skillId, buildCreateRunRequest({
+ agentId: selectedAgentId!,
+ inputId: adHocMode ? null : selectedInput?.id ?? null,
+ content: adHocMode ? adHocContent : selectedInput ? null : adHocContent,
+ templateId: resolution.selection,
+ }));
+ },
+ onSuccess: (run) => {
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.testRuns(companyId, skillId, filterInputId),
+ });
+ onSelectRun(run.id);
+ },
+ onError: onError("Couldn't start run"),
+ });
+
+ if (selectedRunId) {
+ return (
+ <RunDetailView
+ companyId={companyId}
+ skill={skill}
+ runId={selectedRunId}
+ agents={agents}
+ onBack={() => onSelectRun(null)}
+ onSelectRun={onSelectRun}
+ />
+ );
+ }
+
+ return (
+ <PaneScaffold
+ title="Test runs"
+ action={
+ <div className="flex items-center gap-2">
+ <AgentPicker
+ agents={agents}
+ selectedAgent={selectedAgent}
+ onSelect={onSelectAgent}
+ />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {/* span wrapper keeps the tooltip reachable while the button is disabled */}
+ <span>
+ <Button
+ size="sm"
+ disabled={gate.disabled || Boolean(templateGateReason) || createRunMutation.isPending}
+ onClick={() => createRunMutation.mutate()}
+ >
+ <Play className="mr-1.5 h-3.5 w-3.5" /> Run
+ </Button>
+ </span>
+ </TooltipTrigger>
+ {runDisabledReason && <TooltipContent side="bottom">{runDisabledReason}</TooltipContent>}
+ </Tooltip>
+ </div>
+ }
+ >
+ <div className="flex min-h-0 flex-1 flex-col">
+ <RunTemplateAdvancedPanel
+ open={advancedOpen}
+ onOpenChange={setAdvancedOpen}
+ templates={templates}
+ templatesLoading={templatesQuery.isLoading}
+ templatesError={templatesQuery.isError}
+ selectedTemplateId={selectedTemplateId}
+ selectedTemplate={selectedTemplate}
+ selectedTemplateName={selectedTemplateName}
+ onSelectTemplate={updateTemplateSelection}
+ onCreateTemplate={() => setTemplateDialog({ mode: "create" })}
+ onEditTemplate={(template) => setTemplateDialog({ mode: "edit", source: template })}
+ onDuplicateTemplate={(template) => setTemplateDialog({ mode: "create", source: template })}
+ onDeleteTemplate={(template) => {
+ if (
+ typeof window !== "undefined"
+ && !window.confirm(`Delete run template "${template.name}"?`)
+ ) {
+ return;
+ }
+ deleteTemplateMutation.mutate(template.id);
+ }}
+ deletingTemplateId={deleteTemplateMutation.variables ?? null}
+ actionPending={
+ createTemplateMutation.isPending
+ || updateTemplateMutation.isPending
+ || deleteTemplateMutation.isPending
+ }
+ />
+ {filterInput && (
+ <div className="px-3 pt-2">
+ <FilterBar
+ filters={[{ key: "input", label: "Input", value: filterInput.name }]}
+ onRemove={onClearFilter}
+ onClear={onClearFilter}
+ />
+ </div>
+ )}
+ <div className="min-h-0 flex-1 overflow-auto p-3">
+ {runsQuery.isLoading ? (
+ <div className="text-xs text-muted-foreground">Loading runs…</div>
+ ) : runs.length === 0 ? (
+ <EmptyState icon={FlaskConical} message="No test runs yet. Pick an agent and Run." />
+ ) : (
+ <div className="space-y-1 rounded-md border border-border p-1">
+ {runs.map((run) => (
+ <RunHistoryRow
+ key={run.id}
+ run={run}
+ agents={agents}
+ onSelect={() => onSelectRun(run.id)}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ <RunTemplateDialog
+ state={templateDialog}
+ pending={createTemplateMutation.isPending || updateTemplateMutation.isPending}
+ onOpenChange={(open) => {
+ if (!open) setTemplateDialog(null);
+ }}
+ onSubmit={(payload) => {
+ if (templateDialog?.mode === "edit") {
+ updateTemplateMutation.mutate({ templateId: templateDialog.source.id, payload });
+ } else {
+ createTemplateMutation.mutate(payload);
+ }
+ }}
+ />
+ </PaneScaffold>
+ );
+}
+
+type RunTemplateOption = SearchableSelectOption<string> & {
+ description: string | null;
+ builtIn: boolean;
+};
+
+function runTemplateOptionValue(selection: RunTemplateSelection) {
+ return selection ?? NO_TEST_RUN_TEMPLATE_STORAGE_VALUE;
+}
+
+function runTemplateSelectionFromOption(value: string): RunTemplateSelection {
+ return value === NO_TEST_RUN_TEMPLATE_STORAGE_VALUE ? null : value;
+}
+
+function RunTemplateAdvancedPanel({
+ open,
+ onOpenChange,
+ templates,
+ templatesLoading,
+ templatesError,
+ selectedTemplateId,
+ selectedTemplate,
+ selectedTemplateName,
+ onSelectTemplate,
+ onCreateTemplate,
+ onEditTemplate,
+ onDuplicateTemplate,
+ onDeleteTemplate,
+ deletingTemplateId,
+ actionPending,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ templates: CompanySkillTestRunTemplate[];
+ templatesLoading: boolean;
+ templatesError: boolean;
+ selectedTemplateId: RunTemplateSelection;
+ selectedTemplate: CompanySkillTestRunTemplate | null;
+ selectedTemplateName: string;
+ onSelectTemplate: (selection: RunTemplateSelection) => void;
+ onCreateTemplate: () => void;
+ onEditTemplate: (template: CompanySkillTestRunTemplate) => void;
+ onDuplicateTemplate: (template: CompanySkillTestRunTemplate) => void;
+ onDeleteTemplate: (template: CompanySkillTestRunTemplate) => void;
+ deletingTemplateId: string | null;
+ actionPending: boolean;
+}) {
+ const templateGroups = useMemo<readonly SearchableSelectGroup<string, RunTemplateOption>[]>(() => {
+ const noTemplateOption: RunTemplateOption = {
+ key: "no-template",
+ value: NO_TEST_RUN_TEMPLATE_STORAGE_VALUE,
+ label: "No template",
+ title: "No template",
+ description: "Run only the input text.",
+ builtIn: true,
+ searchText: "no template plain input",
+ };
+ const toOption = (template: CompanySkillTestRunTemplate): RunTemplateOption => ({
+ key: template.id,
+ value: template.id,
+ label: template.name,
+ title: template.name,
+ description: template.description,
+ builtIn: template.builtIn,
+ searchText: [template.name, template.description ?? "", template.builtIn ? "built in" : "custom"].join(" "),
+ });
+ const builtIn = templates.filter((template) => template.builtIn).map(toOption);
+ const custom = templates.filter((template) => !template.builtIn).map(toOption);
+ return [
+ { id: "built-in", label: "Built in", options: [noTemplateOption, ...builtIn] },
+ ...(custom.length > 0 ? [{ id: "custom", label: "Custom", options: custom }] : []),
+ ];
+ }, [templates]);
+
+ const selectedValue = runTemplateOptionValue(selectedTemplateId);
+ const selectedMissing = selectedTemplateId !== null && !selectedTemplate && !templatesLoading;
+ const canEdit = Boolean(selectedTemplate && !selectedTemplate.builtIn);
+ const canDuplicate = Boolean(selectedTemplate);
+ const canDelete = Boolean(selectedTemplate && !selectedTemplate.builtIn);
+
+ return (
+ <div className="border-b border-border">
+ <button
+ type="button"
+ className="flex min-h-(--sz-32px) w-full items-center gap-2 px-3 py-2 text-left text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
+ onClick={() => onOpenChange(!open)}
+ >
+ {open ? (
+ <ChevronDown className="h-3.5 w-3.5" />
+ ) : (
+ <ChevronRight className="h-3.5 w-3.5" />
+ )}
+ <span className="font-semibold uppercase tracking-wide">Advanced</span>
+ <span className="ml-auto truncate">{selectedTemplateName}</span>
+ </button>
+ {open ? (
+ <div className="space-y-3 px-3 pb-3 pt-1">
+ <div className="flex items-end gap-2">
+ <div className="min-w-0 flex-1 space-y-1">
+ <Label>Run template</Label>
+ <SearchableSelect<string, RunTemplateOption>
+ value={selectedValue}
+ groups={templateGroups}
+ loading={templatesLoading}
+ disabled={templatesLoading || templatesError}
+ loadingMessage="Loading templates..."
+ placeholder="Select template"
+ searchPlaceholder="Search templates..."
+ emptyMessage="No templates."
+ contentClassName="w-(--sz-320px)"
+ onValueChange={(value) => onSelectTemplate(runTemplateSelectionFromOption(value))}
+ renderValue={(option) => option?.label ?? selectedTemplateName}
+ renderOption={(option, { selected }) => (
+ <span className="flex min-w-0 flex-col">
+ <span className={cn("truncate", selected && "font-medium")}>{option.label}</span>
+ <span className="truncate text-(length:--text-micro) text-muted-foreground">
+ {option.description ?? (option.builtIn ? "Built in" : "Custom")}
+ </span>
+ </span>
+ )}
+ />
+ </div>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon-sm"
+ aria-label="Create run template"
+ disabled={actionPending}
+ onClick={onCreateTemplate}
+ >
+ <Plus />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Create run template</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Edit run template"
+ disabled={!canEdit || actionPending}
+ onClick={() => selectedTemplate && onEditTemplate(selectedTemplate)}
+ >
+ <Pencil />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Edit custom template</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Duplicate run template"
+ disabled={!canDuplicate || actionPending}
+ onClick={() => selectedTemplate && onDuplicateTemplate(selectedTemplate)}
+ >
+ <Copy />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ {selectedTemplate?.builtIn ? "Duplicate built-in template" : "Duplicate template"}
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Delete run template"
+ className="text-destructive hover:text-destructive"
+ disabled={!canDelete || actionPending || deletingTemplateId === selectedTemplate?.id}
+ onClick={() => selectedTemplate && onDeleteTemplate(selectedTemplate)}
+ >
+ <Trash2 />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Delete custom template</TooltipContent>
+ </Tooltip>
+ </div>
+
+ {templatesError ? (
+ <p className="text-xs text-destructive">Run templates could not load.</p>
+ ) : selectedTemplateId === null ? (
+ <p className="text-xs text-muted-foreground">Runs will use only the input text.</p>
+ ) : selectedMissing ? (
+ <p className="text-xs text-destructive">Selected template is no longer available.</p>
+ ) : selectedTemplate ? (
+ <div className="space-y-2">
+ {selectedTemplate.description ? (
+ <p className="text-xs text-muted-foreground">{selectedTemplate.description}</p>
+ ) : null}
+ <pre className="max-h-(--sz-240px) overflow-auto whitespace-pre-wrap rounded-md border border-border bg-muted/30 p-3 text-xs leading-5 text-muted-foreground">
+ {selectedTemplate.body}
+ </pre>
+ </div>
+ ) : (
+ <p className="text-xs text-muted-foreground">Loading template...</p>
+ )}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+function RunTemplateDialog({
+ state,
+ pending,
+ onOpenChange,
+ onSubmit,
+}: {
+ state: RunTemplateDialogState;
+ pending: boolean;
+ onOpenChange: (open: boolean) => void;
+ onSubmit: (payload: CompanySkillTestRunTemplateCreateRequest) => void;
+}) {
+ const source = state?.source ?? null;
+ const [name, setName] = useState("");
+ const [description, setDescription] = useState("");
+ const [body, setBody] = useState("");
+
+ useEffect(() => {
+ if (!state) return;
+ setName(state.mode === "edit" ? source?.name ?? "" : source ? `${source.name} copy` : "");
+ setDescription(source?.description ?? "");
+ setBody(source?.body ?? "");
+ }, [source, state]);
+
+ const title = state?.mode === "edit"
+ ? "Edit run template"
+ : source?.builtIn
+ ? "Duplicate built-in template"
+ : "Create run template";
+ const descriptionText = state?.mode === "edit"
+ ? "Update the custom run instructions used by Skills Studio."
+ : "Save reusable run instructions for Skills Studio.";
+
+ return (
+ <Dialog open={Boolean(state)} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription>{descriptionText}</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-3">
+ <div className="space-y-1">
+ <Label htmlFor="run-template-name">Name</Label>
+ <Input
+ id="run-template-name"
+ value={name}
+ onChange={(event) => setName(event.target.value)}
+ placeholder="Focused smoke"
+ />
+ </div>
+ <div className="space-y-1">
+ <Label htmlFor="run-template-description">Description</Label>
+ <Input
+ id="run-template-description"
+ value={description}
+ onChange={(event) => setDescription(event.target.value)}
+ placeholder="Short instructions for common skill checks"
+ />
+ </div>
+ <div className="space-y-1">
+ <Label htmlFor="run-template-body">Body</Label>
+ <Textarea
+ id="run-template-body"
+ value={body}
+ onChange={(event) => setBody(event.target.value)}
+ className="min-h-(--sz-240px) font-mono text-xs leading-5"
+ />
+ <p className="text-xs text-muted-foreground">
+ Placeholders: {"{{skillName}}"}, {"{{skillKey}}"}, {"{{skillInvocation}}"}, {"{{skillVersion}}"}, {"{{runId}}"}, {"{{issueId}}"}, {"{{outputDocumentKey}}"}.
+ </p>
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button
+ disabled={!name.trim() || !body.trim() || pending}
+ onClick={() =>
+ onSubmit({
+ name: name.trim(),
+ description: description.trim() || null,
+ body,
+ })
+ }
+ >
+ {pending ? "Saving..." : "Save template"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function RunHistoryRow({
+ run,
+ agents,
+ onSelect,
+}: {
+ run: CompanySkillTestRun;
+ agents: Agent[];
+ onSelect: () => void;
+}) {
+ const agent = agents.find((a) => a.id === run.agentId) ?? null;
+ const removed = !agent;
+ const snapshotName =
+ (run.agentConfigSnapshot?.name as string | undefined) ?? "Agent";
+ const name = agent?.name ?? snapshotName;
+ return (
+ <EntityRow
+ leading={<StatusBadge status={runBadgeStatus(run.status)} />}
+ identifier={runShortId(run)}
+ title={removed ? `${name} (removed)` : name}
+ subtitle={relativeTime(run.createdAt)}
+ trailing={
+ <span className="font-mono text-xs text-muted-foreground">
+ {formatCents(run.cost.costCents)}
+ </span>
+ }
+ onClick={onSelect}
+ />
+ );
+}
+
+function AgentPicker({
+ agents,
+ selectedAgent,
+ onSelect,
+}: {
+ agents: Agent[];
+ selectedAgent: Agent | null;
+ onSelect: (id: string) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button variant="outline" size="sm">
+ {selectedAgent ? (
+ <Identity name={selectedAgent.name} size="xs" />
+ ) : (
+ <span className="text-muted-foreground">Pick an agent</span>
+ )}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-64 p-0">
+ <Command>
+ <CommandInput placeholder="Search agents…" />
+ <CommandList>
+ <CommandEmpty>No agents.</CommandEmpty>
+ <CommandGroup>
+ {agents.map((agent) => {
+ const selectable = isAgentSelectable(agent);
+ return (
+ <CommandItem
+ key={agent.id}
+ value={agent.name}
+ disabled={!selectable}
+ onSelect={() => {
+ if (!selectable) return;
+ onSelect(agent.id);
+ setOpen(false);
+ }}
+ className={cn("flex items-center gap-2", !selectable && "opacity-50")}
+ >
+ <span
+ className={cn(
+ "h-2 w-2 rounded-full",
+ selectable ? "bg-green-500" : "bg-orange-400",
+ )}
+ aria-hidden
+ />
+ <Identity name={agent.name} size="xs" />
+ {!selectable && (
+ <Badge variant="secondary" className="ml-auto">
+ Paused
+ </Badge>
+ )}
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Run detail
+// ---------------------------------------------------------------------------
+
+function RunDetailView({
+ companyId,
+ skill,
+ runId,
+ agents,
+ onBack,
+ onSelectRun,
+}: {
+ companyId: string;
+ skill: CompanySkillDetail;
+ runId: string;
+ agents: Agent[];
+ onBack: () => void;
+ onSelectRun: (id: string | null) => void;
+}) {
+ const skillId = skill.id;
+ const queryClient = useQueryClient();
+ const onError = useMutationErrorToast();
+ const detailQuery = useQuery({
+ queryKey: queryKeys.companySkills.testRunDetail(companyId, skillId, runId),
+ queryFn: () => companySkillsApi.testRunDetail(companyId, skillId, runId),
+ enabled: Boolean(companyId && skillId && runId),
+ refetchInterval: (query) => {
+ const data = query.state.data as CompanySkillTestRunDetail | undefined;
+ return data && shouldPollRun(data.status) ? POLL_MS : false;
+ },
+ });
+
+ const cancelMutation = useMutation({
+ mutationFn: () => companySkillsApi.cancelTestRun(companyId, skillId, runId),
+ onSuccess: () =>
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.testRunDetail(companyId, skillId, runId),
+ }),
+ onError: onError("Couldn't cancel run"),
+ });
+
+ // Re-run reproduces the VIEWED run's snapshots — pinned skill version, saved
+ // input (or the ad-hoc snapshot), and agent — rather than whatever the picker
+ // happens to hold this session (PAP-13001 Bug A). Reading detailQuery.data at
+ // mutate() time keeps the hook order stable across the loading guards below.
+ const reRunMutation = useMutation({
+ mutationFn: () => {
+ const d = detailQuery.data;
+ if (!d) throw new Error("Run details are still loading.");
+ return companySkillsApi.createTestRun(companyId, skillId, buildReRunRequest(d));
+ },
+ onSuccess: (run) => {
+ queryClient.invalidateQueries({
+ queryKey: ["company-skills", companyId, skillId, "test-runs"],
+ });
+ onSelectRun(run.id);
+ },
+ onError: onError("Couldn't re-run"),
+ });
+
+ const deleteMutation = useMutation({
+ mutationFn: () => companySkillsApi.deleteTestRun(companyId, skillId, runId),
+ onSuccess: () => {
+ queryClient.invalidateQueries({
+ queryKey: ["company-skills", companyId, skillId, "test-runs"],
+ });
+ onSelectRun(null);
+ },
+ onError: onError("Couldn't delete run"),
+ });
+
+ const detail = detailQuery.data ?? null;
+ const additionalDocuments = useMemo(() => detail ? getRunAdditionalDocuments(detail) : [], [detail]);
+ const rawAttachments = useMemo(() => detail ? getRunRawAttachments(detail) : [], [detail]);
+ const unavailableCopy = useMemo(() => detail ? runHarnessUnavailableCopy(detail) : null, [detail]);
+ const mediaGalleryItems = useMemo<GalleryMediaItem[]>(
+ () => detail ? getRunMediaGalleryItems(detail) : [],
+ [detail],
+ );
+ const [galleryOpen, setGalleryOpen] = useState(false);
+ const [galleryIndex, setGalleryIndex] = useState(0);
+
+ if (detailQuery.isLoading) {
+ return (
+ <PaneScaffold title="Run" action={<BackButton onBack={onBack} />}>
+ <div className="p-3 text-xs text-muted-foreground">Loading run…</div>
+ </PaneScaffold>
+ );
+ }
+ if (!detail) {
+ return (
+ <PaneScaffold title="Run" action={<BackButton onBack={onBack} />}>
+ <div className="p-3 text-xs text-muted-foreground">Run not found.</div>
+ </PaneScaffold>
+ );
+ }
+
+ const agent = agents.find((a) => a.id === detail.agentId) ?? null;
+ const agentName =
+ agent?.name ?? (detail.agentConfigSnapshot?.name as string | undefined) ?? "Agent";
+ const removed = !agent;
+ const outputMode = runOutputMode(detail);
+ const nonTerminal = !isTerminalRunStatus(detail.status);
+ const taskLink = testTaskLinkState(detail);
+
+ return (
+ <PaneScaffold title="Run" action={<BackButton onBack={onBack} />}>
+ <div className="min-h-0 flex-1 space-y-3 overflow-auto p-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <StatusBadge status={runBadgeStatus(detail.status)} />
+ <Identity name={agentName} size="xs" />
+ {removed && <Badge variant="secondary">removed</Badge>}
+ <span className="font-mono text-xs text-muted-foreground">
+ v{detail.skillVersion.revisionNumber}
+ </span>
+ <span className="ml-auto font-mono text-xs text-muted-foreground">
+ {formatCents(detail.cost.costCents)}
+ </span>
+ </div>
+
+ {/* snapshot property block */}
+ <div className="rounded-md border border-border text-xs">
+ <PropRow label="Input" value={detail.inputId ? "saved input" : "ad-hoc paste"} />
+ <PropRow label="Template" value={detail.templateName ?? "No template"} />
+ <PropRow label="Skill version" value={`v${detail.skillVersion.revisionNumber}`} />
+ <PropRow label="Created" value={relativeTime(detail.createdAt)} />
+ </div>
+
+ {showRunErrorCard(detail.status) && (
+ <Card className="border-destructive/50">
+ <CardHeader className="flex-row items-center gap-2 space-y-0 pb-2">
+ <AlertTriangle className="h-3.5 w-3.5 text-destructive" />
+ <span className="text-sm font-medium">Run failed</span>
+ </CardHeader>
+ <CardContent className="text-sm text-muted-foreground">
+ {detail.error ?? "The test task ended with an error."}
+ </CardContent>
+ </Card>
+ )}
+
+ {/* Output snapshot / draft-at-failure */}
+ {outputMode === "output" || outputMode === "draft" ? (
+ <section className="space-y-2">
+ <h3 className="mb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ {outputMode === "draft" ? "Draft at failure" : "Output snapshot"}
+ </h3>
+ <div className="rounded-md border border-border p-3">
+ <MarkdownBody>{detail.outputBody || "_No output_"}</MarkdownBody>
+ </div>
+ </section>
+ ) : outputMode === "pending" ? (
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Clock className="h-3.5 w-3.5" /> Working… output will appear here.
+ </div>
+ ) : null}
+
+ {unavailableCopy ? (
+ <RunHarnessUnavailableNotice copy={unavailableCopy} />
+ ) : null}
+
+ {additionalDocuments.length > 0 ? (
+ <RunDocumentsSection documents={additionalDocuments} />
+ ) : null}
+
+ <IssueOutputSection
+ workProducts={detail.harnessContent.workProducts}
+ onMediaClick={(item) => {
+ const meta = item.metadata;
+ if (!meta) return;
+ const idx = mediaGalleryItems.findIndex((galleryItem) => (
+ galleryItem.contentPath === meta.contentPath ||
+ galleryItem.id === `work-product-${item.id}` ||
+ galleryItem.id === meta.attachmentId
+ ));
+ setGalleryIndex(idx >= 0 ? idx : 0);
+ setGalleryOpen(true);
+ }}
+ />
+
+ {rawAttachments.length > 0 ? (
+ <IssueAttachmentsSection
+ attachments={rawAttachments}
+ onImageClick={(attachment) => {
+ const idx = mediaGalleryItems.findIndex((item) => (
+ item.id === attachment.id || item.contentPath === attachment.contentPath
+ ));
+ setGalleryIndex(idx >= 0 ? idx : 0);
+ setGalleryOpen(true);
+ }}
+ />
+ ) : null}
+
+ {/* Interactions */}
+ <InteractionSection
+ companyId={companyId}
+ detail={detail}
+ agents={agents}
+ onAnswered={() =>
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.testRunDetail(companyId, skillId, runId),
+ })
+ }
+ />
+
+ {/* Actions */}
+ <div className="flex flex-wrap items-center gap-2 border-t border-border pt-3">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={reRunMutation.isPending}
+ onClick={() => reRunMutation.mutate()}
+ >
+ <RotateCcw className="mr-1.5 h-3.5 w-3.5" /> Re-run
+ </Button>
+ {nonTerminal ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={cancelMutation.isPending}
+ onClick={() => cancelMutation.mutate()}
+ >
+ Cancel
+ </Button>
+ ) : (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-destructive hover:text-destructive"
+ disabled={deleteMutation.isPending}
+ onClick={() => deleteMutation.mutate()}
+ >
+ <Trash2 className="mr-1.5 h-3.5 w-3.5" /> Delete
+ </Button>
+ )}
+ {taskLink.enabled && detail.harnessIssue ? (
+ <Button variant="link" size="sm" asChild>
+ <Link to={`/issues/${detail.harnessIssue.id}`}>Open test task ↗</Link>
+ </Button>
+ ) : (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="cursor-not-allowed text-xs text-muted-foreground">
+ Open test task ↗
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{taskLink.reason}</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+
+ <ImageGalleryModal
+ items={mediaGalleryItems}
+ initialIndex={galleryIndex}
+ open={galleryOpen}
+ onOpenChange={setGalleryOpen}
+ />
+ </div>
+ </PaneScaffold>
+ );
+}
+
+function RunHarnessUnavailableNotice({
+ copy,
+}: {
+ copy: NonNullable<ReturnType<typeof runHarnessUnavailableCopy>>;
+}) {
+ return (
+ <div className="flex items-start gap-2 rounded-md border border-border bg-muted/30 p-3 text-xs">
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 space-y-1">
+ <p className="font-medium text-foreground">{copy.title}</p>
+ <p className="text-muted-foreground">{copy.body}</p>
+ </div>
+ </div>
+ );
+}
+
+function RunDocumentsSection({ documents }: { documents: IssueDocument[] }) {
+ return (
+ <section className="space-y-2">
+ <div className="flex items-center gap-2">
+ <FileText className="h-3.5 w-3.5 text-muted-foreground" aria-hidden="true" />
+ <h3 className="text-sm font-medium text-muted-foreground">Documents</h3>
+ <span className="text-xs text-muted-foreground">{documents.length}</span>
+ </div>
+ <div className="space-y-2">
+ {documents.map((document) => (
+ <article key={document.id} className="rounded-md border border-border p-3">
+ <div className="mb-2 flex min-w-0 items-center gap-2 text-xs text-muted-foreground">
+ <span className="truncate font-medium text-foreground">
+ {document.title ?? document.key}
+ </span>
+ <span className="ml-auto shrink-0">{relativeTime(document.updatedAt)}</span>
+ </div>
+ <MarkdownBody className="paperclip-edit-in-place-content text-sm leading-7" softBreaks={false}>
+ {document.body}
+ </MarkdownBody>
+ </article>
+ ))}
+ </div>
+ </section>
+ );
+}
+
+function InteractionSection({
+ companyId,
+ detail,
+ agents,
+ onAnswered,
+}: {
+ companyId: string;
+ detail: CompanySkillTestRunDetail;
+ agents: Agent[];
+ onAnswered: () => void;
+}) {
+ const harnessIssueId = detail.harnessIssue?.id ?? null;
+ const hasInlineAnswerable = detail.interactions.some((i) => isInteractionAnswerable(i));
+
+ // Only fetch the full interaction objects (needed to render answerable cards)
+ // when there is at least one pending inline interaction on a live harness issue.
+ const fullQuery = useQuery({
+ queryKey: ["skill-studio", "interactions", harnessIssueId],
+ queryFn: () => issuesApi.listInteractions(harnessIssueId!),
+ enabled: Boolean(harnessIssueId && hasInlineAnswerable),
+ refetchInterval: hasInlineAnswerable ? POLL_MS : false,
+ });
+ const fullById = useMemo(
+ () => new Map((fullQuery.data ?? []).map((i) => [i.id, i])),
+ [fullQuery.data],
+ );
+ const agentMap = useMemo(() => new Map(agents.map((a) => [a.id, a])), [agents]);
+
+ const accept = useMutation({
+ mutationFn: (vars: { interaction: IssueThreadInteraction; optionIds?: string[] }) =>
+ issuesApi.acceptInteraction(harnessIssueId!, vars.interaction.id, {
+ selectedOptionIds: vars.optionIds,
+ }),
+ onSuccess: onAnswered,
+ });
+ const respond = useMutation({
+ mutationFn: (vars: { interaction: AskUserQuestionsInteraction; answers: AskUserQuestionsAnswer[] }) =>
+ issuesApi.respondToInteraction(harnessIssueId!, vars.interaction.id, { answers: vars.answers }),
+ onSuccess: onAnswered,
+ });
+ const reject = useMutation({
+ mutationFn: (vars: { interaction: IssueThreadInteraction; reason?: string }) =>
+ issuesApi.rejectInteraction(harnessIssueId!, vars.interaction.id, vars.reason),
+ onSuccess: onAnswered,
+ });
+
+ if (detail.interactions.length === 0) return null;
+
+ return (
+ <section>
+ <h3 className="mb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ Interactions
+ </h3>
+ <div className="space-y-2">
+ {detail.interactions.map((summary) => {
+ const inline = routeInteraction(summary.kind) === "inline";
+ const full = fullById.get(summary.id);
+ if (inline && full) {
+ return (
+ <IssueThreadInteractionCard
+ key={summary.id}
+ interaction={full}
+ agentMap={agentMap}
+ onAcceptInteraction={async (interaction, _keys, optionIds) => {
+ await accept.mutateAsync({ interaction, optionIds });
+ }}
+ onRejectInteraction={async (interaction, reason) => {
+ await reject.mutateAsync({ interaction, reason });
+ }}
+ onSubmitInteractionAnswers={async (interaction, answers) => {
+ await respond.mutateAsync({ interaction, answers });
+ }}
+ />
+ );
+ }
+ // Fallback: summary row + open-test-task link (never dropped).
+ return (
+ <EntityRow
+ key={summary.id}
+ title={summary.title}
+ subtitle={`${summary.kind} · ${summary.status}`}
+ trailing={
+ harnessIssueId ? (
+ <Button variant="link" size="xs" asChild>
+ <Link to={`/issues/${harnessIssueId}`}>Open test task ↗</Link>
+ </Button>
+ ) : null
+ }
+ />
+ );
+ })}
+ </div>
+ </section>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Version history drawer
+// ---------------------------------------------------------------------------
+
+function VersionHistorySheet({
+ open,
+ onOpenChange,
+ companyId,
+ skill,
+ onRestored,
+ onFilterRuns,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ companyId: string;
+ skill: CompanySkillDetail;
+ onRestored: () => void;
+ onFilterRuns: (inputId: string) => void;
+}) {
+ const skillId = skill.id;
+ const queryClient = useQueryClient();
+ const versionsQuery = useQuery({
+ queryKey: queryKeys.companySkills.versions(companyId, skillId),
+ queryFn: () => companySkillsApi.versions(companyId, skillId),
+ enabled: open && Boolean(companyId && skillId),
+ });
+ const versions = versionsQuery.data ?? [];
+ const [leftId, setLeftId] = useState<string | null>(null);
+ const [rightId, setRightId] = useState<string | null>(null);
+
+ const restore = useMutation({
+ mutationFn: async (version: CompanySkillVersion) => {
+ // Restore = write each file from the chosen version back, then cut a new
+ // head version (immutability: never rewrites history).
+ for (const file of version.fileInventory) {
+ await companySkillsApi.updateFile(companyId, skillId, file.path, file.content);
+ }
+ return companySkillsApi.createVersion(companyId, skillId, {
+ label: `Restore of v${version.revisionNumber}`,
+ });
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.versions(companyId, skillId) });
+ onRestored();
+ },
+ });
+
+ const left = versions.find((v) => v.id === leftId) ?? null;
+ const right = versions.find((v) => v.id === rightId) ?? null;
+ const diff = left && right ? buildLineDiff(
+ left.fileInventory.map((f) => `# ${f.path}\n${f.content}`).join("\n\n"),
+ right.fileInventory.map((f) => `# ${f.path}\n${f.content}`).join("\n\n"),
+ ) : null;
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent side="left" className="w-full sm:max-w-(--sz-560px)">
+ <SheetHeader>
+ <SheetTitle>Version history</SheetTitle>
+ </SheetHeader>
+ <div className="mt-3 space-y-2 overflow-auto">
+ {versionsQuery.isLoading ? (
+ <div className="text-xs text-muted-foreground">Loading versions…</div>
+ ) : versions.length === 0 ? (
+ <EmptyState icon={History} message="No versions yet. Save changes to create the first." />
+ ) : (
+ <div className="space-y-1 rounded-md border border-border p-1">
+ {versions.map((v) => (
+ <EntityRow
+ key={v.id}
+ identifier={`v${v.revisionNumber}`}
+ title={v.label ?? `Version ${v.revisionNumber}`}
+ subtitle={relativeTime(v.createdAt)}
+ selected={v.id === leftId || v.id === rightId}
+ onClick={() => {
+ // click to build a two-version diff selection
+ if (!leftId) setLeftId(v.id);
+ else if (!rightId && v.id !== leftId) setRightId(v.id);
+ else {
+ setLeftId(v.id);
+ setRightId(null);
+ }
+ }}
+ trailing={
+ <Button
+ variant="outline"
+ size="xs"
+ disabled={restore.isPending}
+ onClick={(e) => {
+ e.stopPropagation();
+ restore.mutate(v);
+ }}
+ >
+ Restore as v{(skill.currentVersion?.revisionNumber ?? v.revisionNumber) + 1}
+ </Button>
+ }
+ />
+ ))}
+ </div>
+ )}
+ {diff && (
+ <div className="rounded-md border border-border">
+ <div className="border-b border-border px-3 py-1.5 text-xs text-muted-foreground">
+ Diff v{left?.revisionNumber} → v{right?.revisionNumber}
+ </div>
+ <pre className="max-h-64 overflow-auto p-2 text-xs">
+ {diff.map((row, i) => (
+ <div
+ key={i}
+ className={cn(
+ "whitespace-pre-wrap",
+ row.kind === "added" && "bg-green-500/10 text-green-700 dark:text-green-300",
+ row.kind === "removed" && "bg-red-500/10 text-red-700 dark:text-red-300",
+ )}
+ >
+ {row.kind === "added" ? "+" : row.kind === "removed" ? "-" : " "}
+ {row.text}
+ </div>
+ ))}
+ </pre>
+ </div>
+ )}
+ </div>
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Shared bits
+// ---------------------------------------------------------------------------
+
+function PaneScaffold({
+ title,
+ action,
+ children,
+}: {
+ title: React.ReactNode;
+ action?: React.ReactNode;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <div className="flex items-center justify-between gap-2 border-b border-border px-3 py-2">
+ <span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ {title}
+ </span>
+ {action}
+ </div>
+ <div className="flex min-h-0 flex-1 flex-col">{children}</div>
+ </div>
+ );
+}
+
+function PropRow({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="flex items-center justify-between gap-2 border-b border-border px-3 py-1.5 last:border-b-0">
+ <span className="text-muted-foreground">{label}</span>
+ <span className="truncate">{value}</span>
+ </div>
+ );
+}
+
+function BackButton({ onBack }: { onBack: () => void }) {
+ return (
+ <Button variant="ghost" size="sm" onClick={onBack}>
+ <ArrowLeft className="mr-1.5 h-3.5 w-3.5" /> Back
+ </Button>
+ );
+}
+
+function MobileTabs({
+ skill,
+ input,
+ runs,
+}: {
+ skill: React.ReactNode;
+ input: React.ReactNode;
+ runs: React.ReactNode;
+}) {
+ return (
+ <Tabs defaultValue="skill" className="flex flex-1 flex-col">
+ <TabsList variant="line" className="px-3">
+ <TabsTrigger value="skill">Skill</TabsTrigger>
+ <TabsTrigger value="input">Input</TabsTrigger>
+ <TabsTrigger value="runs">Runs</TabsTrigger>
+ </TabsList>
+ <TabsContent value="skill" className="min-h-0 flex-1">
+ {skill}
+ </TabsContent>
+ <TabsContent value="input" className="min-h-0 flex-1">
+ {input}
+ </TabsContent>
+ <TabsContent value="runs" className="min-h-0 flex-1">
+ {runs}
+ </TabsContent>
+ </Tabs>
+ );
+}
diff --git a/ui/src/pages/agent-skills/AgentSkillRow.tsx b/ui/src/pages/agent-skills/AgentSkillRow.tsx
new file mode 100644
index 0000000000..acbb2eebd7
--- /dev/null
+++ b/ui/src/pages/agent-skills/AgentSkillRow.tsx
@@ -0,0 +1,139 @@
+import { Lock, type LucideIcon } from "lucide-react";
+import { Link } from "@/lib/router";
+import { cn } from "@/lib/utils";
+import { ToggleSwitch } from "@/components/ui/toggle-switch";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { SkillCardIcon, type SkillIconCard } from "../../components/SkillCardIcon";
+import type { AgentSkillSearchFields } from "./agent-skill-filter";
+
+export type AgentSkillRowVariant = "enabled" | "available" | "readonly";
+
+export interface AgentSkillRowData extends AgentSkillSearchFields {
+ /** Skill key — used as React key and for toggle callbacks. */
+ key: string;
+ name: string;
+ /** Icon inputs (iconUrl / color / slug / key / name). */
+ icon: SkillIconCard;
+ /** One-line resolved summary (tagline → description → key fallback). */
+ summary: string | null;
+ /** Small chip label for the primary category. */
+ chip?: string | null;
+ /** Formatted source/provenance text rendered without badge chrome. */
+ sourceMeta?: {
+ icon: LucideIcon;
+ label: string;
+ } | null;
+ /** Route to the skill detail page; null makes the row non-navigable. */
+ linkTo: string | null;
+ /** Read-only metadata (adapter-detected skills). */
+ originLabel?: string | null;
+ locationLabel?: string | null;
+}
+
+export interface AgentSkillRowProps {
+ variant: AgentSkillRowVariant;
+ data: AgentSkillRowData;
+ checked?: boolean;
+ disabled?: boolean;
+ /** Tooltip shown on a disabled toggle (unsupported adapter). */
+ disabledReason?: string | null;
+ onCheckedChange?: (checked: boolean) => void;
+}
+
+/**
+ * Dense presentational row for the agent Skills tab: 32px icon, name (links to
+ * the skill detail page), one-line clamped tagline, category chip, source
+ * metadata, and a right-aligned toggle (or a lock icon for read-only
+ * adapter-detected skills).
+ */
+export function AgentSkillRow({
+ variant,
+ data,
+ checked = false,
+ disabled = false,
+ disabledReason,
+ onCheckedChange,
+}: AgentSkillRowProps) {
+ const readOnly = variant === "readonly";
+ const SourceIcon = data.sourceMeta?.icon;
+
+ const leading = (
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ <SkillCardIcon card={data.icon} size={32} />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="truncate text-sm font-medium text-foreground">{data.name}</span>
+ {data.chip ? (
+ <span className="hidden shrink-0 items-center rounded-full border border-border bg-muted/40 px-2 py-0.5 text-(length:--text-nano) capitalize text-muted-foreground sm:inline-flex">
+ {data.chip}
+ </span>
+ ) : null}
+ </div>
+ {data.summary ? (
+ <p className="mt-0.5 truncate text-xs text-muted-foreground">{data.summary}</p>
+ ) : null}
+ {data.sourceMeta && SourceIcon ? (
+ <p className="mt-0.5 flex min-w-0 items-center gap-1 text-(length:--text-nano) text-muted-foreground/80">
+ <SourceIcon className="h-3 w-3 shrink-0" aria-hidden="true" />
+ <span className="truncate">{data.sourceMeta.label}</span>
+ </p>
+ ) : null}
+ {readOnly && data.originLabel ? (
+ <p className="mt-0.5 truncate text-(length:--text-nano) text-muted-foreground/80">
+ {data.originLabel}
+ {data.locationLabel ? ` · ${data.locationLabel}` : ""}
+ </p>
+ ) : null}
+ </div>
+ </div>
+ );
+
+ const rowClass = cn(
+ "flex min-h-11 items-center gap-3 border-b border-border px-3 py-2.5 last:border-b-0",
+ readOnly ? "bg-muted/20" : "transition-colors hover:bg-accent/50",
+ );
+
+ const body = data.linkTo ? (
+ <Link
+ to={data.linkTo}
+ className="flex min-w-0 flex-1 items-center gap-3 no-underline outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm"
+ >
+ {leading}
+ </Link>
+ ) : (
+ leading
+ );
+
+ const trailing = readOnly ? (
+ <Lock className="h-4 w-4 shrink-0 text-muted-foreground/60" aria-label="Read-only" />
+ ) : (
+ (() => {
+ const toggle = (
+ <ToggleSwitch
+ checked={checked}
+ disabled={disabled}
+ onCheckedChange={(next) => onCheckedChange?.(next)}
+ aria-label={`${checked ? "Disable" : "Enable"} ${data.name}`}
+ />
+ );
+ if (disabled && disabledReason) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="shrink-0">{toggle}</span>
+ </TooltipTrigger>
+ <TooltipContent side="left">{disabledReason}</TooltipContent>
+ </Tooltip>
+ );
+ }
+ return <span className="shrink-0">{toggle}</span>;
+ })()
+ );
+
+ return (
+ <div className={rowClass}>
+ {body}
+ {trailing}
+ </div>
+ );
+}
diff --git a/ui/src/pages/agent-skills/AgentSkillsTab.tsx b/ui/src/pages/agent-skills/AgentSkillsTab.tsx
new file mode 100644
index 0000000000..ec419647ae
--- /dev/null
+++ b/ui/src/pages/agent-skills/AgentSkillsTab.tsx
@@ -0,0 +1,495 @@
+import { useEffect, useMemo, useRef, useState } from "react";
+import { Link } from "@/lib/router";
+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
+import { AlertCircle, CheckCircle2, ChevronDown, Loader2, Search, Store, X } from "lucide-react";
+import type { Agent } from "@paperclipai/shared";
+import { agentsApi } from "../../api/agents";
+import { companySkillsApi } from "../../api/companySkills";
+import { queryKeys } from "../../lib/queryKeys";
+import { resolveSkillSummaryText } from "../../lib/company-skill-summary";
+import { adapterLabels } from "../../components/agent-config-primitives";
+import { cn } from "../../lib/utils";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import { PageSkeleton } from "../../components/PageSkeleton";
+import {
+ applyAgentSkillSnapshot,
+ isReadOnlyUnmanagedSkillEntry,
+ sameSkillSelection,
+ shouldScheduleSkillAutosave,
+} from "../../lib/agent-skills-state";
+import { AgentSkillRow, type AgentSkillRowData } from "./AgentSkillRow";
+import { filterAgentSkills } from "./agent-skill-filter";
+import { buildAgentSkillSourceMeta } from "./agent-skill-source";
+
+const MATERIALIZATION_NOTE =
+ "Enabled skills are materialized into the stable Paperclip-managed prompt bundle on the agent's next run.";
+
+export function AgentSkillsTab({ agent, companyId }: { agent: Agent; companyId?: string }) {
+ const queryClient = useQueryClient();
+ const [skillDraft, setSkillDraft] = useState<string[]>([]);
+ const [lastSavedSkills, setLastSavedSkills] = useState<string[]>([]);
+ const [search, setSearch] = useState("");
+ const [detectedOpen, setDetectedOpen] = useState(false);
+ const lastSavedSkillsRef = useRef<string[]>([]);
+ const hasHydratedSkillSnapshotRef = useRef(false);
+ const skipNextSkillAutosaveRef = useRef(true);
+ // The exact draft of a save that failed, so we don't re-fire the identical
+ // payload on every `isPending` flip (that was an infinite 422 retry storm).
+ const failedSkillDraftRef = useRef<string[] | null>(null);
+
+ const { data: skillSnapshot, isLoading } = useQuery({
+ queryKey: queryKeys.agents.skills(agent.id),
+ queryFn: () => agentsApi.skills(agent.id, companyId),
+ enabled: Boolean(companyId),
+ });
+
+ const { data: companySkills } = useQuery({
+ queryKey: queryKeys.companySkills.list(companyId ?? ""),
+ queryFn: () => companySkillsApi.list(companyId!),
+ enabled: Boolean(companyId),
+ });
+
+ const syncSkills = useMutation({
+ mutationFn: (desiredSkills: string[]) => agentsApi.syncSkills(agent.id, desiredSkills, companyId),
+ onSuccess: async (snapshot) => {
+ queryClient.setQueryData(queryKeys.agents.skills(agent.id), snapshot);
+ lastSavedSkillsRef.current = snapshot.desiredSkills;
+ setLastSavedSkills(snapshot.desiredSkills);
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.id) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.urlKey) }),
+ ]);
+ },
+ onError: (_error, attemptedDesiredSkills) => {
+ // Remember the payload that failed so the autosave effect stops retrying
+ // it until the user edits the draft again.
+ failedSkillDraftRef.current = attemptedDesiredSkills;
+ },
+ });
+
+ useEffect(() => {
+ setSkillDraft([]);
+ setLastSavedSkills([]);
+ lastSavedSkillsRef.current = [];
+ hasHydratedSkillSnapshotRef.current = false;
+ skipNextSkillAutosaveRef.current = true;
+ failedSkillDraftRef.current = null;
+ }, [agent.id]);
+
+ useEffect(() => {
+ if (!skillSnapshot) return;
+ const nextState = applyAgentSkillSnapshot(
+ {
+ draft: skillDraft,
+ lastSaved: lastSavedSkillsRef.current,
+ hasHydratedSnapshot: hasHydratedSkillSnapshotRef.current,
+ },
+ skillSnapshot.desiredSkills,
+ );
+ skipNextSkillAutosaveRef.current = nextState.shouldSkipAutosave;
+ hasHydratedSkillSnapshotRef.current = nextState.hasHydratedSnapshot;
+ setSkillDraft(nextState.draft);
+ lastSavedSkillsRef.current = nextState.lastSaved;
+ setLastSavedSkills(nextState.lastSaved);
+ }, [skillDraft, skillSnapshot]);
+
+ useEffect(() => {
+ if (!skillSnapshot) return;
+ if (skipNextSkillAutosaveRef.current) {
+ skipNextSkillAutosaveRef.current = false;
+ return;
+ }
+ if (syncSkills.isPending) return;
+ if (
+ !shouldScheduleSkillAutosave({
+ draft: skillDraft,
+ lastSaved: lastSavedSkillsRef.current,
+ failedDraft: failedSkillDraftRef.current,
+ })
+ ) {
+ return;
+ }
+
+ const timeout = window.setTimeout(() => {
+ if (
+ shouldScheduleSkillAutosave({
+ draft: skillDraft,
+ lastSaved: lastSavedSkillsRef.current,
+ failedDraft: failedSkillDraftRef.current,
+ })
+ ) {
+ syncSkills.mutate(skillDraft);
+ }
+ }, 250);
+
+ return () => window.clearTimeout(timeout);
+ }, [skillDraft, skillSnapshot, syncSkills.isPending, syncSkills.isError, syncSkills.mutate]);
+
+ const companySkillByKey = useMemo(
+ () => new Map((companySkills ?? []).map((skill) => [skill.key, skill])),
+ [companySkills],
+ );
+ const companySkillKeys = useMemo(
+ () => new Set((companySkills ?? []).map((skill) => skill.key)),
+ [companySkills],
+ );
+ const adapterEntryByKey = useMemo(
+ () => new Map((skillSnapshot?.entries ?? []).map((entry) => [entry.key, entry])),
+ [skillSnapshot],
+ );
+
+ const unsupported = skillSnapshot?.mode === "unsupported";
+
+ // Library skills → row models (the store's visual language, tuned for rows).
+ const libraryRows = useMemo<AgentSkillRowData[]>(
+ () =>
+ (companySkills ?? []).map((skill) => ({
+ key: skill.key,
+ name: skill.name,
+ icon: {
+ key: skill.key,
+ name: skill.name,
+ slug: skill.slug,
+ iconUrl: skill.iconUrl,
+ color: skill.color,
+ },
+ summary: resolveSkillSummaryText(skill, { fallbackKey: true }),
+ chip: skill.categories[0] ?? null,
+ sourceMeta: buildAgentSkillSourceMeta(skill),
+ linkTo: `/skills/${skill.id}`,
+ // search haystack (mirrors the store's discoveryMatchesSearch fields)
+ slug: skill.slug,
+ author: skill.authorName ?? skill.sourceLabel,
+ tagline: skill.tagline,
+ description: skill.description,
+ categories: skill.categories,
+ })),
+ [companySkills],
+ );
+
+ // Adapter-detected, user-installed / unmanaged skills → read-only rows.
+ const detectedRows = useMemo<AgentSkillRowData[]>(
+ () =>
+ (skillSnapshot?.entries ?? [])
+ .filter((entry) => isReadOnlyUnmanagedSkillEntry(entry, companySkillKeys))
+ .map((entry) => ({
+ key: entry.key,
+ name: entry.runtimeName ?? entry.key,
+ icon: { key: entry.key, name: entry.runtimeName ?? entry.key, slug: null, iconUrl: null, color: null },
+ summary: entry.detail ?? null,
+ chip: null,
+ linkTo: null,
+ originLabel: entry.originLabel ?? null,
+ locationLabel: entry.locationLabel ?? null,
+ })),
+ [companySkillKeys, skillSnapshot],
+ );
+
+ const enabledRows = useMemo(
+ () => libraryRows.filter((row) => skillDraft.includes(row.key)),
+ [libraryRows, skillDraft],
+ );
+ const availableRows = useMemo(
+ () => libraryRows.filter((row) => !skillDraft.includes(row.key)),
+ [libraryRows, skillDraft],
+ );
+
+ // Desired keys that no longer exist in the library → actionable warnings.
+ const staleDesiredKeys = useMemo(
+ () => skillDraft.filter((key) => !companySkillByKey.has(key)),
+ [companySkillByKey, skillDraft],
+ );
+
+ const filteredEnabled = useMemo(() => filterAgentSkills(enabledRows, search), [enabledRows, search]);
+ const filteredAvailable = useMemo(() => filterAgentSkills(availableRows, search), [availableRows, search]);
+ const filteredDetected = useMemo(() => filterAgentSkills(detectedRows, search), [detectedRows, search]);
+
+ const applicationLabel = useMemo(() => {
+ switch (skillSnapshot?.mode) {
+ case "persistent":
+ return "Kept in workspace";
+ case "ephemeral":
+ return "Applied on next run";
+ case "unsupported":
+ return "Tracked only";
+ default:
+ return null;
+ }
+ }, [skillSnapshot?.mode]);
+
+ const unsupportedMessage = useMemo(() => {
+ if (!unsupported) return null;
+ if (
+ agent.adapterType === "acpx_local" &&
+ typeof agent.adapterConfig.agent === "string" &&
+ agent.adapterConfig.agent === "custom"
+ ) {
+ return "Paperclip cannot manage skills for custom ACP commands yet.";
+ }
+ if (agent.adapterType === "openclaw_gateway") {
+ return "Paperclip cannot manage OpenClaw skills here. Visit your OpenClaw instance to manage this agent's skills.";
+ }
+ return "Paperclip cannot manage skills for this adapter yet. Manage them in the adapter directly.";
+ }, [agent.adapterConfig.agent, agent.adapterType, unsupported]);
+
+ const hasUnsavedChanges = !sameSkillSelection(skillDraft, lastSavedSkills);
+
+ const toggleSkill = (key: string, next: boolean) => {
+ setSkillDraft((current) =>
+ next
+ ? Array.from(new Set([...current, key]))
+ : current.filter((value) => value !== key),
+ );
+ };
+
+ const renderRow = (row: AgentSkillRowData, variant: "enabled" | "available") => (
+ <AgentSkillRow
+ key={row.key}
+ variant={variant}
+ data={row}
+ checked={variant === "enabled"}
+ disabled={unsupported}
+ disabledReason={unsupportedMessage}
+ onCheckedChange={(next) => toggleSkill(row.key, next)}
+ />
+ );
+
+ const libraryEmpty = libraryRows.length === 0;
+
+ return (
+ <div className="max-w-4xl space-y-4">
+ {/* Header */}
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-sm font-medium text-foreground">
+ {enabledRows.length} of {libraryRows.length} enabled
+ </span>
+ {applicationLabel ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex cursor-default items-center rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs text-muted-foreground">
+ {applicationLabel}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="max-w-xs">
+ {unsupported ? unsupportedMessage : MATERIALIZATION_NOTE}
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
+ <SaveStatusChip
+ pending={syncSkills.isPending}
+ unsaved={hasUnsavedChanges}
+ error={syncSkills.isError && hasUnsavedChanges}
+ />
+ <div className="ml-auto flex w-full flex-col items-stretch gap-2 sm:w-auto sm:flex-row sm:items-center">
+ <div className="relative w-full sm:w-auto">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ placeholder="Search skills"
+ className="h-8 w-full pl-8 sm:w-56"
+ aria-label="Search skills"
+ />
+ </div>
+ <Button asChild variant="outline" size="sm" className="shrink-0">
+ <Link to="/skills" className="no-underline">
+ <Store className="h-3.5 w-3.5" />
+ Browse skills store
+ </Link>
+ </Button>
+ </div>
+ </div>
+
+ {syncSkills.isError ? (
+ <p className="text-xs text-destructive">
+ {syncSkills.error instanceof Error ? syncSkills.error.message : "Failed to update skills"}
+ </p>
+ ) : null}
+ </div>
+
+ {/* Unsupported adapter banner */}
+ {unsupportedMessage ? (
+ <div className="rounded-lg border border-border bg-muted/30 px-4 py-3 text-sm text-muted-foreground">
+ {unsupportedMessage}
+ </div>
+ ) : null}
+
+ {/* Stale desired-skill warnings — one compact, removable row per key */}
+ {staleDesiredKeys.length > 0 ? (
+ <div className="overflow-hidden rounded-lg border border-amber-300/60 dark:border-amber-500/30">
+ {staleDesiredKeys.map((key) => (
+ <div
+ key={key}
+ className="flex items-center justify-between gap-3 border-b border-amber-300/40 bg-amber-50/60 px-3 py-2 text-xs text-amber-800 last:border-b-0 dark:border-amber-500/20 dark:bg-amber-950/20 dark:text-amber-200"
+ >
+ <span className="min-w-0 truncate">
+ <span className="font-medium">{key}</span> is enabled but missing from the company library.
+ </span>
+ <button
+ type="button"
+ onClick={() => toggleSkill(key, false)}
+ className="inline-flex shrink-0 items-center gap-1 rounded-md border border-amber-400/50 px-2 py-0.5 font-medium transition-colors hover:bg-amber-100/60 dark:hover:bg-amber-900/30"
+ >
+ <X className="h-3 w-3" />
+ Remove
+ </button>
+ </div>
+ ))}
+ </div>
+ ) : null}
+
+ {isLoading ? (
+ <PageSkeleton variant="list" />
+ ) : libraryEmpty && detectedRows.length === 0 ? (
+ <EmptyLibraryCard />
+ ) : (
+ <div className="space-y-4">
+ <SkillSection title="Enabled on this agent" count={filteredEnabled.length}>
+ {filteredEnabled.length > 0 ? (
+ filteredEnabled.map((row) => renderRow(row, "enabled"))
+ ) : (
+ <SectionEmpty>
+ {search ? "No enabled skills match your search." : "No skills enabled on this agent yet."}
+ </SectionEmpty>
+ )}
+ </SkillSection>
+
+ <SkillSection title="Available from the library" count={filteredAvailable.length}>
+ {filteredAvailable.length > 0 ? (
+ filteredAvailable.map((row) => renderRow(row, "available"))
+ ) : (
+ <SectionEmpty>
+ {search
+ ? "No available skills match your search."
+ : libraryEmpty
+ ? "Import skills into the company library to enable them here."
+ : "Every library skill is enabled on this agent."}
+ </SectionEmpty>
+ )}
+ </SkillSection>
+
+ {detectedRows.length > 0 ? (
+ <Collapsible open={detectedOpen} onOpenChange={setDetectedOpen}>
+ <div className="overflow-hidden rounded-lg border border-border">
+ <CollapsibleTrigger className="flex w-full items-center gap-2 bg-muted/50 px-3 py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <ChevronDown
+ className={cn(
+ "h-3.5 w-3.5 text-muted-foreground transition-transform",
+ detectedOpen ? "" : "-rotate-90",
+ )}
+ />
+ <span className="text-xs font-medium text-muted-foreground">
+ Detected on adapter (read-only)
+ </span>
+ <span className="text-xs text-muted-foreground/70">{filteredDetected.length}</span>
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ {filteredDetected.length > 0 ? (
+ filteredDetected.map((row) => (
+ <AgentSkillRow key={row.key} variant="readonly" data={row} />
+ ))
+ ) : (
+ <SectionEmpty>No detected skills match your search.</SectionEmpty>
+ )}
+ </CollapsibleContent>
+ </div>
+ </Collapsible>
+ ) : null}
+
+ <div className="text-xs text-muted-foreground">
+ Adapter: {adapterLabels[agent.adapterType] ?? agent.adapterType}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function SaveStatusChip({
+ pending,
+ unsaved,
+ error,
+}: {
+ pending: boolean;
+ unsaved: boolean;
+ error: boolean;
+}) {
+ if (pending) {
+ return (
+ <span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ Saving…
+ </span>
+ );
+ }
+ if (error) {
+ return (
+ <span className="inline-flex items-center gap-1.5 text-xs text-destructive">
+ <AlertCircle className="h-3.5 w-3.5" />
+ Couldn’t save
+ </span>
+ );
+ }
+ if (unsaved) {
+ return (
+ <span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ Saving soon…
+ </span>
+ );
+ }
+ return (
+ <span className="inline-flex items-center gap-1.5 text-xs text-(--status-task-done)">
+ <CheckCircle2 className="h-3.5 w-3.5" />
+ Saved
+ </span>
+ );
+}
+
+function SkillSection({
+ title,
+ count,
+ children,
+}: {
+ title: string;
+ count: number;
+ children: React.ReactNode;
+}) {
+ return (
+ <section className="overflow-hidden rounded-lg border border-border">
+ <div className="flex items-center gap-2 bg-muted/50 px-3 py-2">
+ <span className="text-xs font-medium text-muted-foreground">{title}</span>
+ <span className="text-xs text-muted-foreground/70">{count}</span>
+ </div>
+ <div>{children}</div>
+ </section>
+ );
+}
+
+function SectionEmpty({ children }: { children: React.ReactNode }) {
+ return <div className="px-3 py-4 text-xs text-muted-foreground">{children}</div>;
+}
+
+function EmptyLibraryCard() {
+ return (
+ <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-border px-6 py-10 text-center">
+ <Store className="h-8 w-8 text-muted-foreground/60" />
+ <div className="space-y-1">
+ <p className="text-sm font-medium text-foreground">No skills in the company library</p>
+ <p className="text-xs text-muted-foreground">
+ Install skills to the company, then enable them on this agent.
+ </p>
+ </div>
+ <Button asChild variant="outline" size="sm">
+ <Link to="/skills" className="no-underline">
+ <Store className="h-3.5 w-3.5" />
+ Browse skills store
+ </Link>
+ </Button>
+ </div>
+ );
+}
diff --git a/ui/src/pages/agent-skills/agent-skill-filter.test.ts b/ui/src/pages/agent-skills/agent-skill-filter.test.ts
new file mode 100644
index 0000000000..51dd15aecc
--- /dev/null
+++ b/ui/src/pages/agent-skills/agent-skill-filter.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from "vitest";
+import {
+ agentSkillMatchesSearch,
+ buildAgentSkillHaystack,
+ filterAgentSkills,
+} from "./agent-skill-filter";
+
+const ROWS = [
+ {
+ key: "agent-browser",
+ name: "agent-browser",
+ slug: "agent-browser",
+ author: "Paperclip",
+ tagline: "Drive a real browser",
+ description: "Inspect and interact with web pages",
+ categories: ["automation", "web"],
+ },
+ {
+ key: "para-memory-files",
+ name: "para-memory-files",
+ slug: "para",
+ author: "Tiago",
+ tagline: "PARA method memory",
+ description: null,
+ categories: ["memory"],
+ },
+];
+
+describe("buildAgentSkillHaystack", () => {
+ it("joins every searchable field lowercased", () => {
+ expect(buildAgentSkillHaystack(ROWS[0])).toBe(
+ "agent-browser agent-browser paperclip drive a real browser inspect and interact with web pages automation web",
+ );
+ });
+
+ it("tolerates null / missing fields", () => {
+ // 6 fields joined by a single space; only name is present.
+ expect(buildAgentSkillHaystack({ name: "Solo" })).toBe(["solo", "", "", "", "", ""].join(" "));
+ expect(buildAgentSkillHaystack({ name: "X", slug: null, description: null, categories: null })).toBe(
+ ["x", "", "", "", "", ""].join(" "),
+ );
+ });
+});
+
+describe("agentSkillMatchesSearch", () => {
+ it("matches empty / whitespace query", () => {
+ expect(agentSkillMatchesSearch(ROWS[0], "")).toBe(true);
+ expect(agentSkillMatchesSearch(ROWS[0], " ")).toBe(true);
+ });
+
+ it("matches on name, category, description, and author case-insensitively", () => {
+ expect(agentSkillMatchesSearch(ROWS[0], "BROWSER")).toBe(true);
+ expect(agentSkillMatchesSearch(ROWS[0], "automation")).toBe(true);
+ expect(agentSkillMatchesSearch(ROWS[0], "web pages")).toBe(true);
+ expect(agentSkillMatchesSearch(ROWS[1], "tiago")).toBe(true);
+ });
+
+ it("does not match unrelated queries", () => {
+ expect(agentSkillMatchesSearch(ROWS[1], "browser")).toBe(false);
+ });
+});
+
+describe("filterAgentSkills", () => {
+ it("returns the original list for an empty query", () => {
+ expect(filterAgentSkills(ROWS, "")).toBe(ROWS);
+ expect(filterAgentSkills(ROWS, " ")).toBe(ROWS);
+ });
+
+ it("filters by the shared haystack fields and preserves order", () => {
+ expect(filterAgentSkills(ROWS, "memory").map((r) => r.key)).toEqual(["para-memory-files"]);
+ expect(filterAgentSkills(ROWS, "a").map((r) => r.key)).toEqual([
+ "agent-browser",
+ "para-memory-files",
+ ]);
+ expect(filterAgentSkills(ROWS, "nonexistent")).toEqual([]);
+ });
+});
diff --git a/ui/src/pages/agent-skills/agent-skill-filter.ts b/ui/src/pages/agent-skills/agent-skill-filter.ts
new file mode 100644
index 0000000000..1d2d7e2c77
--- /dev/null
+++ b/ui/src/pages/agent-skills/agent-skill-filter.ts
@@ -0,0 +1,44 @@
+/**
+ * Client-side search for the agent Skills tab. Mirrors the store's
+ * `discoveryMatchesSearch` haystack (name, slug, author, tagline, description,
+ * categories) so the two surfaces filter on the same fields.
+ */
+export interface AgentSkillSearchFields {
+ name: string;
+ slug?: string | null;
+ author?: string | null;
+ tagline?: string | null;
+ description?: string | null;
+ categories?: string[] | null;
+}
+
+export function buildAgentSkillHaystack(fields: AgentSkillSearchFields): string {
+ return [
+ fields.name,
+ fields.slug ?? "",
+ fields.author ?? "",
+ fields.tagline ?? "",
+ fields.description ?? "",
+ (fields.categories ?? []).join(" "),
+ ]
+ .join(" ")
+ .toLowerCase();
+}
+
+export function agentSkillMatchesSearch(
+ fields: AgentSkillSearchFields,
+ query: string,
+): boolean {
+ const trimmed = query.trim();
+ if (!trimmed) return true;
+ return buildAgentSkillHaystack(fields).includes(trimmed.toLowerCase());
+}
+
+export function filterAgentSkills<T extends AgentSkillSearchFields>(
+ rows: T[],
+ query: string,
+): T[] {
+ const trimmed = query.trim();
+ if (!trimmed) return rows;
+ return rows.filter((row) => agentSkillMatchesSearch(row, trimmed));
+}
diff --git a/ui/src/pages/agent-skills/agent-skill-source.test.ts b/ui/src/pages/agent-skills/agent-skill-source.test.ts
new file mode 100644
index 0000000000..d039682f53
--- /dev/null
+++ b/ui/src/pages/agent-skills/agent-skill-source.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+import { buildAgentSkillSourceMeta } from "./agent-skill-source";
+
+function source(overrides: Parameters<typeof buildAgentSkillSourceMeta>[0]) {
+ return buildAgentSkillSourceMeta(overrides).label;
+}
+
+describe("buildAgentSkillSourceMeta", () => {
+ it("shows GitHub skills as owner/repo text", () => {
+ expect(source({
+ sourceBadge: "github",
+ sourceLabel: "https://github.com/acme/review-skill/tree/main/skills/review",
+ sourceLocator: null,
+ sourceType: "github",
+ })).toBe("GitHub · acme/review-skill");
+ });
+
+ it("does not surface long filesystem labels for local skills", () => {
+ expect(source({
+ sourceBadge: "local",
+ sourceLabel: "/Users/dev/work/paperclip/skills/private-review",
+ sourceLocator: null,
+ sourceType: "local_path",
+ })).toBe("Local folder");
+ });
+
+ it("keeps human-readable project scan labels for local skills", () => {
+ expect(source({
+ sourceBadge: "local",
+ sourceLabel: "Paperclip App / Engineering workspace",
+ sourceLocator: null,
+ sourceType: "local_path",
+ })).toBe("Paperclip App / Engineering workspace");
+ });
+
+ it("does not surface long filesystem labels for catalog skills", () => {
+ expect(source({
+ sourceBadge: "catalog",
+ sourceLabel: "/srv/paperclip/home/.paperclip/instances/default/skills/company-id/__catalog__/briefs-discover-cards--68f7e3ad47",
+ sourceLocator: null,
+ sourceType: "catalog",
+ })).toBe("Catalog");
+ });
+
+ it("keeps human-readable catalog labels", () => {
+ expect(source({
+ sourceBadge: "catalog",
+ sourceLabel: "Bundled catalog",
+ sourceLocator: null,
+ sourceType: "catalog",
+ })).toBe("Bundled catalog");
+ });
+});
diff --git a/ui/src/pages/agent-skills/agent-skill-source.ts b/ui/src/pages/agent-skills/agent-skill-source.ts
new file mode 100644
index 0000000000..139676dfe3
--- /dev/null
+++ b/ui/src/pages/agent-skills/agent-skill-source.ts
@@ -0,0 +1,118 @@
+import { Boxes, Folder, Github, Link2, Paperclip, type LucideIcon } from "lucide-react";
+import type { CompanySkillListItem } from "@paperclipai/shared";
+
+export interface AgentSkillSourceMeta {
+ icon: LucideIcon;
+ label: string;
+}
+
+type SourceSkill = Pick<
+ CompanySkillListItem,
+ "sourceBadge" | "sourceLabel" | "sourceLocator" | "sourceType"
+>;
+
+function cleanRepoName(repo: string) {
+ return repo.replace(/\.git$/i, "");
+}
+
+function githubRepoLabel(value: string | null | undefined): string | null {
+ const raw = value?.trim();
+ if (!raw) return null;
+
+ const parsePath = (path: string) => {
+ const [owner, repo] = path.split("/").filter(Boolean);
+ if (!owner || !repo) return null;
+ return `${owner}/${cleanRepoName(repo)}`;
+ };
+
+ try {
+ const url = new URL(raw.startsWith("http") ? raw : `https://${raw}`);
+ if (url.hostname.toLowerCase().includes("github")) {
+ return parsePath(url.pathname);
+ }
+ } catch {
+ // Fall back to the looser parsing below for owner/repo and git@github forms.
+ }
+
+ const sshMatch = raw.match(/^git@[^:]+:([^/]+)\/([^/#?]+)(?:[/?#]|$)/i);
+ if (sshMatch?.[1] && sshMatch[2]) return `${sshMatch[1]}/${cleanRepoName(sshMatch[2])}`;
+
+ const githubPathMatch = raw.match(/github\.com[:/]([^/]+)\/([^/#?]+)(?:[/?#]|$)/i);
+ if (githubPathMatch?.[1] && githubPathMatch[2]) {
+ return `${githubPathMatch[1]}/${cleanRepoName(githubPathMatch[2])}`;
+ }
+
+ if (!isFilesystemLikeLabel(raw)) {
+ const ownerRepoMatch = raw.match(/^([^/\s]+)\/([^/\s]+)(?:[/?#]|$)/);
+ if (ownerRepoMatch?.[1] && ownerRepoMatch[2]) {
+ return `${ownerRepoMatch[1]}/${cleanRepoName(ownerRepoMatch[2])}`;
+ }
+ }
+
+ return null;
+}
+
+function hostLabel(value: string | null | undefined): string | null {
+ const raw = value?.trim();
+ if (!raw) return null;
+ try {
+ const url = new URL(raw.startsWith("http") ? raw : `https://${raw}`);
+ return url.hostname;
+ } catch {
+ return null;
+ }
+}
+
+function isFilesystemLikeLabel(value: string) {
+ return (
+ value.startsWith("/") ||
+ value.startsWith("~/") ||
+ value.startsWith("./") ||
+ value.startsWith("../") ||
+ /^[A-Za-z]:[\\/]/.test(value) ||
+ value.includes("\\") ||
+ (value.includes("/") && !value.includes(" / "))
+ );
+}
+
+function displayLocalSourceLabel(label: string | null | undefined) {
+ const trimmed = label?.trim();
+ if (!trimmed || isFilesystemLikeLabel(trimmed)) return "Local folder";
+ return trimmed;
+}
+
+function displayCatalogSourceLabel(label: string | null | undefined) {
+ const trimmed = label?.trim();
+ if (!trimmed || isFilesystemLikeLabel(trimmed)) return "Catalog";
+ return trimmed;
+}
+
+export function buildAgentSkillSourceMeta(skill: SourceSkill): AgentSkillSourceMeta {
+ if (skill.sourceBadge === "github" || skill.sourceType === "github") {
+ const repo = githubRepoLabel(skill.sourceLabel) ?? githubRepoLabel(skill.sourceLocator);
+ return { icon: Github, label: repo ? `GitHub · ${repo}` : "GitHub" };
+ }
+
+ if (skill.sourceBadge === "skills_sh" || skill.sourceType === "skills_sh") {
+ const repo = githubRepoLabel(skill.sourceLabel) ?? githubRepoLabel(skill.sourceLocator);
+ return { icon: Github, label: repo ? `skills.sh · ${repo}` : "skills.sh" };
+ }
+
+ if (skill.sourceBadge === "url" || skill.sourceType === "url") {
+ return { icon: Link2, label: hostLabel(skill.sourceLabel) ?? hostLabel(skill.sourceLocator) ?? "URL" };
+ }
+
+ if (skill.sourceBadge === "paperclip") {
+ return { icon: Paperclip, label: skill.sourceLabel?.trim() || "Paperclip managed" };
+ }
+
+ if (skill.sourceBadge === "catalog" || skill.sourceType === "catalog") {
+ return { icon: Boxes, label: displayCatalogSourceLabel(skill.sourceLabel) };
+ }
+
+ if (skill.sourceBadge === "local" || skill.sourceType === "local_path") {
+ return { icon: Folder, label: displayLocalSourceLabel(skill.sourceLabel) };
+ }
+
+ return { icon: Boxes, label: displayCatalogSourceLabel(skill.sourceLabel) };
+}
diff --git a/ui/storybook/stories/agent-skill-row.stories.tsx b/ui/storybook/stories/agent-skill-row.stories.tsx
new file mode 100644
index 0000000000..34d62c99d4
--- /dev/null
+++ b/ui/storybook/stories/agent-skill-row.stories.tsx
@@ -0,0 +1,101 @@
+import { useState } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { Folder, Github } from "lucide-react";
+import { AgentSkillRow, type AgentSkillRowData } from "@/pages/agent-skills/AgentSkillRow";
+
+const ENABLED: AgentSkillRowData = {
+ key: "agent-browser",
+ name: "agent-browser",
+ icon: { key: "agent-browser", name: "agent-browser", slug: "agent-browser", iconUrl: null, color: null },
+ summary: "Drive a real browser to inspect and interact with web pages.",
+ chip: "automation",
+ sourceMeta: { icon: Github, label: "GitHub · vercel-labs/agent-browser" },
+ linkTo: "/skills/agent-browser",
+ slug: "agent-browser",
+ tagline: "Drive a real browser to inspect and interact with web pages.",
+ categories: ["automation"],
+};
+
+const AVAILABLE: AgentSkillRowData = {
+ key: "para-memory-files",
+ name: "para-memory-files",
+ icon: { key: "para-memory-files", name: "para-memory-files", slug: "para", iconUrl: null, color: "#7c3aed" },
+ summary: "File-based memory system using Tiago Forte's PARA method.",
+ chip: "memory",
+ sourceMeta: { icon: Folder, label: "Local folder" },
+ linkTo: "/skills/para-memory-files",
+ slug: "para-memory-files",
+ tagline: "File-based memory system using Tiago Forte's PARA method.",
+ categories: ["memory"],
+};
+
+const READONLY: AgentSkillRowData = {
+ key: "user-installed-linter",
+ name: "user-installed-linter",
+ icon: { key: "user-installed-linter", name: "user-installed-linter", slug: null, iconUrl: null, color: null },
+ summary: "Detected in the adapter's skill directory.",
+ chip: null,
+ linkTo: null,
+ originLabel: "User-installed",
+ locationLabel: "~/.claude/skills/linter",
+};
+
+const meta: Meta<typeof AgentSkillRow> = {
+ title: "Agent Skills/AgentSkillRow",
+ component: AgentSkillRow,
+ parameters: { layout: "padded" },
+ decorators: [
+ (Story) => (
+ <div className="max-w-2xl overflow-hidden rounded-lg border border-border">
+ <Story />
+ </div>
+ ),
+ ],
+};
+export default meta;
+
+type Story = StoryObj<typeof AgentSkillRow>;
+
+function ToggleableRow({ data, initial }: { data: AgentSkillRowData; initial: boolean }) {
+ const [checked, setChecked] = useState(initial);
+ return (
+ <AgentSkillRow
+ variant={checked ? "enabled" : "available"}
+ data={data}
+ checked={checked}
+ onCheckedChange={setChecked}
+ />
+ );
+}
+
+export const Enabled: Story = {
+ render: () => <ToggleableRow data={ENABLED} initial={true} />,
+};
+
+export const Available: Story = {
+ render: () => <ToggleableRow data={AVAILABLE} initial={false} />,
+};
+
+export const ReadOnly: Story = {
+ args: { variant: "readonly", data: READONLY },
+};
+
+export const DisabledUnsupported: Story = {
+ args: {
+ variant: "available",
+ data: AVAILABLE,
+ checked: false,
+ disabled: true,
+ disabledReason: "Paperclip cannot manage skills for this adapter yet.",
+ },
+};
+
+export const AllVariants: Story = {
+ render: () => (
+ <>
+ <ToggleableRow data={ENABLED} initial={true} />
+ <ToggleableRow data={AVAILABLE} initial={false} />
+ <AgentSkillRow variant="readonly" data={READONLY} />
+ </>
+ ),
+};
diff --git a/ui/storybook/stories/agent-skills-edge.stories.tsx b/ui/storybook/stories/agent-skills-edge.stories.tsx
new file mode 100644
index 0000000000..ff04589393
--- /dev/null
+++ b/ui/storybook/stories/agent-skills-edge.stories.tsx
@@ -0,0 +1,222 @@
+import type { ReactNode } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { useQueryClient } from "@tanstack/react-query";
+import type { Agent, AgentSkillSnapshot, CompanySkillListItem } from "@paperclipai/shared";
+import { AgentSkillsTab } from "@/pages/agent-skills/AgentSkillsTab";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Badge } from "@/components/ui/badge";
+import { queryKeys } from "@/lib/queryKeys";
+
+// QA-only fixtures (PAP-13195) to exercise AC5 (stale desired-skill warning) and
+// AC6 (collapsed read-only "Detected on adapter" section) - states the shipped
+// acpx_local stories do not cover.
+
+const COMPANY_ID = "company-qa-edge";
+
+const defaultStoreSkillFields = {
+ iconUrl: null,
+ color: null,
+ tagline: null,
+ authorName: null,
+ homepageUrl: null,
+ categories: [] as string[],
+ sharingScope: "company" as const,
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 0,
+ installCount: 1,
+ forkCount: 0,
+ currentVersionId: null,
+};
+
+function libSkill(key: string, name: string, description: string): CompanySkillListItem {
+ return {
+ id: `skill-${key}`,
+ companyId: COMPANY_ID,
+ key,
+ slug: key,
+ name,
+ description,
+ sourceType: "local_path",
+ sourceLocator: `skills/${key}`,
+ sourceRef: null,
+ trustLevel: "markdown_only",
+ 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: 1,
+ editable: true,
+ editableReason: null,
+ sourceLabel: "Local",
+ sourceBadge: "local",
+ sourcePath: `skills/${key}`,
+ catalogKind: null,
+ originHash: null,
+ packageName: null,
+ packageVersion: null,
+ } as CompanySkillListItem;
+}
+
+const library: CompanySkillListItem[] = [
+ libSkill("paperclip", "Paperclip", "Coordination skill: heartbeats, checkout, comments, and routine API patterns."),
+ libSkill("design-guide", "Design guide", "Paperclip UI design system reference: tokens, typography, status colors."),
+];
+
+function buildAgent(agentId: string, desiredSkills: string[]): Agent {
+ return {
+ id: agentId,
+ companyId: COMPANY_ID,
+ name: "ACPX Claude",
+ urlKey: "acpx-claude-edge",
+ role: "engineer",
+ title: "ACPX Claude agent",
+ icon: "code",
+ status: "idle",
+ reportsTo: null,
+ capabilities: "Routes work through the ACPX adapter.",
+ adapterType: "acpx_local",
+ adapterConfig: {
+ agent: "claude",
+ mode: "persistent",
+ permissionMode: "approve-all",
+ paperclipSkillSync: { desiredSkills },
+ },
+ runtimeConfig: {},
+ budgetMonthlyCents: 100_000,
+ spentMonthlyCents: 0,
+ pauseReason: null,
+ pausedAt: null,
+ permissions: { canCreateAgents: false },
+ lastHeartbeatAt: null,
+ metadata: null,
+ createdAt: new Date("2026-04-30T12:00:00.000Z"),
+ updatedAt: new Date("2026-04-30T12:00:00.000Z"),
+ } as Agent;
+}
+
+// AC5: a desired key that is no longer in the company library -> stale warning row.
+function staleSnapshot(): AgentSkillSnapshot {
+ return {
+ adapterType: "acpx_local",
+ supported: true,
+ mode: "ephemeral",
+ desiredSkills: ["paperclip", "legacy-retired-skill"],
+ warnings: [],
+ entries: [
+ {
+ key: "paperclip",
+ runtimeName: "paperclip",
+ desired: true,
+ managed: true,
+ state: "configured",
+ origin: "company_managed",
+ originLabel: "Managed by Paperclip",
+ readOnly: false,
+ sourcePath: "skills/paperclip",
+ targetPath: null,
+ detail: "Will be mounted into the next ACPX Claude session.",
+ },
+ ],
+ };
+}
+
+// AC6: a user-installed skill detected on the adapter that is NOT in the company
+// library -> read-only lock row inside the collapsed "Detected on adapter" section.
+function detectedSnapshot(): AgentSkillSnapshot {
+ return {
+ adapterType: "acpx_local",
+ supported: true,
+ mode: "ephemeral",
+ desiredSkills: ["paperclip"],
+ warnings: [],
+ entries: [
+ {
+ key: "paperclip",
+ runtimeName: "paperclip",
+ desired: true,
+ managed: true,
+ state: "configured",
+ origin: "company_managed",
+ originLabel: "Managed by Paperclip",
+ readOnly: false,
+ sourcePath: "skills/paperclip",
+ targetPath: null,
+ detail: "Will be mounted into the next ACPX Claude session.",
+ },
+ {
+ key: "my-local-hack",
+ runtimeName: "my-local-hack",
+ desired: false,
+ managed: false,
+ state: "external",
+ origin: "user_installed",
+ originLabel: "Installed by user",
+ locationLabel: "~/.claude/skills/my-local-hack",
+ readOnly: true,
+ sourcePath: null,
+ targetPath: null,
+ detail: "Detected in the adapter's skills directory; managed outside Paperclip.",
+ },
+ ] as AgentSkillSnapshot["entries"],
+ };
+}
+
+function StoryFrame({ title, subtitle, children }: { title: string; subtitle: string; children: ReactNode }) {
+ return (
+ <div className="mx-auto max-w-3xl space-y-5 p-6">
+ <header className="space-y-2">
+ <Badge variant="outline" className="rounded-full px-3 py-1 text-xs uppercase tracking-wide">
+ QA edge state
+ </Badge>
+ <h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
+ <p className="text-sm text-muted-foreground">{subtitle}</p>
+ </header>
+ <Card className="shadow-none border-border">
+ <CardHeader>
+ <CardTitle className="text-base font-semibold">Agent detail - Skills tab</CardTitle>
+ </CardHeader>
+ <CardContent>{children}</CardContent>
+ </Card>
+ </div>
+ );
+}
+
+function EdgeState({ agent, snapshot }: { agent: Agent; snapshot: AgentSkillSnapshot }) {
+ const queryClient = useQueryClient();
+ queryClient.setQueryData(queryKeys.companySkills.list(COMPANY_ID), library);
+ queryClient.setQueryData(queryKeys.agents.skills(agent.id), snapshot);
+ return <AgentSkillsTab agent={agent} companyId={COMPANY_ID} />;
+}
+
+const meta: Meta = {
+ title: "QA / Agent skills edge states",
+ parameters: { layout: "fullscreen" },
+};
+export default meta;
+
+export const StaleWarning: StoryObj = {
+ name: "Stale desired-skill warning (AC5)",
+ render: () => (
+ <StoryFrame
+ title="Stale desired-skill warning"
+ subtitle="An enabled skill key that no longer exists in the company library renders as a compact, removable warning row."
+ >
+ <EdgeState agent={buildAgent("agent-stale", ["paperclip", "legacy-retired-skill"])} snapshot={staleSnapshot()} />
+ </StoryFrame>
+ ),
+};
+
+export const DetectedAdapter: StoryObj = {
+ name: "Detected on adapter - read-only (AC6)",
+ render: () => (
+ <StoryFrame
+ title="Detected on adapter (read-only)"
+ subtitle="A user-installed skill outside Paperclip's management shows in a collapsed, read-only section with a lock icon."
+ >
+ <EdgeState agent={buildAgent("agent-detected", ["paperclip"])} snapshot={detectedSnapshot()} />
+ </StoryFrame>
+ ),
+};
diff --git a/ui/storybook/stories/agents-using-skill.stories.tsx b/ui/storybook/stories/agents-using-skill.stories.tsx
new file mode 100644
index 0000000000..83a57cd509
--- /dev/null
+++ b/ui/storybook/stories/agents-using-skill.stories.tsx
@@ -0,0 +1,185 @@
+import { useState, type ReactNode } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import type {
+ CompanySkillDetail,
+ CompanySkillUsageAgent,
+ CompanySkillVersion,
+} from "@paperclipai/shared";
+import {
+ AgentsUsingSkillBadge,
+ AgentsUsingSkillDialog,
+} from "@/components/skill-studio/AgentsUsingSkillDialog";
+import { queryKeys } from "@/lib/queryKeys";
+
+const COMPANY_ID = "company-storybook";
+const SKILL_ID = "skill-code-review";
+
+function makeVersion(overrides: Partial<CompanySkillVersion>): CompanySkillVersion {
+ return {
+ id: "ver",
+ companyId: COMPANY_ID,
+ companySkillId: SKILL_ID,
+ revisionNumber: 1,
+ label: null,
+ fileInventory: [],
+ authorAgentId: null,
+ authorUserId: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ ...overrides,
+ };
+}
+
+const VERSIONS: CompanySkillVersion[] = [
+ makeVersion({ id: "ver-3", revisionNumber: 3, label: "polish pass" }),
+ makeVersion({ id: "ver-2", revisionNumber: 2 }),
+ makeVersion({ id: "ver-1", revisionNumber: 1 }),
+];
+
+const AGENTS = [
+ { id: "agent-1", name: "Reviewer", urlKey: "reviewer", adapterType: "claude_local", icon: "bot", status: "idle" },
+ { id: "agent-2", name: "Coder", urlKey: "coder", adapterType: "codex_local", icon: "code", status: "idle" },
+ { id: "agent-3", name: "Planner", urlKey: "planner", adapterType: "claude_local", icon: "compass", status: "idle" },
+ { id: "agent-4", name: "QA Bot", urlKey: "qa-bot", adapterType: "claude_local", icon: "bug", status: "idle" },
+];
+
+function usageAgent(overrides: Partial<CompanySkillUsageAgent>): CompanySkillUsageAgent {
+ return {
+ id: "agent-1",
+ name: "Reviewer",
+ urlKey: "reviewer",
+ adapterType: "claude_local",
+ desired: true,
+ actualState: null,
+ versionId: null,
+ ...overrides,
+ };
+}
+
+function makeSkill(overrides: Partial<CompanySkillDetail> = {}): CompanySkillDetail {
+ return {
+ id: SKILL_ID,
+ companyId: COMPANY_ID,
+ key: "paperclip/code-review",
+ slug: "code-review",
+ name: "Code Review",
+ description: "Structured pull-request review with actionable findings.",
+ markdown: "",
+ sourceType: "local_path",
+ sourceLocator: null,
+ sourceRef: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [],
+ iconUrl: null,
+ color: null,
+ tagline: null,
+ authorName: null,
+ homepageUrl: null,
+ categories: [],
+ sharingScope: "company",
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 0,
+ installCount: 0,
+ forkCount: 0,
+ currentVersionId: "ver-3",
+ metadata: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ updatedAt: new Date("2026-01-02T00:00:00Z"),
+ attachedAgentCount: 3,
+ usedByAgents: [
+ usageAgent({ id: "agent-1", name: "Reviewer", urlKey: "reviewer", versionId: null }),
+ usageAgent({ id: "agent-2", name: "Coder", urlKey: "coder", adapterType: "codex_local", versionId: "ver-1" }),
+ usageAgent({ id: "agent-3", name: "Planner", urlKey: "planner", versionId: "ver-3" }),
+ ],
+ editable: true,
+ editableReason: null,
+ sourceLabel: "Local",
+ sourceBadge: "local",
+ sourcePath: null,
+ currentVersion: makeVersion({ id: "ver-3", revisionNumber: 3, label: "polish pass" }),
+ starredByCurrentActor: false,
+ existingForks: [],
+ ...overrides,
+ };
+}
+
+// Prime the react-query cache so the lazy versions/agents lookups resolve
+// offline (storybook staleTime is Infinity, so nothing refetches).
+function Seed({ skill, children }: { skill: CompanySkillDetail; children: ReactNode }) {
+ const queryClient = useQueryClient();
+ queryClient.setQueryData(queryKeys.companySkills.versions(COMPANY_ID, skill.id), VERSIONS);
+ queryClient.setQueryData(queryKeys.agents.list(COMPANY_ID), AGENTS);
+ return <>{children}</>;
+}
+
+const meta: Meta = {
+ title: "Skill Studio/AgentsUsingSkill",
+ parameters: { layout: "centered" },
+};
+export default meta;
+
+type Story = StoryObj;
+
+/** The header badge as it sits next to the other Studio badges. */
+export const HeaderBadge: Story = {
+ render: () => {
+ const skill = makeSkill();
+ return (
+ <Seed skill={skill}>
+ <div className="flex items-center gap-3 rounded-md border border-border bg-card px-3 py-2">
+ <span className="text-base font-semibold">Code Review</span>
+ <span className="font-mono text-xs text-muted-foreground">v3</span>
+ <AgentsUsingSkillBadge companyId={COMPANY_ID} skill={skill} />
+ </div>
+ </Seed>
+ );
+ },
+};
+
+export const HeaderBadgeEmpty: Story = {
+ render: () => {
+ const skill = makeSkill({ usedByAgents: [], attachedAgentCount: 0 });
+ return (
+ <Seed skill={skill}>
+ <div className="flex items-center gap-3 rounded-md border border-border bg-card px-3 py-2">
+ <span className="text-base font-semibold">Code Review</span>
+ <span className="font-mono text-xs text-muted-foreground">v3</span>
+ <AgentsUsingSkillBadge companyId={COMPANY_ID} skill={skill} />
+ </div>
+ </Seed>
+ );
+ },
+};
+
+function OpenDialog({ skill, canManage = true }: { skill: CompanySkillDetail; canManage?: boolean }) {
+ const [open, setOpen] = useState(true);
+ return (
+ <Seed skill={skill}>
+ <AgentsUsingSkillDialog
+ open={open}
+ onOpenChange={setOpen}
+ companyId={COMPANY_ID}
+ skill={skill}
+ canManage={canManage}
+ />
+ </Seed>
+ );
+}
+
+/** The management modal with three agents, mixed latest/pinned versions. */
+export const ManagementModal: Story = {
+ render: () => <OpenDialog skill={makeSkill()} />,
+};
+
+/** Read-only roster: names link out, no mutating controls. */
+export const ReadOnlyRoster: Story = {
+ render: () => <OpenDialog skill={makeSkill()} canManage={false} />,
+};
+
+/** Zero-agent empty state with the add-agent picker as the primary action. */
+export const EmptyState: Story = {
+ render: () => <OpenDialog skill={makeSkill({ usedByAgents: [], attachedAgentCount: 0 })} />,
+};
diff --git a/ui/storybook/stories/fork-skill-flow.stories.tsx b/ui/storybook/stories/fork-skill-flow.stories.tsx
new file mode 100644
index 0000000000..1c250e0bd8
--- /dev/null
+++ b/ui/storybook/stories/fork-skill-flow.stories.tsx
@@ -0,0 +1,269 @@
+import { useState, type ReactNode } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { AlertTriangle, GitFork } from "lucide-react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import type {
+ CompanySkillDetail,
+ CompanySkillForkPrecheckResult,
+ CompanySkillForkSummary,
+ CompanySkillUsageAgent,
+} from "@paperclipai/shared";
+import { ForkSkillDialog } from "@/components/skill-studio/ForkSkillDialog";
+import {
+ ProjectScanNotice,
+ SkillLineageChip,
+} from "@/components/skill-studio/SkillProvenance";
+import { AgentsUsingSkillBadge } from "@/components/skill-studio/AgentsUsingSkillDialog";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { queryKeys } from "@/lib/queryKeys";
+
+const COMPANY_ID = "company-storybook";
+const SKILL_ID = "skill-deep-research";
+const ORIGINAL_ID = "skill-deep-research"; // external original
+const FORK_ID = "skill-deep-research-copy"; // the editable fork
+
+function usageAgent(over: Partial<CompanySkillUsageAgent>): CompanySkillUsageAgent {
+ return {
+ id: "agent-1",
+ name: "Reviewer",
+ urlKey: "reviewer",
+ adapterType: "claude_local",
+ desired: true,
+ actualState: null,
+ versionId: null,
+ ...over,
+ };
+}
+
+const USAGE_AGENTS: CompanySkillUsageAgent[] = [
+ usageAgent({ id: "agent-1", name: "Reviewer", urlKey: "reviewer" }),
+ usageAgent({ id: "agent-2", name: "Coder", urlKey: "coder", adapterType: "codex_local" }),
+ usageAgent({ id: "agent-3", name: "Planner", urlKey: "planner" }),
+];
+
+function makeSkill(over: Partial<CompanySkillDetail> = {}): CompanySkillDetail {
+ return {
+ id: SKILL_ID,
+ companyId: COMPANY_ID,
+ key: "github/anthropics/skills",
+ slug: "deep-research",
+ name: "Deep Research",
+ description: "Multi-source research with adversarial verification.",
+ markdown: "",
+ sourceType: "github",
+ sourceLocator: "https://github.com/anthropics/skills",
+ sourceRef: "0123456789abcdef0123456789abcdef01234567",
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [],
+ iconUrl: null,
+ color: null,
+ tagline: null,
+ authorName: null,
+ homepageUrl: null,
+ categories: [],
+ sharingScope: "company",
+ publicShareToken: null,
+ forkedFromSkillId: null,
+ forkedFromCompanyId: null,
+ starCount: 0,
+ installCount: 0,
+ forkCount: 0,
+ currentVersionId: null,
+ metadata: null,
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ updatedAt: new Date("2026-01-02T00:00:00Z"),
+ attachedAgentCount: USAGE_AGENTS.length,
+ usedByAgents: USAGE_AGENTS,
+ editable: false,
+ editableReason: "This skill comes from GitHub and is read-only.",
+ sourceLabel: "GitHub",
+ sourceBadge: "github",
+ sourcePath: null,
+ currentVersion: null,
+ starredByCurrentActor: false,
+ existingForks: [],
+ ...over,
+ };
+}
+
+function makePrecheck(
+ over: Partial<CompanySkillForkPrecheckResult> = {},
+): CompanySkillForkPrecheckResult {
+ return {
+ skillId: SKILL_ID,
+ original: {
+ id: ORIGINAL_ID,
+ name: "Deep Research",
+ slug: "deep-research",
+ sourceType: "github",
+ sourceLocator: "https://github.com/anthropics/skills",
+ sourceRef: "0123456789abcdef0123456789abcdef01234567",
+ },
+ agentUsageCount: USAGE_AGENTS.length,
+ usedByAgents: USAGE_AGENTS,
+ existingForks: [],
+ ...over,
+ };
+}
+
+function makeForkSummary(over: Partial<CompanySkillForkSummary> = {}): CompanySkillForkSummary {
+ return {
+ id: "fork-existing",
+ name: "Deep Research (copy)",
+ slug: "deep-research-fork",
+ sourceType: "local_path",
+ sourceLocator: null,
+ sourceRef: null,
+ key: "company/deep-research-fork",
+ forkedFromSkillId: ORIGINAL_ID,
+ forkedFromCompanyId: COMPANY_ID,
+ currentVersionId: "v1",
+ createdByCurrentActor: true,
+ diverged: false,
+ createdAt: new Date("2026-07-01T00:00:00Z"),
+ updatedAt: new Date("2026-07-01T00:00:00Z"),
+ ...over,
+ };
+}
+
+/** Prime react-query so the dialog's precheck + lineage lookups resolve offline. */
+function Seed({
+ skill,
+ precheck,
+ children,
+}: {
+ skill: CompanySkillDetail;
+ precheck?: CompanySkillForkPrecheckResult;
+ children: ReactNode;
+}) {
+ const queryClient = useQueryClient();
+ queryClient.setQueryData(
+ queryKeys.companySkills.forkPrecheck(COMPANY_ID, skill.id),
+ precheck ?? makePrecheck(),
+ );
+ // Original detail for the lineage chip on forked skills.
+ queryClient.setQueryData(
+ queryKeys.companySkills.detail(COMPANY_ID, ORIGINAL_ID),
+ makeSkill(),
+ );
+ return <>{children}</>;
+}
+
+const meta: Meta = {
+ title: "Skill Studio/EditACopy",
+ parameters: { layout: "centered" },
+};
+export default meta;
+
+type Story = StoryObj;
+
+/** The read-only external-skill banner with the primary "Edit a copy" CTA. */
+export const ReadOnlyBannerCTA: Story = {
+ render: () => (
+ <div className="w-[30rem] max-w-full overflow-hidden rounded-md border border-border bg-card">
+ <div className="flex items-start gap-3 border-b border-border bg-muted/40 px-3 py-2.5 text-xs text-muted-foreground">
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500" />
+ <div className="min-w-0 flex-1">
+ <p>
+ This skill comes from GitHub and is read-only. Make an editable copy
+ to change it — the original stays untouched.
+ </p>
+ <Button type="button" size="sm" className="mt-2">
+ <GitFork className="mr-1.5 h-3.5 w-3.5" />
+ Edit a copy
+ </Button>
+ </div>
+ </div>
+ <div className="px-3 py-1.5 font-mono text-xs text-muted-foreground">SKILL.md</div>
+ </div>
+ ),
+};
+
+/** Confirm dialog: three agents use the skill, switch toggle default ON (§3.2). */
+export const ForkDialogAgentsSwitchOn: Story = {
+ render: () => {
+ const skill = makeSkill();
+ return (
+ <Seed skill={skill}>
+ <ForkSkillDialog companyId={COMPANY_ID} skill={skill} open onOpenChange={() => {}} />
+ </Seed>
+ );
+ },
+};
+
+/** Same dialog with no agents assigned — toggle hidden, zero-usage disclosure. */
+export const ForkDialogNoAgents: Story = {
+ render: () => {
+ const skill = makeSkill({ usedByAgents: [], attachedAgentCount: 0 });
+ return (
+ <Seed skill={skill} precheck={makePrecheck({ agentUsageCount: 0, usedByAgents: [] })}>
+ <ForkSkillDialog companyId={COMPANY_ID} skill={skill} open onOpenChange={() => {}} />
+ </Seed>
+ );
+ },
+};
+
+/** Fork-sprawl guard: an un-diverged copy already exists (§5). */
+export const ForkDialogExistingCopy: Story = {
+ render: () => {
+ const existing = [makeForkSummary()];
+ const skill = makeSkill({ existingForks: existing });
+ return (
+ <Seed skill={skill} precheck={makePrecheck({ existingForks: existing })}>
+ <ForkSkillDialog companyId={COMPANY_ID} skill={skill} open onOpenChange={() => {}} />
+ </Seed>
+ );
+ },
+};
+
+/** Studio header row of a forked skill, showing the lineage chip. */
+export const ForkedSkillHeader: Story = {
+ render: () => {
+ const fork = makeSkill({
+ id: FORK_ID,
+ name: "Deep Research (copy)",
+ slug: "deep-research-fork",
+ sourceType: "local_path",
+ sourceLocator: null,
+ sourceRef: null,
+ editable: true,
+ editableReason: null,
+ forkedFromSkillId: ORIGINAL_ID,
+ usedByAgents: [],
+ attachedAgentCount: 0,
+ });
+ return (
+ <Seed skill={fork}>
+ <div className="flex items-center gap-3 rounded-md border border-border bg-card px-3 py-2">
+ <span className="text-base font-semibold">Deep Research (copy)</span>
+ <Badge variant="secondary">Unsaved edits</Badge>
+ <SkillLineageChip companyId={COMPANY_ID} forkedFromSkillId={ORIGINAL_ID} />
+ <AgentsUsingSkillBadge companyId={COMPANY_ID} skill={fork} />
+ </div>
+ </Seed>
+ );
+ },
+};
+
+/** Repo-synced (project_scan) source notice with the "Edit a copy instead" path (§3.3). */
+export const ProjectScanSourceNotice: Story = {
+ render: () => {
+ const skill = makeSkill({
+ name: "Repo Linter",
+ sourceType: "local_path",
+ sourceBadge: "local",
+ metadata: { sourceKind: "project_scan" },
+ sourcePath: "acme-app/.claude/skills/repo-linter",
+ sourceLabel: "acme-app",
+ editable: true,
+ editableReason: null,
+ });
+ return (
+ <div className="w-[30rem] max-w-full overflow-hidden rounded-md border border-border bg-card">
+ <ProjectScanNotice skill={skill} onEditACopy={() => {}} />
+ </div>
+ );
+ },
+};
diff --git a/ui/storybook/stories/frontmatter-panel.stories.tsx b/ui/storybook/stories/frontmatter-panel.stories.tsx
new file mode 100644
index 0000000000..f4f510bc26
--- /dev/null
+++ b/ui/storybook/stories/frontmatter-panel.stories.tsx
@@ -0,0 +1,180 @@
+import { useState } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { FrontmatterPanel, type FrontmatterPanelChange } from "@/components/FrontmatterPanel";
+
+/**
+ * Stories for the Skill Studio FrontmatterPanel (PAP-13155, Option B of
+ * PAP-13145). Each story is a live, stateful harness so Fields/YAML edits and
+ * mode switches behave exactly as they do in Studio.
+ */
+
+interface HarnessProps {
+ frontmatterText: string;
+ hasFrontmatter: boolean;
+ fileName?: string;
+ skillSlug?: string;
+ readOnly?: boolean;
+ width?: number;
+}
+
+function Harness({
+ frontmatterText,
+ hasFrontmatter,
+ fileName = "SKILL.md",
+ skillSlug = "reflection-coach",
+ readOnly,
+ width = 640,
+}: HarnessProps) {
+ const [state, setState] = useState({ frontmatterText, hasFrontmatter });
+ const onChange = (change: FrontmatterPanelChange) => setState(change);
+
+ return (
+ <div className="bg-background text-foreground" style={{ width }}>
+ <div className="rounded-(--rad-8) border border-border">
+ {/* Mimic the Studio file-path + Save toolbar that sits above the panel. */}
+ <div className="flex items-center justify-between gap-2 border-b border-border px-3 py-1.5">
+ <span className="truncate font-mono text-xs text-muted-foreground">{fileName} · v3</span>
+ <span className="text-xs text-muted-foreground">Save</span>
+ </div>
+ <FrontmatterPanel
+ key={fileName}
+ frontmatterText={state.frontmatterText}
+ hasFrontmatter={state.hasFrontmatter}
+ fileName={fileName}
+ skillSlug={skillSlug}
+ readOnly={readOnly}
+ onChange={onChange}
+ />
+ {/* Stand-in for the rich MarkdownEditor body below the panel. */}
+ <div className="px-3 py-6 text-sm text-muted-foreground"># Skill body (rich editor)…</div>
+ </div>
+ <pre className="mt-3 max-w-full overflow-auto rounded-(--rad-6) bg-muted/40 p-2 text-[10px] leading-relaxed text-muted-foreground">
+ {state.hasFrontmatter ? `---\n${state.frontmatterText}\n---` : "(no frontmatter)"}
+ </pre>
+ </div>
+ );
+}
+
+const FULL_SKILL = `name: reflection-coach
+description: Helps agents reflect on recent work and surface lessons.
+allowed-tools:
+ - Read
+ - Grep
+ - Bash
+metadata:
+ author: Paperclip
+ version: 2`;
+
+const meta: Meta<typeof Harness> = {
+ title: "Product/Skill Studio · FrontmatterPanel",
+ component: Harness,
+ parameters: { layout: "padded" },
+};
+
+export default meta;
+
+type Story = StoryObj<typeof Harness>;
+
+/** 1. Fields mode — full SKILL.md (name/description/allowed-tools/metadata). */
+export const FieldsFull: Story = {
+ args: { frontmatterText: FULL_SKILL, hasFrontmatter: true },
+};
+
+/** 2. Fields mode — unknown/extra keys rendered generically below known ones. */
+export const FieldsUnknownKeys: Story = {
+ args: {
+ frontmatterText: `name: reflection-coach
+description: Coach skill with extra keys.
+license: MIT
+version-tag: beta`,
+ hasFrontmatter: true,
+ },
+};
+
+/** 3. YAML mode — round-trippable block (toggle to Fields is enabled). */
+export const YamlRoundTrippable: Story = {
+ args: { frontmatterText: FULL_SKILL, hasFrontmatter: true },
+ parameters: {
+ docs: { description: { story: "Round-trippable — switch to the YAML tab to edit raw." } },
+ },
+};
+
+/** 4. Non-round-trippable — Fields disabled + tooltip + info banner (comments). */
+export const NonRoundTrippable: Story = {
+ args: {
+ frontmatterText: `name: reflection-coach # keep this comment
+description: Uses YAML features the form can't round-trip.
+allowed-tools:
+ - Read`,
+ hasFrontmatter: true,
+ },
+};
+
+/** 5. Unparseable YAML — parse-error notice, forced to YAML. */
+export const UnparseableYaml: Story = {
+ args: {
+ frontmatterText: `:::: not valid yaml ::::
+- [broken`,
+ hasFrontmatter: true,
+ },
+};
+
+/** 6. Validation — missing name/description on SKILL.md (chip + inline). */
+export const ValidationMissingFields: Story = {
+ args: { frontmatterText: `allowed-tools:\n - Read`, hasFrontmatter: true },
+};
+
+/** 7. Validation — wrong type (allowed-tools as a string, not a list). */
+export const ValidationWrongType: Story = {
+ args: {
+ frontmatterText: `name: reflection-coach
+description: allowed-tools is a string, not a list.
+allowed-tools: Read`,
+ hasFrontmatter: true,
+ },
+};
+
+/** 8a. Collapsed summary row on a non-SKILL file (no warnings). */
+export const CollapsedSummary: Story = {
+ args: {
+ frontmatterText: `name: reference-notes
+allowed-tools:
+ - Read
+ - Grep
+metadata:
+ author: Paperclip`,
+ hasFrontmatter: true,
+ fileName: "reference/notes.md",
+ },
+};
+
+/** 8b. Collapsed summary row with a warning chip (invalid slug). */
+export const CollapsedSummaryWithWarning: Story = {
+ args: {
+ frontmatterText: `name: Not A Slug
+allowed-tools:
+ - Read`,
+ hasFrontmatter: true,
+ fileName: "reference/notes.md",
+ },
+};
+
+/** 9a. No frontmatter on SKILL.md — "+ Add frontmatter" seeds from the slug. */
+export const NoFrontmatterSkill: Story = {
+ args: { frontmatterText: "", hasFrontmatter: false, fileName: "SKILL.md" },
+};
+
+/** 9b. No frontmatter on a reference file — add seeds an empty block. */
+export const NoFrontmatterReference: Story = {
+ args: { frontmatterText: "", hasFrontmatter: false, fileName: "reference/notes.md" },
+};
+
+/** 10. Read-only variant — fields shown, no edit affordances. */
+export const ReadOnly: Story = {
+ args: { frontmatterText: FULL_SKILL, hasFrontmatter: true, readOnly: true },
+};
+
+/** Narrow pane — confirm single-column form + chip-wrap don't overflow. */
+export const NarrowPane: Story = {
+ args: { frontmatterText: FULL_SKILL, hasFrontmatter: true, width: 340 },
+};