Skip to content

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

feat(skills): open-by-default company skill policy and core UX (#9564)

Dotta89ce36d7afcb
diff --git a/doc/CLI.md b/doc/CLI.md
index 90775c94ed..392b3a440c 100644
--- a/doc/CLI.md
+++ b/doc/CLI.md
@@ -402,9 +402,11 @@ Required Paperclip runtime skills (heartbeat, etc.) remain server-enforced and
are added on top of whatever the desired set names.
Company skill mutations (`skills install`, `skills import`, `skills create`, and
-`skills scan-projects`) require board authentication, an explicit `skills:create`
-grant, or an agent whose permissions keep `canCreateSkills` enabled. They do not
-require `agents:create` unless the command also creates agents.
+`skills scan-projects`) are open to same-company actors by default. Missing
+`skills:create` grants and `canCreateSkills` settings do not deny these commands;
+only an explicit company skill policy restriction does. Core safety and company
+boundary checks still apply, and `agents:create` remains required when a command
+also creates agents.
### Catalog (app-shipped skills)
diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md
index 7a3d1f7b40..f276d3dfbc 100644
--- a/doc/PRODUCT.md
+++ b/doc/PRODUCT.md
@@ -58,6 +58,16 @@ Tasks have parentage. Every task exists in service of a parent task, all the way
The current issue model includes stable issue identifiers, parent/sub-issues, blockers, a single assignee, comments, issue documents, attachments and work products, and review/approval handoffs. That structure keeps work inspectable by both the board and agents while still allowing agents to decompose work into smaller tasks.
+### Company Skills and Policy
+
+Company skills are shared operating capabilities, not privileged objects by default. Every authenticated agent in a company can create, import, install, edit, update, test, reset, and remove that company's skills unless the company has configured an explicit restriction.
+
+The governing rule is: **skill permissions are opt-in restrictions, not opt-in capabilities**. Missing skill grants never create a denial in an otherwise unconfigured company, and ordinary skill work does not require board confirmation, a draft-only workflow, or an activation approval.
+
+Core Paperclip owns the skill runtime, company-boundary enforcement, policy evaluation contract, API denials, validation, path containment, secret redaction, and activity logging. Those safety invariants cannot be disabled by policy. Open-by-default skill work never authorizes arbitrary host-path reads, unsafe executable content, or policy edits: local imports and scans must stay within Paperclip-known workspace or managed-skill roots, remote sources must resolve to validated immutable content, and platform safety denials must stay distinct from optional administrative restrictions. Paperclip EE may provide detailed administration for per-agent, per-role, per-action, per-source, and protected-skill rules, but EE is not required to use skills and is not an enforcement boundary. Without EE, companies remain open by default and any already-configured restrictions continue to be enforced by core.
+
+An explicit restricted policy may deny selected operations or switch to a default-deny preset with explicit allow rules. Core exposes a stable versioned policy API so EE and other administrative clients configure and simulate the same evaluator used by skill mutation routes. Core Skill Studio only needs to perform normal skill work, explain an explicit denial, and point administrators to EE when its richer policy UI is available; it must not recreate a partial enterprise permission editor.
+
## Principles
1. **Unopinionated about how you run your agents.** Your agents could be OpenClaw bots, Python scripts, Node scripts, Claude Code sessions, Codex instances — we don't care. Paperclip defines the control plane for communication and provides utility infrastructure for heartbeats. It does not mandate an agent runtime.
diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md
index 13793545ad..b705aa9da4 100644
--- a/doc/SPEC-implementation.md
+++ b/doc/SPEC-implementation.md
@@ -573,6 +573,7 @@ The approved term set is:
| Assignment/invocation | Assignment creates execution authority; board can reassign or force release | Delegation policies and scoped invokers with deny-listed tool classes |
| Work-object visibility | All issues and projects in-company are visible to board and agents | Project/issue ACLs and reviewer-only channels |
| Tool/secret policy | Secret refs, log redaction, and adapter-level command/webhook restrictions | Tool allowlists with centralized policy evaluation |
+| Company skills | Open to authenticated company agents; core enforces invariants and any stored restriction policy | Paperclip EE policy editor, protected-skill controls, presets, simulation, and policy audit UX |
| Escalation | Escalate from agent to manager to board; board approval/budget gates remain authoritative | Escalation routing and SLA windows |
## 9.7 Recommended first-slice implementation order
@@ -669,6 +670,120 @@ Implementation, security, UI, and QA work for task watchdogs must prove these co
No unresolved policy decision blocks implementation once CTO and Security accept this contract. Deliberately deferred and disallowed for the first implementation: resolving interaction kinds beyond eligible plan confirmations, letting watchdogs cancel active runs, approving board/governance actions, mutating outside the watched subtree, or allowing watchdog agents to modify their own watchdog configuration. Any expansion requires a new product/security review.
+## 9.10 Company Skill Policy Contract
+
+### Product default
+
+An authenticated agent may perform normal company-skill work without a skill-specific grant when the target company has no explicit skill policy. This includes creating, importing, installing, editing, updating, testing, resetting, and removing skills. Core MUST NOT introduce a `skills:author` prerequisite, a draft-only default, or an activation-approval default.
+
+Authorization order is fixed:
+
+1. Enforce non-configurable platform invariants.
+2. Evaluate the company's explicit skill policy when one exists.
+3. Otherwise allow the authenticated company agent.
+
+Non-configurable invariants include authenticated actor identity, exact company scoping, source and workspace path containment, package and frontmatter validation, secret redaction/non-export, immutable audit attribution, and any hard runtime isolation rule. A policy rule, legacy grant, plugin, or EE configuration cannot override these invariants.
+
+For avoidance of doubt:
+
+- Local-path imports, updates, resets, and project scans MUST resolve under a Paperclip-known local workspace root or a Paperclip-managed skill root. Arbitrary host filesystem paths are invalid even when the caller is otherwise authorized. Caller-supplied `source`, `sourceLocator`, or similar path strings are descriptive input only; they MUST NOT expand authority beyond those approved roots.
+- Remote imports and updates MUST normalize to a known source category, require validated HTTPS or catalog sources, and resolve immutable content before install (for example pinned Git commit/content hash or pinned package version). Unknown schemes, unknown source categories, symlink escapes, and out-of-tree files fail closed before persistence.
+- Unsafe executable content, fetch-and-exec patterns, and secret exfiltration or non-redacted secret material are platform safety failures. Policy cannot waive them; the route MUST reject the operation before any new skill version, install, update, or reset is persisted.
+- Mandatory activity attribution is part of the invariant boundary. If the required audit record for a skill mutation or policy mutation cannot be persisted, the mutation MUST fail or roll back; do not return success with missing auditability.
+
+### Canonical actions and resources
+
+The version 1 evaluator uses these stable action identifiers:
+
+- `skills.create`: create or fork a company-authored skill and create skill versions
+- `skills.import`: import or scan skills from a workspace, Git source, URL, or package
+- `skills.install`: install a catalog or externally sourced skill into the company
+- `skills.edit`: change skill metadata, name, files, test inputs, or test templates
+- `skills.update`: install a newer upstream revision
+- `skills.test`: start, cancel, or remove a skill test run and run a skill audit
+- `skills.reset`: restore the installed/upstream revision
+- `skills.remove`: delete a company skill
+
+Policy resources may include `skillId`, stable `skillKey`, `sourceType`, and `sourceLocator`. The stable source categories are `workspace`, `catalog`, `git`, `external_package`, `generated`, and `unknown`; adapters may preserve a more specific source value as metadata, but policy evaluation MUST normalize it to one of these categories. Core derives actor and company identity from authentication and derives known resource fields from stored data; a mutation client cannot authorize itself by supplying actor or resource identity fields.
+
+### Version 1 policy document
+
+Absence of a policy record is semantically equivalent to the following document, but core SHOULD avoid materializing records for untouched companies:
+
+```json
+{
+ "schemaVersion": 1,
+ "revision": 0,
+ "defaultEffect": "allow",
+ "rules": []
+}
+```
+
+An explicit policy has a monotonically increasing `revision`, a `defaultEffect` of `allow` or `deny`, and ordered rules. Each rule contains a stable `id`, integer `priority`, `effect` (`allow` or `deny`), a subject selector (`all_agents`, agent ids, or role names), one or more canonical actions, and optional resource selectors for skill ids/keys and normalized source types/locators. An omitted resource selector matches every resource for the listed action.
+
+Rules are evaluated by ascending `priority`, then stable rule id; the first matching rule decides. If no rule matches, `defaultEffect` decides. This supports both the normal open policy with targeted deny rules and an opt-in restricted preset with default deny plus explicit allow rules. Core MUST validate policy documents atomically and reject ambiguous, unknown-version, unknown-action, cross-company, or malformed selectors with `422`.
+
+Every decision returned by the evaluator has this stable shape:
+
+```json
+{
+ "allowed": false,
+ "action": "skills.install",
+ "reason": "explicit_rule",
+ "policyRevision": 7,
+ "matchedRuleId": "deny-external-packages",
+ "remediation": "Contact a company administrator to change the skill policy."
+}
+```
+
+`reason` is one of `platform_invariant`, `no_policy_default`, `explicit_rule`, `policy_default`, or `legacy_compatibility`. Mutation routes MUST use this evaluator and return `403` with code `skill_policy_denied` and the non-sensitive decision fields when an explicit restriction denies an operation. Denials must identify the action and remediation without exposing hidden rule data, secrets, or another company's policy.
+
+Platform-invariant failures are not policy denials and MUST use stable machine-readable error codes so clients can distinguish non-overridable safety failures from optional administrative restrictions. Version 1 requires a finite code set covering at least:
+
+- `skill_authentication_required`
+- `skill_company_boundary_denied`
+- `skill_workspace_boundary_denied`
+- `skill_source_validation_failed`
+- `skill_unsafe_content_blocked`
+- `skill_secret_handling_blocked`
+- `skill_policy_admin_required`
+
+Core Skill Studio and Paperclip EE MUST treat those codes as hard platform failures, not as prompts to loosen policy.
+
+### Core API and ownership boundary
+
+Core owns and ships these company-scoped endpoints:
+
+- `GET /companies/:companyId/skill-policy` returns the effective versioned policy, its revision, and whether it is materialized or the open default.
+- `PUT /companies/:companyId/skill-policy` atomically replaces the policy and requires the caller's expected revision; stale writes return `409`.
+- `DELETE /companies/:companyId/skill-policy` removes explicit configuration and restores the open default.
+- `POST /companies/:companyId/skill-policy/evaluate` simulates decisions for administrative tooling without performing a skill mutation.
+
+Policy reads, writes, deletion, and simulation enforce company access. Policy mutation and cross-principal simulation require board administration authority or the existing `users:manage_permissions` capability; ordinary skill access does not. Every policy mutation writes an activity event containing the actor, previous revision, new revision, and a redacted change summary. Skill mutation activity logging remains required independently of the policy decision.
+
+Paperclip EE owns the detailed editor, presets, protected-skill management, policy simulation UX, and policy-specific audit views. EE consumes the core endpoints and does not implement a second evaluator. Core may expose a concise effective-policy summary and denial state, but MUST NOT depend on EE for enforcement or make EE installation a prerequisite for normal skill work.
+
+### Compatibility and availability
+
+- Existing companies with no explicit restriction adopt the open default, including companies that previously depended on missing grants to deny skill changes. Release notes and upgrade guidance MUST call out this behavior change.
+- Existing explicit restriction policies remain effective after migration.
+- Legacy `skills:create` and `skills:suggest-changes` positive grants remain accepted in APIs and portability packages. Historically either positive grant authorized the broad company-skill mutation surface, so in an explicit restricted policy either grant remains a compatibility allow fallback for all eight canonical skill actions only when no explicit rule matched. They never override an explicit deny or a platform invariant. With no explicit policy they are redundant because the default already allows the action.
+- Legacy `skills:suggest-changes` consent state is not a platform invariant for company skills and does not add a second mutation gate under the open-default policy. Companies that require approval or consent before skill changes must express that restriction through explicit skill-policy rules; authentication, company boundaries, source containment, validation, auditability, and runtime safety remain non-configurable invariants.
+- Import preview MUST report whether a package contains an explicit skill policy or legacy grants and how each will map. Import apply MUST preserve explicit policies, normalize supported legacy grants, and reject unknown policy versions rather than silently weakening them.
+- Export MUST include explicit skill policy configuration and retained legacy grants in `.paperclip.yaml`, never secret values or environment-specific paths. An unconfigured company exports no synthetic restriction.
+- If Paperclip EE is unavailable or removed, core continues to enforce stored policies and expose the policy API. Normal skill work remains available under the open default; explicit denials use core remediation text rather than a broken EE-only link.
+
+### Required regression tests
+
+Phase 2 server tests and Phase 4 UI tests must prove:
+
+- unauthenticated actors and authenticated actors from another company are denied for all skill mutation routes and all skill-policy routes
+- local-path imports and project scans reject paths outside approved workspace or managed-skill roots, including symlink escapes and out-of-tree files
+- remote imports and updates reject unknown schemes/categories, unpinned mutable refs, unsafe executable content, and secret exfiltration patterns before persistence
+- policy mutation, policy reset, and cross-principal policy simulation require board administration authority or `users:manage_permissions`; ordinary open-default skill access never grants those actions
+- explicit policy denials return `skill_policy_denied`, while platform safety failures return the stable invariant denial codes above
+- successful skill mutations and policy mutations persist activity records with actor, company, run attribution, normalized action, and revision/change summary; audit-write failures do not leave successful unaudited mutations behind
+
## 10. API Contract (REST)
All endpoints are under `/api` and return JSON.
@@ -814,6 +929,7 @@ The current app also exposes V1-supporting surfaces for:
- routines and scheduled/API/webhook triggers
- plugin installation, configuration, state, jobs, logs, webhooks, and plugin database namespace migration
- company import/export preview/apply, feedback export/vote routes, instance backup/config routes, invites, join requests, memberships, and permission grants
+- company skill policy read/replace/reset/simulation, enforced by the same core evaluator used by skill mutation routes
## 11. Heartbeat and Adapter Contract
@@ -1142,6 +1258,7 @@ Export/import behavior in V1:
- Paperclip imports recurring task packages as routines instead of downgrading them to one-time issues
- export strips environment-specific paths (`cwd`, local instruction file paths, inline prompt duplication) while preserving portable project repo/workspace metadata such as `repoUrl`, refs, and workspace-policy references keyed in `.paperclip.yaml`
- export never includes secret values; env inputs are reported as portable declarations instead
+- export preserves explicit company skill policy and retained legacy skill grants in `.paperclip.yaml`; absence of policy remains the open default
- import supports target modes:
- create a new company
- import into an existing company
@@ -1149,4 +1266,5 @@ Export/import behavior in V1:
- import forces imported agent timer heartbeats off so packages never start scheduled runs implicitly
- import supports collision strategies: `rename`, `skip`, `replace`
- import supports preview (dry-run) before apply
+- import preview reports skill-policy and legacy-grant mappings before apply and rejects unknown policy schema versions
- GitHub imports warn on unpinned refs instead of blocking
diff --git a/packages/db/src/migrations/0170_company_skill_policies.sql b/packages/db/src/migrations/0170_company_skill_policies.sql
new file mode 100644
index 0000000000..2b9b91dc32
--- /dev/null
+++ b/packages/db/src/migrations/0170_company_skill_policies.sql
@@ -0,0 +1,12 @@
+CREATE TABLE IF NOT EXISTS "company_skill_policies" (
+ "company_id" uuid PRIMARY KEY NOT NULL REFERENCES "companies"("id") ON DELETE CASCADE,
+ "schema_version" integer DEFAULT 1 NOT NULL,
+ "revision" integer NOT NULL,
+ "default_effect" text NOT NULL,
+ "rules" jsonb DEFAULT '[]'::jsonb NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "company_skill_policies_schema_version_check" CHECK ("schema_version" = 1),
+ CONSTRAINT "company_skill_policies_revision_check" CHECK ("revision" > 0),
+ CONSTRAINT "company_skill_policies_default_effect_check" CHECK ("default_effect" IN ('allow', 'deny'))
+);
diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json
index b5fae44d7a..80f6e4628c 100644
--- a/packages/db/src/migrations/meta/_journal.json
+++ b/packages/db/src/migrations/meta/_journal.json
@@ -1177,6 +1177,13 @@
"when": 1783953536660,
"tag": "0169_tool_gateway_protocol_rate_limit_counters",
"breakpoints": true
+ },
+ {
+ "idx": 170,
+ "version": "7",
+ "when": 1784037600000,
+ "tag": "0170_company_skill_policies",
+ "breakpoints": true
}
]
}
diff --git a/packages/db/src/schema/company_skill_policies.ts b/packages/db/src/schema/company_skill_policies.ts
new file mode 100644
index 0000000000..46e00ebc9f
--- /dev/null
+++ b/packages/db/src/schema/company_skill_policies.ts
@@ -0,0 +1,12 @@
+import { integer, jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
+import { companies } from "./companies.js";
+
+export const companySkillPolicies = pgTable("company_skill_policies", {
+ companyId: uuid("company_id").primaryKey().references(() => companies.id, { onDelete: "cascade" }),
+ schemaVersion: integer("schema_version").notNull().default(1),
+ revision: integer("revision").notNull(),
+ defaultEffect: text("default_effect").$type<"allow" | "deny">().notNull(),
+ rules: jsonb("rules").$type<Array<Record<string, unknown>>>().notNull().default([]),
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
+});
diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts
index 545131409c..c84a2ab120 100644
--- a/packages/db/src/schema/index.ts
+++ b/packages/db/src/schema/index.ts
@@ -13,6 +13,7 @@ export { cliAuthChallenges } from "./cli_auth_challenges.js";
export { companyMemberships } from "./company_memberships.js";
export { companyUserSidebarPreferences } from "./company_user_sidebar_preferences.js";
export { principalPermissionGrants } from "./principal_permission_grants.js";
+export { companySkillPolicies } from "./company_skill_policies.js";
export { invites } from "./invites.js";
export { joinRequests } from "./join_requests.js";
export { budgetPolicies } from "./budget_policies.js";
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 38db63ec1d..587c429582 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -2108,3 +2108,4 @@ export {
type CreateEnvironmentCustomImageTerminalSessionToken,
type EnvironmentCustomImageTerminalSessionToken,
} from "./validators/environment-custom-images.js";
+export * from "./validators/skill-policy.js";
diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts
index bb42ffc52f..d3ccb2aa70 100644
--- a/packages/shared/src/validators/index.ts
+++ b/packages/shared/src/validators/index.ts
@@ -833,3 +833,4 @@ export {
type CreateToolTrustRuleFromActionRequest,
type RevokeToolTrustRule,
} from "./tool-access.js";
+export * from "./skill-policy.js";
diff --git a/packages/shared/src/validators/skill-policy.test.ts b/packages/shared/src/validators/skill-policy.test.ts
new file mode 100644
index 0000000000..b9d74af4d8
--- /dev/null
+++ b/packages/shared/src/validators/skill-policy.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+import {
+ normalizeSkillPolicySourceLocator,
+ skillPolicyDocumentSchema,
+ skillPolicyEvaluationResourceSchema,
+} from "./skill-policy.js";
+
+const credentialBearingLocators = [
+ "https://vault.example/?token=hvs.x",
+ "https://vault.example/?api_key=secret",
+ "https://vault.example/#token=hvs.x",
+ "https://vault.example/#section?authorization=Bearer",
+];
+
+describe("skill policy source locators", () => {
+ it.each(credentialBearingLocators)("rejects credential-bearing locator %s in policy rules", (sourceLocator) => {
+ expect(() => skillPolicyDocumentSchema.parse({
+ schemaVersion: 1,
+ defaultEffect: "allow",
+ rules: [{
+ id: "deny-secret-source",
+ priority: 1,
+ effect: "deny",
+ subject: { type: "all_agents" },
+ actions: ["skills.import"],
+ resources: { sourceLocators: [sourceLocator] },
+ }],
+ })).toThrow(/credentials or secret query or fragment parameters/i);
+ });
+
+ it.each(credentialBearingLocators)("rejects credential-bearing locator %s in evaluations", (sourceLocator) => {
+ expect(() => skillPolicyEvaluationResourceSchema.parse({ sourceLocator }))
+ .toThrow(/credentials or secret query or fragment parameters/i);
+ });
+
+ it("allows non-secret URL fragments", () => {
+ expect(skillPolicyEvaluationResourceSchema.parse({
+ sourceLocator: "https://docs.example/skill#installation",
+ })).toEqual({ sourceLocator: "https://docs.example/skill#installation" });
+ });
+});
+
+describe("normalizeSkillPolicySourceLocator", () => {
+ it.each([
+ ["https://github.com/Owner/Repo.git", "https://github.com/owner/repo"],
+ ["https://WWW.GitHub.com/Owner/Repo", "https://github.com/owner/repo"],
+ ["https://GitLab.com/Owner/Repo.git", "https://gitlab.com/owner/repo"],
+ ["https://github.com/Owner/Repo/tree/Main/Skills", "https://github.com/owner/repo/tree/Main/Skills"],
+ [" https://github.com/owner/repo ", "https://github.com/owner/repo"],
+ ])("canonicalizes repo-style locator %s", (input, expected) => {
+ expect(normalizeSkillPolicySourceLocator(input)).toBe(expected);
+ });
+
+ it.each([
+ "/srv/company/skills/pr-gardening",
+ "@paperclipai/skill-pack",
+ "https://gist.github.com/Owner/abc123",
+ "https://raw.githubusercontent.com/Owner/Repo/main/SKILL.md",
+ "https://docs.example/skill#installation",
+ ])("leaves non-repo locator %s unchanged", (input) => {
+ expect(normalizeSkillPolicySourceLocator(input)).toBe(input);
+ });
+
+ it("is idempotent", () => {
+ const once = normalizeSkillPolicySourceLocator("https://github.com/Owner/Repo.git");
+ expect(normalizeSkillPolicySourceLocator(once)).toBe(once);
+ });
+
+ it("normalizes rule sourceLocators on parse so deny rules match normalized resources", () => {
+ const parsed = skillPolicyDocumentSchema.parse({
+ schemaVersion: 1,
+ defaultEffect: "allow",
+ rules: [{
+ id: "deny-repo",
+ priority: 1,
+ effect: "deny",
+ subject: { type: "all_agents" },
+ actions: ["skills.import"],
+ resources: { sourceLocators: ["https://github.com/Owner/Repo.git"] },
+ }],
+ });
+ expect(parsed.rules[0]!.resources!.sourceLocators).toEqual(["https://github.com/owner/repo"]);
+ });
+
+ it("normalizes evaluation resource sourceLocators on parse", () => {
+ expect(skillPolicyEvaluationResourceSchema.parse({
+ sourceLocator: "https://WWW.GitHub.com/Owner/Repo.git",
+ })).toEqual({ sourceLocator: "https://github.com/owner/repo" });
+ });
+
+ it("rejects locators that collapse to duplicates after normalization", () => {
+ expect(() => skillPolicyDocumentSchema.parse({
+ schemaVersion: 1,
+ defaultEffect: "allow",
+ rules: [{
+ id: "deny-repo",
+ priority: 1,
+ effect: "deny",
+ subject: { type: "all_agents" },
+ actions: ["skills.import"],
+ resources: { sourceLocators: ["https://github.com/Owner/Repo.git", "https://github.com/owner/repo"] },
+ }],
+ })).toThrow(/unique/i);
+ });
+});
diff --git a/packages/shared/src/validators/skill-policy.ts b/packages/shared/src/validators/skill-policy.ts
new file mode 100644
index 0000000000..04c4fe6b69
--- /dev/null
+++ b/packages/shared/src/validators/skill-policy.ts
@@ -0,0 +1,156 @@
+import { z } from "zod";
+
+export const SKILL_POLICY_ACTIONS = [
+ "skills.create",
+ "skills.import",
+ "skills.install",
+ "skills.edit",
+ "skills.update",
+ "skills.test",
+ "skills.reset",
+ "skills.remove",
+] as const;
+
+export const SKILL_POLICY_SOURCE_TYPES = [
+ "workspace",
+ "catalog",
+ "git",
+ "external_package",
+ "generated",
+ "unknown",
+] as const;
+
+export const skillPolicyActionSchema = z.enum(SKILL_POLICY_ACTIONS);
+export const skillPolicySourceTypeSchema = z.enum(SKILL_POLICY_SOURCE_TYPES);
+export const skillPolicyEffectSchema = z.enum(["allow", "deny"]);
+
+const nonEmptyUniqueStrings = z.array(z.string().trim().min(1).max(512)).min(1).max(500)
+ .refine((values) => new Set(values).size === values.length, "Values must be unique");
+
+function isSafeSourceLocator(value: string) {
+ if (/:\/\/[^/@\s]+:[^/@\s]+@/.test(value)) return false;
+ try {
+ const url = new URL(value);
+ if (url.username || url.password) return false;
+ const credentialParameter = /token|secret|password|api[-_]?key|authorization/i;
+ if ([...url.searchParams.keys()].some((key) => credentialParameter.test(key))) return false;
+ const fragment = url.hash.slice(1);
+ return !/(?:^|[?&;])(?:token|secret|password|api[-_]?key|authorization)=/i.test(fragment);
+ } catch {
+ return true;
+ }
+}
+
+// Canonical form matching the server-side remote-import normalization: repo-style
+// https URLs get a lowercased host (www.github.com -> github.com), lowercased
+// owner/repo, and a stripped .git suffix. Evaluation resources are normalized the
+// same way, so rules must be too or deny rules silently never match.
+export function normalizeSkillPolicySourceLocator(value: string): string {
+ const trimmed = value.trim();
+ let url: URL;
+ try {
+ url = new URL(trimmed);
+ } catch {
+ return trimmed;
+ }
+ if (url.protocol !== "https:" && url.protocol !== "http:") return trimmed;
+ const hostname = url.hostname.toLowerCase() === "www.github.com" ? "github.com" : url.hostname.toLowerCase();
+ const segments = url.pathname.split("/").filter(Boolean);
+ const isRepoStyle = url.protocol === "https:"
+ && !hostname.endsWith(".githubusercontent.com")
+ && hostname !== "gist.github.com"
+ && segments.length >= 2
+ && !url.pathname.endsWith(".md")
+ && !url.username && !url.password && !url.search && !url.hash;
+ if (!isRepoStyle) return url.toString();
+ const owner = segments[0]!.toLowerCase();
+ const repo = segments[1]!.replace(/\.git$/i, "").toLowerCase();
+ const suffix = segments.slice(2).join("/");
+ return `https://${hostname}/${owner}/${repo}${suffix ? `/${suffix}` : ""}`;
+}
+
+const skillPolicySourceLocatorSchema = z.string().trim().min(1).max(2_048)
+ .refine(isSafeSourceLocator, "Source locators must not contain credentials or secret query or fragment parameters")
+ .transform(normalizeSkillPolicySourceLocator);
+
+export const skillPolicySubjectSchema = z.discriminatedUnion("type", [
+ z.object({ type: z.literal("all_agents") }).strict(),
+ z.object({
+ type: z.literal("agents"),
+ agentIds: z.array(z.string().uuid()).min(1).max(500)
+ .refine((values) => new Set(values).size === values.length, "Agent IDs must be unique"),
+ }).strict(),
+ z.object({ type: z.literal("roles"), roles: nonEmptyUniqueStrings }).strict(),
+]);
+
+export const skillPolicyResourceSelectorSchema = z.object({
+ skillIds: z.array(z.string().uuid()).min(1).max(500).optional(),
+ skillKeys: nonEmptyUniqueStrings.optional(),
+ sourceTypes: z.array(skillPolicySourceTypeSchema).min(1)
+ .refine((values) => new Set(values).size === values.length, "Source types must be unique")
+ .optional(),
+ sourceLocators: z.array(skillPolicySourceLocatorSchema).min(1).max(500)
+ .refine((values) => new Set(values).size === values.length, "Source locators must be unique")
+ .optional(),
+}).strict().refine((value) => Object.keys(value).length > 0, "At least one resource selector is required");
+
+export const skillPolicyRuleSchema = z.object({
+ id: z.string().trim().min(1).max(128).regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]*$/),
+ priority: z.number().int().min(-1_000_000).max(1_000_000),
+ effect: skillPolicyEffectSchema,
+ subject: skillPolicySubjectSchema,
+ actions: z.array(skillPolicyActionSchema).min(1)
+ .refine((values) => new Set(values).size === values.length, "Actions must be unique"),
+ resources: skillPolicyResourceSelectorSchema.optional(),
+}).strict();
+
+export const skillPolicyDocumentSchema = z.object({
+ schemaVersion: z.literal(1),
+ defaultEffect: skillPolicyEffectSchema,
+ rules: z.array(skillPolicyRuleSchema).max(1_000)
+ .refine((rules) => new Set(rules.map((rule) => rule.id)).size === rules.length, "Rule IDs must be unique"),
+}).strict();
+
+export const replaceSkillPolicySchema = skillPolicyDocumentSchema.extend({
+ expectedRevision: z.number().int().nonnegative(),
+}).strict();
+
+export const skillPolicyEvaluationResourceSchema = z.object({
+ skillId: z.string().uuid().optional(),
+ skillKey: z.string().trim().min(1).max(512).optional(),
+ sourceType: skillPolicySourceTypeSchema.optional(),
+ sourceLocator: skillPolicySourceLocatorSchema.optional(),
+}).strict();
+
+export const evaluateSkillPolicySchema = z.object({
+ action: skillPolicyActionSchema,
+ resource: skillPolicyEvaluationResourceSchema.default({}),
+ principal: z.object({ agentId: z.string().uuid() }).strict().optional(),
+}).strict();
+
+export type SkillPolicyAction = z.infer<typeof skillPolicyActionSchema>;
+export type SkillPolicySourceType = z.infer<typeof skillPolicySourceTypeSchema>;
+export type SkillPolicyEffect = z.infer<typeof skillPolicyEffectSchema>;
+export type SkillPolicySubject = z.infer<typeof skillPolicySubjectSchema>;
+export type SkillPolicyResourceSelector = z.infer<typeof skillPolicyResourceSelectorSchema>;
+export type SkillPolicyRule = z.infer<typeof skillPolicyRuleSchema>;
+export type SkillPolicyDocument = z.infer<typeof skillPolicyDocumentSchema>;
+export type ReplaceSkillPolicy = z.infer<typeof replaceSkillPolicySchema>;
+export type SkillPolicyEvaluationResource = z.infer<typeof skillPolicyEvaluationResourceSchema>;
+export type EvaluateSkillPolicy = z.infer<typeof evaluateSkillPolicySchema>;
+
+export type EffectiveSkillPolicy = SkillPolicyDocument & { revision: number; materialized: boolean };
+export type SkillPolicyDecisionReason =
+ | "platform_invariant"
+ | "no_policy_default"
+ | "explicit_rule"
+ | "policy_default"
+ | "legacy_compatibility";
+export type SkillPolicyDecision = {
+ allowed: boolean;
+ action: SkillPolicyAction;
+ reason: SkillPolicyDecisionReason;
+ policyRevision: number;
+ matchedRuleId: string | null;
+ remediation: string | null;
+};
diff --git a/server/src/__tests__/company-skill-import-boundary.test.ts b/server/src/__tests__/company-skill-import-boundary.test.ts
new file mode 100644
index 0000000000..9e096f1771
--- /dev/null
+++ b/server/src/__tests__/company-skill-import-boundary.test.ts
@@ -0,0 +1,86 @@
+import { randomUUID } from "node:crypto";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import { companies, companySkills, createDb, projects, projectWorkspaces } 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;
+
+describeEmbeddedPostgres("company skill local import boundary", () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+ const cleanupDirs = new Set<string>();
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-skill-import-boundary-");
+ db = createDb(tempDb.connectionString);
+ }, 20_000);
+
+ afterEach(async () => {
+ await db.delete(companySkills);
+ await db.delete(projectWorkspaces);
+ await db.delete(projects);
+ await db.delete(companies);
+ await Promise.all([...cleanupDirs].map((dir) => fs.rm(dir, { recursive: true, force: true })));
+ cleanupDirs.clear();
+ });
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ it("allows configured workspace imports and rejects out-of-tree and symlink escapes", async () => {
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const workspace = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-approved-workspace-"));
+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-outside-skill-"));
+ cleanupDirs.add(workspace);
+ cleanupDirs.add(outside);
+ await fs.writeFile(path.join(outside, "SKILL.md"), "---\nname: escaped\ndescription: escaped\n---\n# Escaped\n", "utf8");
+ const allowedSkill = path.join(workspace, ".agents", "skills", "allowed");
+ await fs.mkdir(allowedSkill, { recursive: true });
+ await fs.writeFile(path.join(allowedSkill, "SKILL.md"), "---\nname: allowed\ndescription: allowed\n---\n# Allowed\n", "utf8");
+ const symlink = path.join(workspace, "escaped-link");
+ await fs.symlink(outside, symlink);
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Boundary Co",
+ issuePrefix: `B${companyId.replaceAll("-", "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(projects).values({ id: projectId, companyId, name: "Approved project" });
+ await db.insert(projectWorkspaces).values({
+ companyId,
+ projectId,
+ name: "Primary",
+ cwd: workspace,
+ isPrimary: true,
+ });
+
+ const service = companySkillService(db);
+ await expect(service.importFromSource(companyId, allowedSkill)).resolves.toMatchObject({
+ imported: [expect.objectContaining({ slug: "allowed" })],
+ });
+ await expect(service.importFromSource(companyId, outside)).rejects.toMatchObject({
+ status: 403,
+ details: { code: "skill_workspace_boundary_denied" },
+ });
+ await expect(service.importFromSource(companyId, symlink)).rejects.toMatchObject({
+ status: 403,
+ details: { code: "skill_workspace_boundary_denied" },
+ });
+ await expect(service.importFromSource(companyId, "ftp://example.com/skill")).rejects.toMatchObject({
+ status: 422,
+ details: { code: "skill_source_validation_failed" },
+ });
+ await expect(service.importFromSource(companyId, "http://example.com/skill")).rejects.toMatchObject({
+ status: 422,
+ details: { code: "skill_source_validation_failed" },
+ });
+ });
+});
diff --git a/server/src/__tests__/company-skill-policy-routes.test.ts b/server/src/__tests__/company-skill-policy-routes.test.ts
new file mode 100644
index 0000000000..45a2586e1c
--- /dev/null
+++ b/server/src/__tests__/company-skill-policy-routes.test.ts
@@ -0,0 +1,201 @@
+import { randomUUID } from "node:crypto";
+import express from "express";
+import request from "supertest";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import { activityLog, agents, companies, companySkillPolicies, createDb } from "@paperclipai/db";
+import { errorHandler } from "../middleware/error-handler.js";
+import { companySkillPolicyRoutes } from "../routes/company-skill-policy.js";
+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
+
+describeEmbeddedPostgres("company skill policy routes", () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+ let companyId: string;
+ let otherCompanyId: string;
+ let agentId: string;
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-skill-policy-routes-");
+ db = createDb(tempDb.connectionString);
+ }, 20_000);
+
+ afterEach(async () => {
+ await db.delete(activityLog);
+ await db.delete(companySkillPolicies);
+ await db.delete(agents);
+ await db.delete(companies);
+ });
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ async function setupApp() {
+ companyId = randomUUID();
+ otherCompanyId = randomUUID();
+ agentId = randomUUID();
+ await db.insert(companies).values([
+ {
+ id: companyId,
+ name: "Policy Co",
+ issuePrefix: `P${companyId.replaceAll("-", "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ },
+ {
+ id: otherCompanyId,
+ name: "Other Co",
+ issuePrefix: `O${otherCompanyId.replaceAll("-", "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ },
+ ]);
+ await db.insert(agents).values({
+ id: agentId,
+ companyId,
+ name: "Builder",
+ role: "engineer",
+ adapterType: "process",
+ adapterConfig: {},
+ status: "idle",
+ });
+
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ const actor = req.header("x-test-actor");
+ req.actor = actor === "board"
+ ? {
+ type: "board",
+ source: "local_implicit",
+ userId: "board",
+ companyIds: [],
+ isInstanceAdmin: true,
+ }
+ : actor === "none"
+ ? { type: "none", source: "none" }
+ : {
+ type: "agent",
+ source: "agent_key",
+ agentId,
+ companyId: actor === "cross-company" ? otherCompanyId : companyId,
+ runId: null,
+ };
+ next();
+ });
+ app.use(companySkillPolicyRoutes(db));
+ app.use(errorHandler);
+ return app;
+ }
+
+ it("returns the open default and stable authentication/company boundary errors", async () => {
+ const app = await setupApp();
+ await request(app)
+ .get(`/companies/${companyId}/skill-policy`)
+ .expect(200)
+ .expect(({ body }) => expect(body).toMatchObject({ revision: 0, materialized: false, defaultEffect: "allow" }));
+ await request(app)
+ .get(`/companies/${companyId}/skill-policy`)
+ .set("x-test-actor", "none")
+ .expect(401)
+ .expect(({ body }) => expect(body.code).toBe("skill_authentication_required"));
+ await request(app)
+ .get(`/companies/${companyId}/skill-policy`)
+ .set("x-test-actor", "cross-company")
+ .expect(403)
+ .expect(({ body }) => expect(body.code).toBe("skill_company_boundary_denied"));
+ });
+
+ it("restricts policy administration, persists revisions, evaluates denials, and logs mutations", async () => {
+ const app = await setupApp();
+ const body = {
+ schemaVersion: 1,
+ expectedRevision: 0,
+ defaultEffect: "allow",
+ rules: [{
+ id: "deny-remove",
+ priority: 1,
+ effect: "deny",
+ subject: { type: "all_agents" },
+ actions: ["skills.remove"],
+ }],
+ };
+ await request(app)
+ .put(`/companies/${companyId}/skill-policy`)
+ .send(body)
+ .expect(403)
+ .expect(({ body: responseBody }) => expect(responseBody.code).toBe("skill_policy_admin_required"));
+ await request(app)
+ .put(`/companies/${companyId}/skill-policy`)
+ .set("x-test-actor", "board")
+ .send(body)
+ .expect(200)
+ .expect(({ body: responseBody }) => expect(responseBody).toMatchObject({ revision: 1, materialized: true }));
+ await request(app)
+ .put(`/companies/${companyId}/skill-policy`)
+ .set("x-test-actor", "board")
+ .send(body)
+ .expect(409)
+ .expect(({ body: responseBody }) => expect(responseBody.code).toBe("skill_policy_revision_conflict"));
+ await request(app)
+ .post(`/companies/${companyId}/skill-policy/evaluate`)
+ .send({ action: "skills.remove", resource: {} })
+ .expect(200)
+ .expect(({ body: responseBody }) => expect(responseBody).toMatchObject({
+ allowed: false,
+ reason: "explicit_rule",
+ matchedRuleId: "deny-remove",
+ }));
+ await request(app)
+ .post(`/companies/${companyId}/skill-policy/evaluate`)
+ .send({ action: "skills.remove", resource: {}, principal: { agentId } })
+ .expect(403)
+ .expect(({ body: responseBody }) => expect(responseBody.code).toBe("skill_policy_admin_required"));
+ await request(app)
+ .delete(`/companies/${companyId}/skill-policy`)
+ .set("x-test-actor", "board")
+ .expect(200)
+ .expect(({ body: responseBody }) => expect(responseBody).toMatchObject({ revision: 0, materialized: false }));
+ const activities = await db.select().from(activityLog);
+ expect(activities).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ companyId,
+ action: "company.skill_policy_replaced",
+ entityType: "company_skill_policy",
+ }),
+ expect.objectContaining({
+ companyId,
+ action: "company.skill_policy_reset",
+ entityType: "company_skill_policy",
+ }),
+ ]));
+ });
+
+ it("rejects unknown actions and secret-bearing policy locators with 422", async () => {
+ const app = await setupApp();
+ await request(app)
+ .post(`/companies/${companyId}/skill-policy/evaluate`)
+ .send({ action: "skills.publish", resource: {} })
+ .expect(422)
+ .expect(({ body }) => expect(body.code).toBe("skill_policy_validation_failed"));
+ await request(app)
+ .put(`/companies/${companyId}/skill-policy`)
+ .set("x-test-actor", "board")
+ .send({
+ schemaVersion: 1,
+ expectedRevision: 0,
+ defaultEffect: "allow",
+ rules: [{
+ id: "secret-locator",
+ priority: 1,
+ effect: "deny",
+ subject: { type: "all_agents" },
+ actions: ["skills.import"],
+ resources: { sourceLocators: ["https://example.com/skill?token=do-not-store"] },
+ }],
+ })
+ .expect(422)
+ .expect(({ body }) => expect(body.code).toBe("skill_policy_validation_failed"));
+ });
+});
diff --git a/server/src/__tests__/company-skill-policy-service.test.ts b/server/src/__tests__/company-skill-policy-service.test.ts
new file mode 100644
index 0000000000..cf2ff866ac
--- /dev/null
+++ b/server/src/__tests__/company-skill-policy-service.test.ts
@@ -0,0 +1,282 @@
+import { randomUUID } from "node:crypto";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import {
+ activityLog,
+ agents,
+ companies,
+ companySkillPolicies,
+ createDb,
+ principalPermissionGrants,
+} from "@paperclipai/db";
+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
+import { companySkillPolicyService } from "../services/company-skill-policy.js";
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
+
+describeEmbeddedPostgres("companySkillPolicyService", () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-skill-policy-");
+ db = createDb(tempDb.connectionString);
+ }, 20_000);
+
+ afterEach(async () => {
+ await db.delete(activityLog);
+ await db.delete(principalPermissionGrants);
+ await db.delete(companySkillPolicies);
+ await db.delete(agents);
+ await db.delete(companies);
+ });
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ async function seedAgent(role = "engineer") {
+ const companyId = randomUUID();
+ const agentId = randomUUID();
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Policy Co",
+ issuePrefix: `P${companyId.replaceAll("-", "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(agents).values({
+ id: agentId,
+ companyId,
+ name: "Policy Agent",
+ role,
+ adapterType: "process",
+ adapterConfig: {},
+ status: "idle",
+ });
+ return { companyId, agentId, principal: { type: "agent" as const, id: agentId, role } };
+ }
+
+ it("allows every canonical action when no explicit policy exists", async () => {
+ const seeded = await seedAgent();
+ const service = companySkillPolicyService(db);
+ for (const action of [
+ "skills.create",
+ "skills.import",
+ "skills.install",
+ "skills.edit",
+ "skills.update",
+ "skills.test",
+ "skills.reset",
+ "skills.remove",
+ ] as const) {
+ await expect(service.evaluate({
+ companyId: seeded.companyId,
+ principal: seeded.principal,
+ action,
+ })).resolves.toMatchObject({ allowed: true, action, reason: "no_policy_default", policyRevision: 0 });
+ }
+ });
+
+ it("evaluates protected resources, role overrides, and agent overrides deterministically", async () => {
+ const seeded = await seedAgent("security");
+ const service = companySkillPolicyService(db);
+ const protectedSkillId = randomUUID();
+ await service.replace({
+ companyId: seeded.companyId,
+ expectedRevision: 0,
+ policy: {
+ schemaVersion: 1,
+ defaultEffect: "allow",
+ rules: [
+ {
+ id: "agent-override",
+ priority: 1,
+ effect: "allow",
+ subject: { type: "agents", agentIds: [seeded.agentId] },
+ actions: ["skills.install"],
+ resources: { sourceTypes: ["external_package"] },
+ },
+ {
+ id: "security-override",
+ priority: 5,
+ effect: "allow",
+ subject: { type: "roles", roles: ["security"] },
+ actions: ["skills.edit"],
+ resources: { skillIds: [protectedSkillId] },
+ },
+ {
+ id: "protected-skill",
+ priority: 10,
+ effect: "deny",
+ subject: { type: "all_agents" },
+ actions: ["skills.edit", "skills.remove"],
+ resources: { skillIds: [protectedSkillId] },
+ },
+ {
+ id: "deny-external",
+ priority: 20,
+ effect: "deny",
+ subject: { type: "all_agents" },
+ actions: ["skills.install"],
+ resources: { sourceTypes: ["external_package"] },
+ },
+ ],
+ },
+ activity: { actorType: "agent", actorId: seeded.agentId, agentId: seeded.agentId },
+ });
+
+ await expect(service.evaluate({
+ companyId: seeded.companyId,
+ principal: seeded.principal,
+ action: "skills.edit",
+ resource: { skillId: protectedSkillId },
+ })).resolves.toMatchObject({ allowed: true, matchedRuleId: "security-override" });
+ await expect(service.evaluate({
+ companyId: seeded.companyId,
+ principal: seeded.principal,
+ action: "skills.remove",
+ resource: { skillId: protectedSkillId },
+ })).resolves.toMatchObject({ allowed: false, reason: "explicit_rule", matchedRuleId: "protected-skill" });
+ await expect(service.evaluate({
+ companyId: seeded.companyId,
+ principal: seeded.principal,
+ action: "skills.install",
+ resource: { sourceType: "external_package" },
+ })).resolves.toMatchObject({ allowed: true, matchedRuleId: "agent-override" });
+ });
+
+ it("uses retained legacy grants only after explicit rules fail to match", async () => {
+ const seeded = await seedAgent();
+ const service = companySkillPolicyService(db);
+ await db.insert(companySkillPolicies).values({
+ companyId: seeded.companyId,
+ schemaVersion: 1,
+ revision: 3,
+ defaultEffect: "deny",
+ rules: [{
+ id: "deny-removal",
+ priority: 1,
+ effect: "deny",
+ subject: { type: "all_agents" },
+ actions: ["skills.remove"],
+ }],
+ });
+ await db.insert(principalPermissionGrants).values({
+ companyId: seeded.companyId,
+ principalType: "agent",
+ principalId: seeded.agentId,
+ permissionKey: "skills:create",
+ scope: null,
+ });
+
+ await expect(service.evaluate({
+ companyId: seeded.companyId,
+ principal: seeded.principal,
+ action: "skills.edit",
+ })).resolves.toMatchObject({ allowed: true, reason: "legacy_compatibility" });
+ await expect(service.evaluate({
+ companyId: seeded.companyId,
+ principal: seeded.principal,
+ action: "skills.remove",
+ })).resolves.toMatchObject({ allowed: false, reason: "explicit_rule" });
+ });
+
+ it("matches sourceLocator deny rules regardless of GitHub URL casing or .git suffix", async () => {
+ const seeded = await seedAgent();
+ const service = companySkillPolicyService(db);
+ await service.replace({
+ companyId: seeded.companyId,
+ expectedRevision: 0,
+ policy: {
+ schemaVersion: 1,
+ defaultEffect: "allow",
+ rules: [{
+ id: "deny-repo",
+ priority: 1,
+ effect: "deny",
+ subject: { type: "all_agents" },
+ actions: ["skills.import"],
+ resources: { sourceLocators: ["https://WWW.GitHub.com/Owner/Repo.git"] },
+ }],
+ },
+ activity: { actorType: "agent", actorId: seeded.agentId, agentId: seeded.agentId },
+ });
+
+ const stored = await service.get(seeded.companyId);
+ expect(stored.rules[0]!.resources!.sourceLocators).toEqual(["https://github.com/owner/repo"]);
+ await expect(service.evaluate({
+ companyId: seeded.companyId,
+ principal: seeded.principal,
+ action: "skills.import",
+ resource: { sourceType: "git", sourceLocator: "https://github.com/owner/repo" },
+ })).resolves.toMatchObject({ allowed: false, reason: "explicit_rule", matchedRuleId: "deny-repo" });
+ await expect(service.evaluate({
+ companyId: seeded.companyId,
+ principal: seeded.principal,
+ action: "skills.import",
+ resource: { sourceType: "git", sourceLocator: "https://github.com/Owner/Repo.git" },
+ })).resolves.toMatchObject({ allowed: false, reason: "explicit_rule", matchedRuleId: "deny-repo" });
+ await expect(service.evaluate({
+ companyId: seeded.companyId,
+ principal: seeded.principal,
+ action: "skills.import",
+ resource: { sourceType: "git", sourceLocator: "https://github.com/owner/other-repo" },
+ })).resolves.toMatchObject({ allowed: true, reason: "policy_default" });
+ });
+
+ it("matches deny rules persisted before locator normalization existed", async () => {
+ const seeded = await seedAgent();
+ const service = companySkillPolicyService(db);
+ await db.insert(companySkillPolicies).values({
+ companyId: seeded.companyId,
+ schemaVersion: 1,
+ revision: 2,
+ defaultEffect: "allow",
+ rules: [{
+ id: "legacy-deny-repo",
+ priority: 1,
+ effect: "deny",
+ subject: { type: "all_agents" },
+ actions: ["skills.import"],
+ resources: { sourceLocators: ["https://github.com/Owner/Repo.git"] },
+ }],
+ });
+
+ await expect(service.evaluate({
+ companyId: seeded.companyId,
+ principal: seeded.principal,
+ action: "skills.import",
+ resource: { sourceType: "git", sourceLocator: "https://github.com/owner/repo" },
+ })).resolves.toMatchObject({ allowed: false, reason: "explicit_rule", matchedRuleId: "legacy-deny-repo" });
+ });
+
+ it("rejects cross-company simulation principals", async () => {
+ const first = await seedAgent();
+ const second = await seedAgent();
+ const service = companySkillPolicyService(db);
+ await expect(service.resolveAgentPrincipal(first.companyId, second.agentId)).rejects.toMatchObject({
+ status: 403,
+ details: { code: "skill_company_boundary_denied" },
+ });
+ });
+
+ it("rolls back policy replacement when the required activity record cannot persist", async () => {
+ const seeded = await seedAgent();
+ const service = companySkillPolicyService(db);
+ await expect(service.replace({
+ companyId: seeded.companyId,
+ expectedRevision: 0,
+ policy: { schemaVersion: 1, defaultEffect: "deny", rules: [] },
+ activity: {
+ actorType: "agent",
+ actorId: seeded.agentId,
+ agentId: randomUUID(),
+ },
+ })).rejects.toBeDefined();
+ await expect(service.get(seeded.companyId)).resolves.toMatchObject({
+ revision: 0,
+ materialized: false,
+ defaultEffect: "allow",
+ });
+ });
+});
diff --git a/server/src/__tests__/company-skills-import-authz-routes.test.ts b/server/src/__tests__/company-skills-import-authz-routes.test.ts
index 2942cb3de2..b7a945d1e4 100644
--- a/server/src/__tests__/company-skills-import-authz-routes.test.ts
+++ b/server/src/__tests__/company-skills-import-authz-routes.test.ts
@@ -41,11 +41,13 @@ describeEmbeddedPostgres("company skill import authorization routes", () => {
const cleanupDirs = new Set<string>();
const previousAgentJwtSecret = process.env.PAPERCLIP_AGENT_JWT_SECRET;
const previousPaperclipHome = process.env.PAPERCLIP_HOME;
+ const previousPaperclipInstanceId = process.env.PAPERCLIP_INSTANCE_ID;
beforeAll(async () => {
process.env.PAPERCLIP_AGENT_JWT_SECRET = "company-skills-import-authz-test-secret";
paperclipHome = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-company-skills-import-authz-home-"));
process.env.PAPERCLIP_HOME = paperclipHome;
+ process.env.PAPERCLIP_INSTANCE_ID = "default";
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-company-skills-import-authz-");
db = createDb(tempDb.connectionString);
}, 20_000);
@@ -72,6 +74,8 @@ describeEmbeddedPostgres("company skill import authorization routes", () => {
else process.env.PAPERCLIP_AGENT_JWT_SECRET = previousAgentJwtSecret;
if (previousPaperclipHome === undefined) delete process.env.PAPERCLIP_HOME;
else process.env.PAPERCLIP_HOME = previousPaperclipHome;
+ if (previousPaperclipInstanceId === undefined) delete process.env.PAPERCLIP_INSTANCE_ID;
+ else process.env.PAPERCLIP_INSTANCE_ID = previousPaperclipInstanceId;
});
function authenticatedApp() {
@@ -83,8 +87,14 @@ describeEmbeddedPostgres("company skill import authorization routes", () => {
return instance;
}
- async function writeSkillFixture() {
- const skillDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-import-authz-skill-"));
+ async function writeSkillFixture(companyId: string) {
+ if (!paperclipHome) throw new Error("Expected Paperclip test home");
+ // Local imports must originate from an approved root (managed-skill
+ // directory or a configured workspace); a bare tmpdir is rejected with
+ // skill_workspace_boundary_denied.
+ const managedRoot = path.join(paperclipHome, "instances", "default", "skills", companyId);
+ await fs.mkdir(managedRoot, { recursive: true });
+ const skillDir = await fs.mkdtemp(path.join(managedRoot, "paperclip-import-authz-skill-"));
cleanupDirs.add(skillDir);
await fs.writeFile(
path.join(skillDir, "SKILL.md"),
@@ -169,7 +179,7 @@ describeEmbeddedPostgres("company skill import authorization routes", () => {
it("lets a standard responsible-user agent JWT with skills:create import a company skill", async () => {
const { companyId, agent, responsibleUserId, runId } = await seedGrantedAgentWithResponsibleUser();
- const skillDir = await writeSkillFixture();
+ const skillDir = await writeSkillFixture(companyId);
const token = createLocalAgentJwt(agent.id, companyId, agent.adapterType, runId, responsibleUserId);
expect(token).toBeTruthy();
diff --git a/server/src/__tests__/company-skills-routes.test.ts b/server/src/__tests__/company-skills-routes.test.ts
index 1bd34a526b..e141e649d2 100644
--- a/server/src/__tests__/company-skills-routes.test.ts
+++ b/server/src/__tests__/company-skills-routes.test.ts
@@ -55,6 +55,11 @@ const mockCompanySkillService = vi.hoisted(() => ({
pruneExpiredTestHarnessIssues: vi.fn(),
}));
+const mockCompanySkillPolicyService = vi.hoisted(() => ({
+ resolveAgentPrincipal: vi.fn(),
+ evaluate: vi.fn(),
+}));
+
const mockIssueService = vi.hoisted(() => ({
create: vi.fn(),
getById: vi.fn(),
@@ -103,6 +108,26 @@ function denySkillChangeDecision(reason = "deny_no_grant", explanation = "Missin
};
}
+function denyTaskAssignDecision(reason = "deny_missing_grant", explanation = "Missing permission: tasks:assign") {
+ return {
+ allowed: false,
+ action: "tasks:assign",
+ reason,
+ explanation,
+ };
+}
+
+function denySkillPolicy(action = "skills.import") {
+ return {
+ allowed: false,
+ action,
+ reason: "explicit_rule",
+ policyRevision: 1,
+ matchedRuleId: "deny-skill-mutation",
+ remediation: "Contact a company administrator to change the skill policy.",
+ };
+}
+
function registerModuleMocks() {
vi.doMock("../routes/authz.js", async () => vi.importActual("../routes/authz.js"));
@@ -127,9 +152,25 @@ function registerModuleMocks() {
agentService: () => mockAgentService,
}));
- vi.doMock("../services/company-skills.js", () => ({
- companySkillService: () => mockCompanySkillService,
- }));
+ vi.doMock("../services/company-skills.js", async () => {
+ const actual = await vi.importActual<typeof import("../services/company-skills.js")>(
+ "../services/company-skills.js",
+ );
+ return {
+ ...actual,
+ companySkillService: () => mockCompanySkillService,
+ };
+ });
+
+ vi.doMock("../services/company-skill-policy.js", async () => {
+ const actual = await vi.importActual<typeof import("../services/company-skill-policy.js")>(
+ "../services/company-skill-policy.js",
+ );
+ return {
+ ...actual,
+ companySkillPolicyService: () => mockCompanySkillPolicyService,
+ };
+ });
vi.doMock("../services/skills-catalog.js", () => mockCatalogService);
@@ -178,6 +219,7 @@ describe("company skill mutation permissions", () => {
vi.doUnmock("../services/activity-log.js");
vi.doUnmock("../services/agents.js");
vi.doUnmock("../services/company-skills.js");
+ vi.doUnmock("../services/company-skill-policy.js");
vi.doUnmock("../services/skills-catalog.js");
vi.doUnmock("../services/change-consent-gate.js");
vi.doUnmock("../services/index.js");
@@ -630,6 +672,19 @@ describe("company skill mutation permissions", () => {
mockAccessService.canUser.mockResolvedValue(true);
mockAccessService.decide.mockResolvedValue(allowSkillChangeDecision());
mockAccessService.hasPermission.mockResolvedValue(false);
+ mockCompanySkillPolicyService.resolveAgentPrincipal.mockImplementation(async (_companyId, agentId) => ({
+ type: "agent",
+ id: agentId,
+ role: "engineer",
+ }));
+ mockCompanySkillPolicyService.evaluate.mockImplementation(async (input) => ({
+ allowed: true,
+ action: input.action,
+ reason: "no_policy_default",
+ policyRevision: 0,
+ matchedRuleId: null,
+ remediation: null,
+ }));
mockReflectionCoachMutationGate.assertConsented.mockResolvedValue(undefined);
});
@@ -702,7 +757,7 @@ describe("company skill mutation permissions", () => {
expect(mockCompanySkillService.resetSkill).toHaveBeenCalled();
});
- it("blocks board users without skills:create from mutating company skills", async () => {
+ it("allows board users without skills:create when no explicit skill policy exists", async () => {
mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
const res = await request(await createApp({
@@ -715,13 +770,309 @@ describe("company skill mutation permissions", () => {
.post("/api/companies/company-1/skills/import")
.send({ source: "https://github.com/vercel-labs/agent-browser" });
- expect(res.status, JSON.stringify(res.body)).toBe(403);
- expect(res.body.error).toBe("Missing permission: skills:create or skills:suggest-changes.");
+ expect(res.status, JSON.stringify(res.body)).toBe(201);
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "skill_config:update",
resource: { type: "company", companyId: "company-1" },
}));
expect(mockAccessService.canUser).not.toHaveBeenCalledWith("company-1", "board-user", "agents:create");
+ expect(mockCompanySkillService.importFromSource).toHaveBeenCalled();
+ });
+
+ it("returns a structured denial when an explicit skill policy blocks the action", async () => {
+ mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
+ mockCompanySkillPolicyService.evaluate.mockResolvedValue({
+ allowed: false,
+ action: "skills.import",
+ reason: "explicit_rule",
+ policyRevision: 4,
+ matchedRuleId: "deny-external",
+ remediation: "Contact a company administrator to change the skill policy.",
+ });
+
+ const res = await request(await createApp({
+ type: "agent",
+ agentId: "55555555-5555-4555-8555-555555555555",
+ companyId: "company-1",
+ runId: "run-1",
+ }))
+ .post("/api/companies/company-1/skills/import")
+ .send({ source: "https://packages.example.com/skill.tgz" });
+
+ expect(res.status, JSON.stringify(res.body)).toBe(403);
+ expect(res.body).toEqual({
+ error: "Skill action denied by company policy",
+ code: "skill_policy_denied",
+ reason: "explicit_rule",
+ remediation: "Contact a company administrator to change the skill policy.",
+ });
+ expect(JSON.stringify(res.body)).not.toContain("deny-external");
+ expect(JSON.stringify(res.body)).not.toContain("policyRevision");
+ expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
+ });
+
+ it("rejects secret-bearing remote import URLs without echoing the secret", async () => {
+ const source = "https://github.com/acme/private-skill?token=secret#token=secret";
+
+ const res = await request(await createApp({
+ type: "board",
+ userId: "local-board",
+ companyIds: ["company-1"],
+ source: "local_implicit",
+ isInstanceAdmin: false,
+ }))
+ .post("/api/companies/company-1/skills/import")
+ .send({ source });
+
+ expect(res.status, JSON.stringify(res.body)).toBe(422);
+ expect(res.body).toEqual({
+ error: "Remote skill source URLs cannot include credentials, query parameters, or fragments.",
+ });
+ expect(JSON.stringify(res.body)).not.toContain("secret");
+ expect(mockCompanySkillPolicyService.evaluate).not.toHaveBeenCalled();
+ expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
+ });
+
+ it("rejects malformed remote import URLs before policy evaluation", async () => {
+ const res = await request(await createApp({
+ type: "board",
+ userId: "local-board",
+ companyIds: ["company-1"],
+ source: "local_implicit",
+ isInstanceAdmin: false,
+ }))
+ .post("/api/companies/company-1/skills/import")
+ .send({ source: "https://" });
+
+ expect(res.status, JSON.stringify(res.body)).toBe(422);
+ expect(res.body).toEqual({
+ error: "Invalid remote skill source URL.",
+ });
+ expect(mockCompanySkillPolicyService.evaluate).not.toHaveBeenCalled();
+ expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
+ });
+
+ it("keeps platform actor restrictions separate from optional policy denials", async () => {
+ mockAccessService.decide.mockResolvedValue(denySkillChangeDecision(
+ "deny_low_trust_boundary",
+ "Low-trust agents cannot use company-wide skill APIs.",
+ ));
+
+ const res = await request(await createApp({
+ type: "agent",
+ agentId: "55555555-5555-4555-8555-555555555555",
+ companyId: "company-1",
+ runId: "run-1",
+ }))
+ .post("/api/companies/company-1/skills/import")
+ .send({ source: "https://github.com/vercel-labs/agent-browser" });
+
+ expect(res.status, JSON.stringify(res.body)).toBe(403);
+ expect(res.body).toMatchObject({
+ code: "skill_actor_restricted",
+ details: { reason: "platform_invariant" },
+ });
+ expect(mockCompanySkillPolicyService.evaluate).not.toHaveBeenCalled();
+ });
+
+ it("blocks shorthand GitHub imports when policy denies the canonical git source locator", async () => {
+ mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
+ mockCompanySkillPolicyService.evaluate.mockImplementation(async (input: { resource?: { sourceType?: string; sourceLocator?: string } }) => {
+ const resource = input.resource ?? {};
+ return resource.sourceType === "git" && resource.sourceLocator === "https://github.com/vercel-labs/agent-browser"
+ ? denySkillPolicy("skills.import")
+ : {
+ allowed: true,
+ action: "skills.import",
+ reason: "policy_default",
+ policyRevision: 1,
+ matchedRuleId: null,
+ remediation: null,
+ };
+ });
+
+ const res = await request(await createApp({
+ type: "board",
+ userId: "board-user",
+ companyIds: ["company-1"],
+ source: "session",
+ isInstanceAdmin: false,
+ }))
+ .post("/api/companies/company-1/skills/import")
+ .send({ source: "vercel-labs/agent-browser" });
+
+ expect(res.status, JSON.stringify(res.body)).toBe(403);
+ expect(res.body.error).toBe("Skill action denied by company policy");
+ expect(mockCompanySkillPolicyService.evaluate).toHaveBeenCalledWith(expect.objectContaining({
+ companyId: "company-1",
+ action: "skills.import",
+ resource: expect.objectContaining({
+ sourceType: "git",
+ sourceLocator: "https://github.com/vercel-labs/agent-browser",
+ }),
+ }));
+ expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
+ });
+
+ it("normalizes stored GitHub locators before evaluating mutation policy", async () => {
+ mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
+ mockCompanySkillService.getById.mockResolvedValue({
+ id: "skill-1",
+ key: "company/company-1/review",
+ sourceType: "github",
+ sourceLocator: "https://WWW.GitHub.com/Acme/Review.git",
+ });
+ mockCompanySkillPolicyService.evaluate.mockImplementation(async (input: { resource?: { sourceLocator?: string } }) => (
+ input.resource?.sourceLocator === "https://github.com/acme/review"
+ ? denySkillPolicy("skills.edit")
+ : {
+ allowed: true,
+ action: "skills.edit",
+ reason: "policy_default",
+ policyRevision: 1,
+ matchedRuleId: null,
+ remediation: null,
+ }
+ ));
+
+ const res = await request(await createApp({
+ type: "board",
+ userId: "board-user",
+ companyIds: ["company-1"],
+ source: "session",
+ isInstanceAdmin: false,
+ }))
+ .patch("/api/companies/company-1/skills/skill-1")
+ .send({ name: "Updated review" });
+
+ expect(res.status, JSON.stringify(res.body)).toBe(403);
+ expect(mockCompanySkillPolicyService.evaluate).toHaveBeenCalledWith(expect.objectContaining({
+ action: "skills.edit",
+ resource: expect.objectContaining({
+ sourceType: "git",
+ sourceLocator: "https://github.com/acme/review",
+ }),
+ }));
+ expect(mockCompanySkillService.updateSkill).not.toHaveBeenCalled();
+ });
+
+ it("evaluates skill version creation with the skills.create policy action", async () => {
+ mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
+ mockCompanySkillService.getById.mockResolvedValue({
+ id: "skill-1",
+ key: "company/company-1/review",
+ sourceType: "github",
+ sourceLocator: "https://github.com/acme/review",
+ });
+ mockCompanySkillPolicyService.evaluate.mockResolvedValue(denySkillPolicy("skills.create"));
+
+ const res = await request(await createApp({
+ type: "board",
+ userId: "board-user",
+ companyIds: ["company-1"],
+ source: "session",
+ isInstanceAdmin: false,
+ }))
+ .post("/api/companies/company-1/skills/skill-1/versions")
+ .send({ label: "v1" });
+
+ expect(res.status, JSON.stringify(res.body)).toBe(403);
+ expect(mockCompanySkillPolicyService.evaluate).toHaveBeenCalledWith(expect.objectContaining({
+ action: "skills.create",
+ companyId: "company-1",
+ resource: expect.objectContaining({
+ skillId: "skill-1",
+ }),
+ }));
+ expect(mockCompanySkillService.createVersion).not.toHaveBeenCalled();
+ });
+
+ it("blocks npx skills add imports when policy denies the canonical git source locator", async () => {
+ mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
+ mockCompanySkillPolicyService.evaluate.mockImplementation(async (input: { resource?: { sourceType?: string; sourceLocator?: string } }) => {
+ const resource = input.resource ?? {};
+ return resource.sourceType === "git" && resource.sourceLocator === "https://github.com/vercel-labs/agent-browser"
+ ? denySkillPolicy("skills.import")
+ : {
+ allowed: true,
+ action: "skills.import",
+ reason: "policy_default",
+ policyRevision: 1,
+ matchedRuleId: null,
+ remediation: null,
+ };
+ });
+
+ const res = await request(await createApp({
+ type: "board",
+ userId: "board-user",
+ companyIds: ["company-1"],
+ source: "session",
+ isInstanceAdmin: false,
+ }))
+ .post("/api/companies/company-1/skills/import")
+ .send({ source: "npx skills add Vercel-Labs/Agent-Browser --skill agent-browser -g" });
+
+ expect(res.status, JSON.stringify(res.body)).toBe(403);
+ expect(res.body.error).toBe("Skill action denied by company policy");
+ expect(mockCompanySkillPolicyService.evaluate).toHaveBeenCalledWith(expect.objectContaining({
+ companyId: "company-1",
+ action: "skills.import",
+ resource: expect.objectContaining({
+ sourceType: "git",
+ sourceLocator: "https://github.com/vercel-labs/agent-browser",
+ }),
+ }));
+ expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ {
+ label: "tree directory",
+ source: "https://github.com/Vercel-Labs/Agent-Browser/tree/main/skills/Upper.MD",
+ sourceLocator: "https://github.com/vercel-labs/agent-browser/tree/main/skills/Upper.MD",
+ },
+ {
+ label: "blob file",
+ source: "https://github.com/Vercel-Labs/Agent-Browser/blob/main/skills/Upper/SKILL.MD",
+ sourceLocator: "https://github.com/vercel-labs/agent-browser/blob/main/skills/Upper/SKILL.MD",
+ },
+ ])("blocks uppercase .MD GitHub $label imports when policy denies the canonical git source locator", async ({ source, sourceLocator }) => {
+ mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
+ mockCompanySkillPolicyService.evaluate.mockImplementation(async (input: { resource?: { sourceType?: string; sourceLocator?: string } }) => {
+ const resource = input.resource ?? {};
+ return resource.sourceType === "git" && resource.sourceLocator === sourceLocator
+ ? denySkillPolicy("skills.import")
+ : {
+ allowed: true,
+ action: "skills.import",
+ reason: "policy_default",
+ policyRevision: 1,
+ matchedRuleId: null,
+ remediation: null,
+ };
+ });
+
+ const res = await request(await createApp({
+ type: "board",
+ userId: "board-user",
+ companyIds: ["company-1"],
+ source: "session",
+ isInstanceAdmin: false,
+ }))
+ .post("/api/companies/company-1/skills/import")
+ .send({ source });
+
+ expect(res.status, JSON.stringify(res.body)).toBe(403);
+ expect(res.body.error).toBe("Skill action denied by company policy");
+ expect(mockCompanySkillPolicyService.evaluate).toHaveBeenCalledWith(expect.objectContaining({
+ companyId: "company-1",
+ action: "skills.import",
+ resource: expect.objectContaining({
+ sourceType: "git",
+ sourceLocator,
+ }),
+ }));
expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
});
@@ -779,6 +1130,35 @@ describe("company skill mutation permissions", () => {
expect(mockCatalogService.readCatalogSkillFile).not.toHaveBeenCalled();
});
+ it("rejects unauthenticated skill imports before parsing source details", async () => {
+ const app = await createApp({ type: "none" });
+
+ const res = await request(app)
+ .post("/api/companies/company-1/skills/import")
+ .send({ source: "https://github.com/acme/private-skill?token=secret#token=secret" });
+
+ expect(res.status, JSON.stringify(res.body)).toBe(401);
+ expect(res.body).toEqual({ error: "Authentication required" });
+ expect(JSON.stringify(res.body)).not.toContain("secret");
+ expect(mockAccessService.decide).not.toHaveBeenCalled();
+ expect(mockCompanySkillPolicyService.evaluate).not.toHaveBeenCalled();
+ expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
+ });
+
+ it("rejects unauthenticated skill edits before loading stored policy resources", async () => {
+ const app = await createApp({ type: "none" });
+
+ const res = await request(app)
+ .patch("/api/companies/company-1/skills/skill-1")
+ .send({ description: "Updated" });
+
+ expect(res.status, JSON.stringify(res.body)).toBe(401);
+ expect(res.body).toEqual({ error: "Authentication required" });
+ expect(mockCompanySkillService.getById).not.toHaveBeenCalled();
+ expect(mockCompanySkillPolicyService.evaluate).not.toHaveBeenCalled();
+ expect(mockCompanySkillService.updateSkill).not.toHaveBeenCalled();
+ });
+
it("serves catalog detail and files by catalog reference", async () => {
const app = await createApp({
type: "board",
@@ -966,7 +1346,7 @@ describe("company skill mutation permissions", () => {
});
});
- it("blocks same-company agents without skill change grants from mutating company skills", async () => {
+ it("allows same-company agents without skill change grants when no explicit policy exists", async () => {
mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
mockAgentService.getById.mockResolvedValue({
id: "55555555-5555-4555-8555-555555555555",
@@ -983,14 +1363,13 @@ describe("company skill mutation permissions", () => {
.post("/api/companies/company-1/skills/import")
.send({ source: "https://github.com/vercel-labs/agent-browser" });
- expect(res.status, JSON.stringify(res.body)).toBe(403);
- expect(res.body.error).toBe("Missing permission: skills:create or skills:suggest-changes.");
+ expect(res.status, JSON.stringify(res.body)).toBe(201);
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "skill_config:update",
resource: { type: "company", companyId: "company-1" },
}));
expect(mockAccessService.hasPermission).not.toHaveBeenCalledWith("company-1", "agent", "55555555-5555-4555-8555-555555555555", "agents:create");
- expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
+ expect(mockCompanySkillService.importFromSource).toHaveBeenCalled();
});
it("blocks agent catalog installs for other companies", async () => {
@@ -1204,7 +1583,7 @@ describe("company skill mutation permissions", () => {
);
});
- it("rejects suggest-tier skill mutations when the consent gate is not satisfied", async () => {
+ it("does not require consent for suggest-tier skill mutations under the open default", async () => {
const { forbidden } = await import("../errors.js");
mockAccessService.decide.mockResolvedValue(denySkillChangeDecision(
"deny_missing_consent",
@@ -1223,18 +1602,12 @@ describe("company skill mutation permissions", () => {
.post("/api/companies/company-1/skills")
.send({ name: "Reflection Draft", slug: "reflection-draft", markdown: "# Draft" });
- expect(res.status, JSON.stringify(res.body)).toBe(403);
- expect(res.body.error).toBe("Permission skills:suggest-changes requires accepted change consent before applying this mutation.");
- expect(mockReflectionCoachMutationGate.assertConsented).toHaveBeenCalledWith({
- companyId: "company-1",
- actorAgentId: "reflection-coach",
- actorRunId: "run-apply",
- targetKeys: ["skill-slug:reflection-draft"],
- });
- expect(mockCompanySkillService.createLocalSkill).not.toHaveBeenCalled();
+ expect(res.status, JSON.stringify(res.body)).toBe(201);
+ expect(mockReflectionCoachMutationGate.assertConsented).not.toHaveBeenCalled();
+ expect(mockCompanySkillService.createLocalSkill).toHaveBeenCalled();
});
- it("does not convert consent gate service failures into authorization denials", async () => {
+ it("does not invoke the legacy consent gate under the open default", async () => {
mockAccessService.decide.mockResolvedValue(denySkillChangeDecision(
"deny_missing_consent",
"Permission skills:suggest-changes requires accepted change consent before applying this mutation.",
@@ -1250,18 +1623,12 @@ describe("company skill mutation permissions", () => {
.post("/api/companies/company-1/skills")
.send({ name: "Reflection Draft", slug: "reflection-draft", markdown: "# Draft" });
- expect(res.status, JSON.stringify(res.body)).toBe(500);
- expect(res.body.error).toBe("Internal server error");
- expect(mockReflectionCoachMutationGate.assertConsented).toHaveBeenCalledWith({
- companyId: "company-1",
- actorAgentId: "reflection-coach",
- actorRunId: "run-apply",
- targetKeys: ["skill-slug:reflection-draft"],
- });
- expect(mockCompanySkillService.createLocalSkill).not.toHaveBeenCalled();
+ expect(res.status, JSON.stringify(res.body)).toBe(201);
+ expect(mockReflectionCoachMutationGate.assertConsented).not.toHaveBeenCalled();
+ expect(mockCompanySkillService.createLocalSkill).toHaveBeenCalled();
});
- it("allows suggest-tier skill mutations after accepted change consent", async () => {
+ it("allows suggest-tier skill mutations without a second consent decision", async () => {
mockAccessService.decide
.mockResolvedValueOnce(denySkillChangeDecision(
"deny_missing_consent",
@@ -1284,24 +1651,15 @@ describe("company skill mutation permissions", () => {
.send({ source: "https://github.com/vercel-labs/agent-browser" });
expect(res.status, JSON.stringify(res.body)).toBe(201);
- expect(mockReflectionCoachMutationGate.assertConsented).toHaveBeenCalledWith({
- companyId: "company-1",
- actorAgentId: "55555555-5555-4555-8555-555555555555",
- actorRunId: "run-1",
- targetKeys: ["skill-import:https://github.com/vercel-labs/agent-browser"],
- });
- expect(mockAccessService.decide).toHaveBeenLastCalledWith(expect.objectContaining({
- action: "skill_config:update",
- resource: { type: "company", companyId: "company-1" },
- scope: { consentedChange: true },
- }));
+ expect(mockReflectionCoachMutationGate.assertConsented).not.toHaveBeenCalled();
+ expect(mockAccessService.decide).toHaveBeenCalledTimes(1);
expect(mockCompanySkillService.importFromSource).toHaveBeenCalledWith(
"company-1",
"https://github.com/vercel-labs/agent-browser",
);
});
- it("blocks same-company agents without skill change or suggest grants", async () => {
+ it("allows same-company agents without either legacy skill grant", async () => {
mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
mockAgentService.getById.mockResolvedValue({
id: "55555555-5555-4555-8555-555555555555",
@@ -1318,16 +1676,15 @@ describe("company skill mutation permissions", () => {
.post("/api/companies/company-1/skills/import")
.send({ source: "https://github.com/vercel-labs/agent-browser" });
- expect(res.status, JSON.stringify(res.body)).toBe(403);
- expect(res.body.error).toBe("Missing permission: skills:create or skills:suggest-changes.");
+ expect(res.status, JSON.stringify(res.body)).toBe(201);
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "skill_config:update",
resource: { type: "company", companyId: "company-1" },
}));
- expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
+ expect(mockCompanySkillService.importFromSource).toHaveBeenCalled();
});
- it("does not allow explicit agents:create grants to mutate company skills", async () => {
+ it("does not require unrelated agents:create grants for open-default skill mutations", async () => {
mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
mockAgentService.getById.mockResolvedValue({
id: "agent-1",
@@ -1350,14 +1707,13 @@ describe("company skill mutation permissions", () => {
.post("/api/companies/company-1/skills/import")
.send({ source: "https://github.com/vercel-labs/agent-browser" });
- expect(res.status, JSON.stringify(res.body)).toBe(403);
- expect(res.body.error).toBe("Missing permission: skills:create or skills:suggest-changes.");
+ expect(res.status, JSON.stringify(res.body)).toBe(201);
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "skill_config:update",
resource: { type: "company", companyId: "company-1" },
}));
expect(mockAccessService.hasPermission).not.toHaveBeenCalledWith("company-1", "agent", "agent-1", "agents:create");
- expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
+ expect(mockCompanySkillService.importFromSource).toHaveBeenCalled();
});
it("routes skill test input CRUD through skills mutation permissions", async () => {
@@ -1568,6 +1924,55 @@ describe("company skill mutation permissions", () => {
}));
});
+ it.each([
+ ["create", "post", "/api/companies/company-1/skills/skill-1/test-runs"],
+ ["cancel", "post", "/api/companies/company-1/skills/skill-1/test-runs/22222222-2222-4222-8222-222222222222/cancel"],
+ ["delete", "delete", "/api/companies/company-1/skills/skill-1/test-runs/22222222-2222-4222-8222-222222222222"],
+ ] as const)("denies agents without tasks:assign permission from %s test runs", async (_operation, method, path) => {
+ mockAccessService.decide.mockImplementation(async (input: { action: string }) => {
+ if (input.action === "tasks:assign") return denyTaskAssignDecision();
+ return allowSkillChangeDecision();
+ });
+ mockCompanySkillService.getTestRunDetail.mockResolvedValue({
+ id: "22222222-2222-4222-8222-222222222222",
+ companyId: "company-1",
+ skillId: "skill-1",
+ issueId: "44444444-4444-4444-8444-444444444444",
+ agentId: "55555555-5555-4555-8555-555555555555",
+ status: "queued",
+ });
+
+ const app = await createApp({
+ type: "agent",
+ agentId: "agent-1",
+ companyId: "company-1",
+ keyScope: null,
+ runId: "run-1",
+ });
+ const response = method === "post"
+ ? await request(app)[method](path).send({
+ inputId: "11111111-1111-4111-8111-111111111111",
+ agentId: "55555555-5555-4555-8555-555555555555",
+ })
+ : await request(app)[method](path);
+
+ expect(response.status, JSON.stringify(response.body)).toBe(403);
+ expect(response.body.error).toBe("Missing permission: tasks:assign");
+ expect(mockCompanySkillPolicyService.evaluate).toHaveBeenCalledWith(expect.objectContaining({
+ action: "skills.test",
+ }));
+ expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
+ action: "tasks:assign",
+ resource: expect.objectContaining({
+ type: "issue",
+ companyId: "company-1",
+ }),
+ }));
+ expect(mockCompanySkillService.createTestRun).not.toHaveBeenCalled();
+ expect(mockCompanySkillService.cancelTestRun).not.toHaveBeenCalled();
+ expect(mockCompanySkillService.deleteTestRun).not.toHaveBeenCalled();
+ });
+
it("does not prune expired harness issues from test run reads", async () => {
mockCompanySkillService.listTestRuns.mockResolvedValueOnce([]);
mockCompanySkillService.getTestRunDetail.mockResolvedValueOnce({
diff --git a/server/src/__tests__/company-skills-service.test.ts b/server/src/__tests__/company-skills-service.test.ts
index 532abac3de..a7e68a8abc 100644
--- a/server/src/__tests__/company-skills-service.test.ts
+++ b/server/src/__tests__/company-skills-service.test.ts
@@ -25,14 +25,26 @@ describeEmbeddedPostgres("companySkillService.list", () => {
let svc!: ReturnType<typeof companySkillService>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
let oldPaperclipHome: string | undefined;
+ let oldPaperclipInstanceId: string | undefined;
let paperclipHome: string | null = null;
const cleanupDirs = new Set<string>();
+ async function createManagedSkillDir(companyId: string, prefix: string) {
+ if (!paperclipHome) throw new Error("Expected Paperclip test home");
+ const managedRoot = path.join(paperclipHome, "instances", "default", "skills", companyId);
+ await fs.mkdir(managedRoot, { recursive: true });
+ const skillDir = await fs.mkdtemp(path.join(managedRoot, prefix));
+ cleanupDirs.add(skillDir);
+ return skillDir;
+ }
+
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-company-skills-service-");
oldPaperclipHome = process.env.PAPERCLIP_HOME;
+ oldPaperclipInstanceId = process.env.PAPERCLIP_INSTANCE_ID;
paperclipHome = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-company-skills-home-"));
process.env.PAPERCLIP_HOME = paperclipHome;
+ process.env.PAPERCLIP_INSTANCE_ID = "default";
db = createDb(tempDb.connectionString);
svc = companySkillService(db);
}, 20_000);
@@ -49,6 +61,8 @@ describeEmbeddedPostgres("companySkillService.list", () => {
afterAll(async () => {
if (oldPaperclipHome === undefined) delete process.env.PAPERCLIP_HOME;
else process.env.PAPERCLIP_HOME = oldPaperclipHome;
+ if (oldPaperclipInstanceId === undefined) delete process.env.PAPERCLIP_INSTANCE_ID;
+ else process.env.PAPERCLIP_INSTANCE_ID = oldPaperclipInstanceId;
if (paperclipHome) {
await fs.rm(paperclipHome, { recursive: true, force: true });
}
@@ -344,8 +358,7 @@ describeEmbeddedPostgres("companySkillService.list", () => {
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);
+ const skillDir = await createManagedSkillDir(companyId, "idempotent-import-skill-");
await fs.writeFile(
path.join(skillDir, "SKILL.md"),
"---\nname: Idempotent Import Skill\n---\n\n# Idempotent Import Skill\n",
@@ -377,8 +390,7 @@ describeEmbeddedPostgres("companySkillService.list", () => {
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);
+ const skillDir = await createManagedSkillDir(companyId, "null-metadata-import-skill-");
await fs.writeFile(
path.join(skillDir, "SKILL.md"),
"---\nname: Null Metadata Import Skill\n---\n\n# Null Metadata Import Skill\n",
@@ -1330,8 +1342,7 @@ describeEmbeddedPostgres("companySkillService.list", () => {
it("imports sibling reference files when the source is a direct SKILL.md path", async () => {
const companyId = randomUUID();
- const skillDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-file-import-skill-"));
- cleanupDirs.add(skillDir);
+ const skillDir = await createManagedSkillDir(companyId, "file-import-skill-");
await fs.mkdir(path.join(skillDir, "references"), { recursive: true });
await fs.writeFile(
path.join(skillDir, "SKILL.md"),
@@ -1358,8 +1369,7 @@ describeEmbeddedPostgres("companySkillService.list", () => {
it("bounds direct root SKILL.md imports to known support directories", async () => {
const companyId = randomUUID();
- const repoDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-root-skill-"));
- cleanupDirs.add(repoDir);
+ const repoDir = await createManagedSkillDir(companyId, "root-skill-");
await fs.mkdir(path.join(repoDir, "references"), { recursive: true });
await fs.mkdir(path.join(repoDir, "server", "src"), { recursive: true });
await fs.writeFile(
diff --git a/server/src/__tests__/company-skills.test.ts b/server/src/__tests__/company-skills.test.ts
index 2a5c603f0b..555df881c3 100644
--- a/server/src/__tests__/company-skills.test.ts
+++ b/server/src/__tests__/company-skills.test.ts
@@ -84,6 +84,36 @@ describe("company skill import source parsing", () => {
expect(parsed.resolvedSource).toBe("https://github.com/vercel-labs/skills");
expect(parsed.originalSkillsShUrl).toBeNull();
});
+
+ it("rejects secret-bearing remote URLs without echoing the secret", () => {
+ const source = "https://github.com/acme/private-skill?token=secret#token=secret";
+
+ expect(() => parseSkillImportSourceInput(source)).toThrow(
+ "Remote skill source URLs cannot include credentials, query parameters, or fragments.",
+ );
+ try {
+ parseSkillImportSourceInput(source);
+ } catch (error) {
+ expect((error as Error).message).not.toContain("secret");
+ }
+ });
+
+ it("rejects malformed remote URLs as validation errors", () => {
+ expect(() => parseSkillImportSourceInput("https://")).toThrow(
+ "Invalid remote skill source URL.",
+ );
+ });
+
+ it("canonicalizes clean GitHub URLs before persistence", () => {
+ const parsed = parseSkillImportSourceInput(
+ "https://www.github.com/Vercel-Labs/Agent-Browser/blob/main/skills/Upper/SKILL.MD",
+ );
+
+ expect(parsed.resolvedSource).toBe(
+ "https://github.com/vercel-labs/agent-browser/blob/main/skills/Upper/SKILL.MD",
+ );
+ expect(parsed.originalSkillsShUrl).toBeNull();
+ });
});
describe("project workspace skill discovery", () => {
diff --git a/server/src/__tests__/invite-rate-limit-route.test.ts b/server/src/__tests__/invite-rate-limit-route.test.ts
index 9cfae606cd..da748bc45c 100644
--- a/server/src/__tests__/invite-rate-limit-route.test.ts
+++ b/server/src/__tests__/invite-rate-limit-route.test.ts
@@ -88,7 +88,7 @@ describe("invite-token endpoint rate limiting", () => {
error: "Too many invite requests",
details: { retryAfterSeconds: 60 },
});
- });
+ }, 15_000);
it("also rate-limits the accept sub-route", async () => {
const app = await createApp(createDbStub([], [], [], [], []));
diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts
index 771faf802a..743d5234fd 100644
--- a/server/src/__tests__/openapi-routes.test.ts
+++ b/server/src/__tests__/openapi-routes.test.ts
@@ -24,6 +24,7 @@ const apiPrefixes: Record<string, string> = {
"cloud-upstreams.ts": "/api",
"companies.ts": "/api/companies",
"company-skills.ts": "/api",
+ "company-skill-policy.ts": "/api",
"costs.ts": "/api",
"dashboard.ts": "/api",
"environments.ts": "/api",
diff --git a/server/src/__tests__/redact-sensitive.test.ts b/server/src/__tests__/redact-sensitive.test.ts
index 173fbece82..8804ddb826 100644
--- a/server/src/__tests__/redact-sensitive.test.ts
+++ b/server/src/__tests__/redact-sensitive.test.ts
@@ -39,6 +39,14 @@ describe("redactSensitive", () => {
expect(out.limit).toBe(20);
});
+ it("strips secret-bearing query and fragment values from source URLs", () => {
+ const out = redactSensitive({
+ source: "https://github.com/acme/private-skill?token=secret#token=secret",
+ }) as Record<string, unknown>;
+
+ expect(out.source).toBe("https://github.com/acme/private-skill");
+ });
+
it("recurses into nested objects and arrays", () => {
const out = redactSensitive({
user: { email: "[email protected]", password: "secret-pass" },
diff --git a/server/src/__tests__/worktree-config.test.ts b/server/src/__tests__/worktree-config.test.ts
index 3b44cc7964..351122dce5 100644
--- a/server/src/__tests__/worktree-config.test.ts
+++ b/server/src/__tests__/worktree-config.test.ts
@@ -21,6 +21,7 @@ beforeEach(() => {
delete process.env[key];
}
}
+ process.env.PAPERCLIP_INSTANCE_ID = "default";
});
afterEach(() => {
diff --git a/server/src/app.ts b/server/src/app.ts
index 16f750308d..68663296a5 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -14,6 +14,7 @@ import { applyTrustProxy, parseTrustProxyEnv } from "./middleware/trust-proxy.js
import { healthRoutes } from "./routes/health.js";
import { companyRoutes } from "./routes/companies.js";
import { companySkillRoutes } from "./routes/company-skills.js";
+import { companySkillPolicyRoutes } from "./routes/company-skill-policy.js";
import { builtInAgentRoutes } from "./routes/built-in-agents.js";
import { teamsCatalogRoutes } from "./routes/teams-catalog.js";
import { agentRoutes } from "./routes/agents.js";
@@ -235,6 +236,7 @@ export async function createApp(
api.use("/companies", companyRoutes(db, opts.storageService));
api.use(llmRoutes(db));
api.use(companySkillRoutes(db));
+ api.use(companySkillPolicyRoutes(db));
api.use(builtInAgentRoutes(db));
api.use(teamsCatalogRoutes(db));
api.use(agentRoutes(db, { pluginWorkerManager: workerManager }));
diff --git a/server/src/middleware/error-handler.ts b/server/src/middleware/error-handler.ts
index ca1b0c0e78..4656482ac8 100644
--- a/server/src/middleware/error-handler.ts
+++ b/server/src/middleware/error-handler.ts
@@ -19,6 +19,10 @@ export interface ErrorContext {
reqQuery?: unknown;
}
+function isRedactedSkillPolicyDenial(details: Record<string, unknown> | null) {
+ return details?.code === "skill_policy_denied";
+}
+
function attachErrorContext(
req: Request,
res: Response,
@@ -78,6 +82,7 @@ export function errorHandler(
const details = err.details && typeof err.details === "object" && !Array.isArray(err.details)
? err.details as Record<string, unknown>
: null;
+ const redactedSkillPolicyDenial = isRedactedSkillPolicyDenial(details);
recordResponsibleUserDenialFromHttpError(req, details);
if (err.status >= 500) {
attachErrorContext(
@@ -92,8 +97,9 @@ export function errorHandler(
res.status(err.status).json({
error: err.message,
...(typeof details?.code === "string" ? { code: details.code } : {}),
+ ...(redactedSkillPolicyDenial && typeof details?.reason === "string" ? { reason: details.reason } : {}),
...(typeof details?.remediation === "string" ? { remediation: details.remediation } : {}),
- ...(err.details ? { details: err.details } : {}),
+ ...(!redactedSkillPolicyDenial && err.details ? { details: err.details } : {}),
});
return;
}
diff --git a/server/src/middleware/redact-sensitive.ts b/server/src/middleware/redact-sensitive.ts
index 4b7247a42d..e5a5e9ade1 100644
--- a/server/src/middleware/redact-sensitive.ts
+++ b/server/src/middleware/redact-sensitive.ts
@@ -43,11 +43,40 @@ const SENSITIVE_KEYS = new Set<string>([
const MAX_DEPTH = 6;
const REDACTED = "[REDACTED]";
+const URLISH_KEYS = new Set<string>([
+ "href",
+ "locator",
+ "source",
+ "source_locator",
+ "sourcelocator",
+ "source_url",
+ "sourceurl",
+ "uri",
+ "url",
+]);
function isSensitiveKey(key: string): boolean {
return SENSITIVE_KEYS.has(key.toLowerCase());
}
+function isUrlishKey(key: string): boolean {
+ return URLISH_KEYS.has(key.toLowerCase());
+}
+
+function stripSecretBearingUrlParts(value: string): string {
+ try {
+ const url = new URL(value);
+ if (!url.username && !url.password && !url.search && !url.hash) return value;
+ url.username = "";
+ url.password = "";
+ url.search = "";
+ url.hash = "";
+ return url.toString();
+ } catch {
+ return value;
+ }
+}
+
export function redactSensitive(value: unknown, depth = 0): unknown {
if (depth > MAX_DEPTH) return undefined;
if (value === null || typeof value !== "object") return value;
@@ -61,6 +90,10 @@ export function redactSensitive(value: unknown, depth = 0): unknown {
out[key] = REDACTED;
continue;
}
+ if (typeof entry === "string" && isUrlishKey(key)) {
+ out[key] = stripSecretBearingUrlParts(entry);
+ continue;
+ }
out[key] = redactSensitive(entry, depth + 1);
}
return out;
diff --git a/server/src/routes/company-skill-policy.ts b/server/src/routes/company-skill-policy.ts
new file mode 100644
index 0000000000..9d0d85104e
--- /dev/null
+++ b/server/src/routes/company-skill-policy.ts
@@ -0,0 +1,137 @@
+import { Router, type NextFunction, type Request, type Response } from "express";
+import type { Db } from "@paperclipai/db";
+import { evaluateSkillPolicySchema, replaceSkillPolicySchema } from "@paperclipai/shared";
+import { ZodError, type ZodSchema } from "zod";
+import { forbidden, HttpError, unprocessable } from "../errors.js";
+import { accessService } from "../services/access.js";
+import { companySkillPolicyService, type SkillPolicyPrincipal } from "../services/company-skill-policy.js";
+import { assertCompanyAccess, getActorInfo } from "./authz.js";
+
+export function companySkillPolicyRoutes(db: Db) {
+ const router = Router();
+ const access = accessService(db);
+ const policies = companySkillPolicyService(db);
+
+ function validatePolicyBody(schema: ZodSchema) {
+ return (req: Request, _res: Response, next: NextFunction) => {
+ try {
+ req.body = schema.parse(req.body);
+ next();
+ } catch (error) {
+ if (error instanceof ZodError) {
+ next(unprocessable("Invalid skill policy document", {
+ code: "skill_policy_validation_failed",
+ issues: error.issues,
+ }));
+ return;
+ }
+ next(error);
+ }
+ };
+ }
+
+ function assertSkillPolicyCompanyAccess(req: Request, companyId: string) {
+ if (req.actor.type === "none") {
+ throw new HttpError(401, "Authentication required", { code: "skill_authentication_required" });
+ }
+ if (req.actor.type === "agent" && req.actor.companyId !== companyId) {
+ throw forbidden("Agent key cannot access another company", { code: "skill_company_boundary_denied" });
+ }
+ assertCompanyAccess(req, companyId);
+ }
+
+ async function assertCanAdministerPolicy(req: Request, companyId: string) {
+ assertSkillPolicyCompanyAccess(req, companyId);
+ if (req.actor.type === "board") {
+ if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return;
+ if (await access.canUser(companyId, req.actor.userId, "users:manage_permissions")) return;
+ } else if (
+ req.actor.type === "agent"
+ && req.actor.agentId
+ && await access.hasPermission(companyId, "agent", req.actor.agentId, "users:manage_permissions")
+ ) {
+ return;
+ }
+ throw forbidden("Skill policy administration authority required", {
+ code: "skill_policy_admin_required",
+ remediation: "Ask a company administrator to manage the skill policy.",
+ });
+ }
+
+ async function currentPrincipal(req: Request, companyId: string): Promise<SkillPolicyPrincipal> {
+ if (req.actor.type === "agent" && req.actor.agentId) {
+ return policies.resolveAgentPrincipal(companyId, req.actor.agentId);
+ }
+ if (req.actor.type === "board") {
+ return { type: "board", id: req.actor.userId ?? "board", role: "board" };
+ }
+ throw forbidden("Authenticated company actor required", { code: "skill_authentication_required" });
+ }
+
+ router.get("/companies/:companyId/skill-policy", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ assertSkillPolicyCompanyAccess(req, companyId);
+ res.json(await policies.get(companyId));
+ });
+
+ router.put(
+ "/companies/:companyId/skill-policy",
+ validatePolicyBody(replaceSkillPolicySchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ await assertCanAdministerPolicy(req, companyId);
+ const actor = getActorInfo(req);
+ const { expectedRevision, ...policy } = req.body;
+ res.json(await policies.replace({
+ companyId,
+ expectedRevision,
+ policy,
+ activity: {
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ },
+ }));
+ },
+ );
+
+ router.delete("/companies/:companyId/skill-policy", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ await assertCanAdministerPolicy(req, companyId);
+ const actor = getActorInfo(req);
+ res.json(await policies.reset({
+ companyId,
+ activity: {
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ },
+ }));
+ });
+
+ router.post(
+ "/companies/:companyId/skill-policy/evaluate",
+ validatePolicyBody(evaluateSkillPolicySchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ assertSkillPolicyCompanyAccess(req, companyId);
+ let principal: SkillPolicyPrincipal;
+ if (req.body.principal) {
+ await assertCanAdministerPolicy(req, companyId);
+ principal = await policies.resolveAgentPrincipal(companyId, req.body.principal.agentId);
+ } else {
+ principal = await currentPrincipal(req, companyId);
+ }
+ res.json(await policies.evaluate({
+ companyId,
+ principal,
+ action: req.body.action,
+ resource: req.body.resource,
+ }));
+ },
+ );
+
+ return router;
+}
diff --git a/server/src/routes/company-skills.ts b/server/src/routes/company-skills.ts
index b18a5aec38..7fe9e62721 100644
--- a/server/src/routes/company-skills.ts
+++ b/server/src/routes/company-skills.ts
@@ -25,23 +25,34 @@ import {
} from "@paperclipai/shared";
import { trackSkillImported } from "@paperclipai/shared/telemetry";
import { validate } from "../middleware/validate.js";
-import { accessService, agentService, companySkillService, heartbeatService, issueService, logActivity } from "../services/index.js";
+import {
+ accessService,
+ companySkillService,
+ heartbeatService,
+ issueService,
+ logActivity,
+} from "../services/index.js";
+import { isGitRepoSkillImportSource, parseSkillImportSourceInput } from "../services/company-skills.js";
import {
getCatalogSkillOrThrow,
listCatalogSkillsOrEmpty,
readCatalogSkillFile,
} from "../services/skills-catalog.js";
-import { forbidden, HttpError } from "../errors.js";
+import { forbidden, unauthorized } from "../errors.js";
import { assertAuthenticated, assertCompanyAccess, getActorInfo } from "./authz.js";
import { getTelemetryClient } from "../telemetry.js";
+import {
+ companySkillPolicyService,
+ normalizeSkillPolicySourceType,
+ type SkillPolicyPrincipal,
+} from "../services/company-skill-policy.js";
import { authorizationDeniedDetails } from "../services/authorization.js";
import {
- changeConsentGateService,
- skillChangeTargetKey,
- skillImportChangeTargetKey,
- skillSlugChangeTargetKey,
- skillsScanProjectsChangeTargetKey,
-} from "../services/change-consent-gate.js";
+ normalizeSkillPolicySourceLocator,
+ type SkillPolicyAction,
+ type SkillPolicyDecision,
+ type SkillPolicyEvaluationResource,
+} from "@paperclipai/shared";
type SkillTelemetryInput = {
key: string;
@@ -51,13 +62,32 @@ type SkillTelemetryInput = {
metadata: Record<string, unknown> | null;
};
+type SkillPolicyDenialResponse = {
+ code: "skill_policy_denied";
+ reason: SkillPolicyDecision["reason"];
+ remediation?: string;
+};
+
+type SkillTestRunAssignmentAuthorizationScope = {
+ issueId?: string | null;
+ projectId?: string | null;
+ parentIssueId?: string | null;
+ assigneeAgentId?: string | null;
+ assigneeUserId?: string | null;
+};
+
+type SkillPolicyResourceInput =
+ | SkillPolicyEvaluationResource
+ | Promise<SkillPolicyEvaluationResource>
+ | (() => SkillPolicyEvaluationResource | Promise<SkillPolicyEvaluationResource>);
+
export function companySkillRoutes(db: Db) {
const router = Router();
- const agents = agentService(db);
const access = accessService(db);
const svc = companySkillService(db);
const issues = issueService(db);
const heartbeat = heartbeatService(db);
+ const skillPolicies = companySkillPolicyService(db);
function asString(value: unknown): string | null {
if (typeof value !== "string") return null;
@@ -91,6 +121,16 @@ export function companySkillRoutes(db: Db) {
return [];
}
+ function toSkillPolicyDenialResponse(
+ decision: Pick<SkillPolicyDecision, "reason" | "remediation">,
+ ): SkillPolicyDenialResponse {
+ return {
+ code: "skill_policy_denied",
+ reason: decision.reason,
+ ...(typeof decision.remediation === "string" ? { remediation: decision.remediation } : {}),
+ };
+ }
+
function skillActor(req: Request) {
if (req.actor.type === "agent") {
return { type: "agent" as const, agentId: req.actor.agentId ?? null };
@@ -101,91 +141,135 @@ export function companySkillRoutes(db: Db) {
return { type: "system" as const };
}
- function skillMutationTargets(input: {
+ async function skillPolicyPrincipal(req: Request, companyId: string): Promise<SkillPolicyPrincipal> {
+ if (req.actor.type === "agent" && req.actor.agentId) {
+ return skillPolicies.resolveAgentPrincipal(companyId, req.actor.agentId);
+ }
+ if (req.actor.type === "board") {
+ return { type: "board", id: req.actor.userId ?? "board", role: "board" };
+ }
+ throw unauthorized("Authentication required");
+ }
+
+ async function skillPolicyResource(input: {
+ companyId: string;
skillId?: string | null;
- slug?: unknown;
- source?: unknown;
- catalogSkillId?: unknown;
- scanProjects?: boolean;
- }) {
- const targetKeys: string[] = [];
- const skillId = asString(input.skillId);
- const slug = asString(input.slug);
- const source = asString(input.source);
- const catalogSkillId = asString(input.catalogSkillId);
- if (skillId) targetKeys.push(skillChangeTargetKey(skillId));
- if (slug) targetKeys.push(skillSlugChangeTargetKey(slug));
- if (source) targetKeys.push(skillImportChangeTargetKey(source));
- if (catalogSkillId) targetKeys.push(skillImportChangeTargetKey(catalogSkillId));
- if (input.scanProjects) targetKeys.push(skillsScanProjectsChangeTargetKey());
- return targetKeys;
+ skillKey?: unknown;
+ sourceType?: string | null;
+ sourceLocator?: unknown;
+ }): Promise<SkillPolicyEvaluationResource> {
+ const stored = input.skillId ? await svc.getById(input.companyId, input.skillId) : null;
+ const sourceLocator = asString(input.sourceLocator) ?? stored?.sourceLocator ?? undefined;
+ return {
+ ...(input.skillId ? { skillId: input.skillId } : {}),
+ ...(asString(input.skillKey) || stored?.key ? { skillKey: asString(input.skillKey) ?? stored?.key } : {}),
+ ...((input.sourceType || stored?.sourceType) ? {
+ sourceType: normalizeSkillPolicySourceType(input.sourceType ?? stored?.sourceType),
+ } : {}),
+ ...(sourceLocator ? { sourceLocator: normalizeSkillPolicySourceLocator(sourceLocator) } : {}),
+ };
+ }
+
+ function skillImportPolicyResource(source: string): SkillPolicyEvaluationResource {
+ const parsed = parseSkillImportSourceInput(source);
+ const resolvedSource = parsed.resolvedSource;
+ return {
+ sourceType: normalizeSkillPolicySourceType(
+ isGitRepoSkillImportSource(resolvedSource) ? "git" : /^https?:\/\//i.test(resolvedSource) ? "external_package" : "workspace",
+ ),
+ sourceLocator: normalizeSkillPolicySourceLocator(resolvedSource),
+ };
}
- async function assertCanMutateCompanySkills(req: Request, companyId: string, targetKeys: string[] = []) {
+ async function assertCanMutateCompanySkills(
+ req: Request,
+ companyId: string,
+ action: SkillPolicyAction,
+ resource: SkillPolicyResourceInput = {},
+ ) {
+ if (req.actor.type === "none") {
+ throw unauthorized("Authentication required");
+ }
+ if (req.actor.type === "agent" && req.actor.companyId !== companyId) {
+ throw forbidden("Agent key cannot access another company", { code: "skill_company_boundary_denied" });
+ }
assertCompanyAccess(req, companyId);
- const decision = await access.decide({
+ const platformDecision = await access.decide({
actor: req.actor,
action: "skill_config:update",
resource: { type: "company", companyId },
});
- if (decision.allowed) {
- return;
- }
-
- if (decision.reason === "deny_missing_consent" && req.actor.type === "agent" && targetKeys.length > 0) {
- try {
- await changeConsentGateService(db).assertConsented({
- companyId,
- actorAgentId: req.actor.agentId,
- actorRunId: req.actor.runId ?? null,
- targetKeys,
- });
- } catch (err) {
- if (err instanceof HttpError && err.status === 403) {
- throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
- }
- throw err;
- }
-
- const consentedDecision = await access.decide({
- actor: req.actor,
- action: "skill_config:update",
- resource: { type: "company", companyId },
- scope: { consentedChange: true },
+ // Legacy missing-grant and suggest-change-consent denials are not platform
+ // invariants for skills. The company skill policy is the governance layer;
+ // authentication, company boundaries, and safety checks still fail closed.
+ if (
+ !platformDecision.allowed
+ && !["deny_no_grant", "deny_missing_consent", "deny_missing_grant"].includes(platformDecision.reason)
+ ) {
+ throw forbidden(platformDecision.explanation, {
+ code: platformDecision.reason === "deny_company_boundary"
+ ? "skill_company_boundary_denied"
+ : "skill_actor_restricted",
+ reason: "platform_invariant",
});
- if (consentedDecision.allowed) {
- return;
- }
- throw forbidden(consentedDecision.explanation, { reason: consentedDecision.reason });
}
-
- throw forbidden(decision.explanation, { reason: decision.reason });
+ const resolvedResource = typeof resource === "function" ? await resource() : await resource;
+ const policyDecision = await skillPolicies.evaluate({
+ companyId,
+ principal: await skillPolicyPrincipal(req, companyId),
+ action,
+ resource: resolvedResource,
+ });
+ if (!policyDecision.allowed) {
+ throw forbidden("Skill action denied by company policy", toSkillPolicyDenialResponse(policyDecision));
+ }
}
- async function assertCanStartSkillTestRuns(req: Request, companyId: string) {
+ async function assertCanOrchestrateSkillTestHarness(
+ req: Request,
+ companyId: string,
+ assignmentScope: SkillTestRunAssignmentAuthorizationScope = {},
+ ) {
assertCompanyAccess(req, companyId);
+ const decision = await access.decide({
+ actor: req.actor,
+ action: "tasks:assign",
+ resource: {
+ type: "issue",
+ companyId,
+ issueId: assignmentScope.issueId ?? null,
+ projectId: assignmentScope.projectId ?? null,
+ parentIssueId: assignmentScope.parentIssueId ?? null,
+ assigneeAgentId: assignmentScope.assigneeAgentId ?? null,
+ assigneeUserId: assignmentScope.assigneeUserId ?? null,
+ },
+ scope: assignmentScope,
+ });
+ if (decision.allowed) return;
+ throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
+ }
- 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");
+ async function loadSkillTestRunAssignmentScope(
+ companyId: string,
+ skillId: string,
+ runId: string,
+ ): Promise<SkillTestRunAssignmentAuthorizationScope> {
+ const run = await svc.getTestRunDetail(companyId, skillId, runId);
+ if (!run?.issueId) return {};
+ const issue = await issues.getById(run.issueId);
+ if (!issue || issue.companyId !== companyId) {
+ return {
+ issueId: run.issueId,
+ assigneeAgentId: run.agentId ?? null,
+ };
}
+ return {
+ issueId: issue.id,
+ projectId: issue.projectId ?? null,
+ parentIssueId: issue.parentId ?? null,
+ assigneeAgentId: issue.assigneeAgentId ?? run.agentId ?? null,
+ assigneeUserId: issue.assigneeUserId ?? null,
+ };
}
router.get("/skills/catalog", async (req, res) => {
@@ -294,7 +378,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
- await assertCanMutateCompanySkills(req, companyId);
+ await assertCanMutateCompanySkills(req, companyId, "skills.edit", () => skillPolicyResource({ companyId, skillId }));
const result = await svc.createTestInput(companyId, skillId, req.body, skillActor(req));
const actor = getActorInfo(req);
await logActivity(db, {
@@ -319,7 +403,7 @@ export function companySkillRoutes(db: Db) {
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);
+ await assertCanMutateCompanySkills(req, companyId, "skills.edit", () => skillPolicyResource({ companyId, skillId }));
const result = await svc.updateTestInput(companyId, skillId, inputId, req.body);
if (!result) {
res.status(404).json({ error: "Test input not found" });
@@ -345,7 +429,7 @@ export function companySkillRoutes(db: Db) {
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);
+ await assertCanMutateCompanySkills(req, companyId, "skills.edit", () => skillPolicyResource({ companyId, skillId }));
const result = await svc.deleteTestInput(companyId, skillId, inputId);
if (!result) {
res.status(404).json({ error: "Test input not found" });
@@ -377,7 +461,7 @@ export function companySkillRoutes(db: Db) {
validate(companySkillTestRunTemplateCreateSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
- await assertCanMutateCompanySkills(req, companyId);
+ await assertCanMutateCompanySkills(req, companyId, "skills.edit");
const result = await svc.createTestRunTemplate(companyId, req.body, skillActor(req));
const actor = getActorInfo(req);
await logActivity(db, {
@@ -401,7 +485,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const templateId = req.params.templateId as string;
- await assertCanMutateCompanySkills(req, companyId);
+ await assertCanMutateCompanySkills(req, companyId, "skills.edit");
const result = await svc.updateTestRunTemplate(companyId, templateId, req.body, skillActor(req));
if (!result) {
res.status(404).json({ error: "Test run template not found" });
@@ -426,7 +510,7 @@ export function companySkillRoutes(db: Db) {
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);
+ await assertCanMutateCompanySkills(req, companyId, "skills.edit");
const result = await svc.deleteTestRunTemplate(companyId, templateId);
if (!result) {
res.status(404).json({ error: "Test run template not found" });
@@ -476,7 +560,10 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
- await assertCanStartSkillTestRuns(req, companyId);
+ await assertCanMutateCompanySkills(req, companyId, "skills.test", () => skillPolicyResource({ companyId, skillId }));
+ await assertCanOrchestrateSkillTestHarness(req, companyId, {
+ assigneeAgentId: req.body.agentId,
+ });
const actor = getActorInfo(req);
const result = await svc.createTestRun(companyId, skillId, req.body, skillActor(req), {
createHarnessIssue: async (harnessIssue) => {
@@ -562,7 +649,8 @@ export function companySkillRoutes(db: Db) {
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);
+ await assertCanMutateCompanySkills(req, companyId, "skills.test", () => skillPolicyResource({ companyId, skillId }));
+ await assertCanOrchestrateSkillTestHarness(req, companyId, await loadSkillTestRunAssignmentScope(companyId, skillId, runId));
const actor = getActorInfo(req);
const result = await svc.cancelTestRun(companyId, skillId, runId, {
cancelHarnessIssue: async (issueId) => {
@@ -602,7 +690,8 @@ export function companySkillRoutes(db: Db) {
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);
+ await assertCanMutateCompanySkills(req, companyId, "skills.test", () => skillPolicyResource({ companyId, skillId }));
+ await assertCanOrchestrateSkillTestHarness(req, companyId, await loadSkillTestRunAssignmentScope(companyId, skillId, runId));
const actor = getActorInfo(req);
const result = await svc.deleteTestRun(companyId, skillId, runId, {
hideHarnessIssue: async (issueId) => {
@@ -639,7 +728,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
- await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
+ await assertCanMutateCompanySkills(req, companyId, "skills.create", () => skillPolicyResource({ companyId, skillId }));
const result = await svc.createVersion(companyId, skillId, req.body, skillActor(req));
const actor = getActorInfo(req);
await logActivity(db, {
@@ -707,10 +796,12 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
- await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({
- skillId,
- slug: req.body.slug,
- }));
+ await assertCanMutateCompanySkills(
+ req,
+ companyId,
+ "skills.create",
+ () => skillPolicyResource({ companyId, skillId }),
+ );
const result = await svc.forkSkill(companyId, skillId, req.body, skillActor(req));
const actor = getActorInfo(req);
await logActivity(db, {
@@ -840,9 +931,9 @@ export function companySkillRoutes(db: Db) {
validate(companySkillCreateSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
- await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({
- slug: req.body.slug,
- }));
+ await assertCanMutateCompanySkills(req, companyId, "skills.create", {
+ sourceType: "generated",
+ });
const result = await svc.createLocalSkill(companyId, req.body, skillActor(req));
const actor = getActorInfo(req);
@@ -871,7 +962,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
- await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
+ await assertCanMutateCompanySkills(req, companyId, "skills.edit", () => skillPolicyResource({ companyId, skillId }));
const result = await svc.updateSkill(companyId, skillId, req.body);
const actor = getActorInfo(req);
@@ -901,7 +992,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
- await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
+ await assertCanMutateCompanySkills(req, companyId, "skills.edit", () => skillPolicyResource({ companyId, skillId }));
const result = await svc.updateFile(
companyId,
skillId,
@@ -936,7 +1027,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
- await assertCanMutateCompanySkills(req, companyId);
+ await assertCanMutateCompanySkills(req, companyId, "skills.edit", () => skillPolicyResource({ companyId, skillId }));
const result = await svc.deleteFile(companyId, skillId, req.body, skillActor(req));
const actor = getActorInfo(req);
@@ -966,7 +1057,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const source = String(req.body.source ?? "");
- await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ source }));
+ await assertCanMutateCompanySkills(req, companyId, "skills.import", () => skillImportPolicyResource(source));
const result = await svc.importFromSource(companyId, source);
const actor = getActorInfo(req);
@@ -1005,10 +1096,10 @@ export function companySkillRoutes(db: Db) {
validate(companySkillInstallCatalogSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
- await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({
- catalogSkillId: req.body.catalogSkillId,
- slug: req.body.slug,
- }));
+ await assertCanMutateCompanySkills(req, companyId, "skills.install", {
+ sourceType: "catalog",
+ sourceLocator: req.body.catalogSkillId,
+ });
const result = await svc.installFromCatalog(companyId, req.body);
const actor = getActorInfo(req);
@@ -1040,7 +1131,7 @@ export function companySkillRoutes(db: Db) {
validate(companySkillProjectScanRequestSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
- await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ scanProjects: true }));
+ await assertCanMutateCompanySkills(req, companyId, "skills.import", { sourceType: "workspace" });
const result = await svc.scanProjectWorkspaces(companyId, req.body);
const actor = getActorInfo(req);
@@ -1071,7 +1162,7 @@ export function companySkillRoutes(db: Db) {
router.delete("/companies/:companyId/skills/:skillId", async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
- await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
+ await assertCanMutateCompanySkills(req, companyId, "skills.remove", () => skillPolicyResource({ companyId, skillId }));
const result = await svc.deleteSkill(companyId, skillId);
if (!result) {
res.status(404).json({ error: "Skill not found" });
@@ -1102,7 +1193,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
- await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
+ await assertCanMutateCompanySkills(req, companyId, "skills.test", () => skillPolicyResource({ companyId, skillId }));
const result = await svc.auditSkill(companyId, skillId);
if (!result) {
res.status(404).json({ error: "Skill not found" });
@@ -1138,7 +1229,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
- await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
+ await assertCanMutateCompanySkills(req, companyId, "skills.update", () => skillPolicyResource({ companyId, skillId }));
const before = await svc.getById(companyId, skillId);
const result = await svc.installUpdate(companyId, skillId, req.body);
if (!result) {
@@ -1178,7 +1269,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
- await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
+ await assertCanMutateCompanySkills(req, companyId, "skills.reset", () => skillPolicyResource({ companyId, skillId }));
const before = await svc.getById(companyId, skillId);
const result = await svc.resetSkill(companyId, skillId, req.body);
if (!result) {
diff --git a/server/src/routes/index.ts b/server/src/routes/index.ts
index 631bc498a3..5c04a1c104 100644
--- a/server/src/routes/index.ts
+++ b/server/src/routes/index.ts
@@ -1,6 +1,7 @@
export { healthRoutes } from "./health.js";
export { companyRoutes } from "./companies.js";
export { companySkillRoutes } from "./company-skills.js";
+export { companySkillPolicyRoutes } from "./company-skill-policy.js";
export { builtInAgentRoutes } from "./built-in-agents.js";
export { teamsCatalogRoutes } from "./teams-catalog.js";
export { agentRoutes } from "./agents.js";
diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts
index 49ac1734da..75988a639c 100644
--- a/server/src/routes/openapi.ts
+++ b/server/src/routes/openapi.ts
@@ -101,6 +101,8 @@ import {
companySkillTestRunListQuerySchema,
companySkillTestRunTemplateCreateSchema,
companySkillTestRunTemplateUpdateSchema,
+ evaluateSkillPolicySchema,
+ replaceSkillPolicySchema,
// Issue tree
createIssueTreeHoldSchema,
previewIssueTreeControlSchema,
@@ -3977,6 +3979,48 @@ registry.registerPath({
responses: { 200: r.ok(), 401: r.unauthorized },
});
+registry.registerPath({
+ method: "get",
+ path: "/api/companies/{companyId}/skill-policy",
+ tags: ["skills"],
+ summary: "Get the effective company skill policy",
+ request: { params: z.object({ companyId: z.string() }) },
+ responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
+});
+
+registry.registerPath({
+ method: "put",
+ path: "/api/companies/{companyId}/skill-policy",
+ tags: ["skills"],
+ summary: "Replace the company skill policy",
+ request: {
+ params: z.object({ companyId: z.string() }),
+ body: jsonBody(replaceSkillPolicySchema),
+ },
+ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 409: r.conflict },
+});
+
+registry.registerPath({
+ method: "delete",
+ path: "/api/companies/{companyId}/skill-policy",
+ tags: ["skills"],
+ summary: "Reset the company skill policy to the open default",
+ request: { params: z.object({ companyId: z.string() }) },
+ responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
+});
+
+registry.registerPath({
+ method: "post",
+ path: "/api/companies/{companyId}/skill-policy/evaluate",
+ tags: ["skills"],
+ summary: "Evaluate a company skill policy decision",
+ request: {
+ params: z.object({ companyId: z.string() }),
+ body: jsonBody(evaluateSkillPolicySchema),
+ },
+ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden },
+});
+
// ─── Execution workspaces ─────────────────────────────────────────────────────
registry.registerPath({
diff --git a/server/src/services/company-skill-policy.ts b/server/src/services/company-skill-policy.ts
new file mode 100644
index 0000000000..f4be82cc72
--- /dev/null
+++ b/server/src/services/company-skill-policy.ts
@@ -0,0 +1,292 @@
+import { and, eq, inArray } from "drizzle-orm";
+import type { Db } from "@paperclipai/db";
+import { agents, companySkillPolicies, principalPermissionGrants } from "@paperclipai/db";
+import {
+ normalizeSkillPolicySourceLocator,
+ skillPolicyDocumentSchema,
+ type EffectiveSkillPolicy,
+ type SkillPolicyAction,
+ type SkillPolicyDecision,
+ type SkillPolicyDocument,
+ type SkillPolicyEvaluationResource,
+ type SkillPolicyRule,
+ type SkillPolicySourceType,
+} from "@paperclipai/shared";
+import { conflict, forbidden, notFound } from "../errors.js";
+import { logActivity, type LogActivityInput } from "./activity-log.js";
+
+export type SkillPolicyPrincipal = {
+ type: "agent" | "board";
+ id: string;
+ role: string | null;
+};
+
+const OPEN_DEFAULT_POLICY: EffectiveSkillPolicy = {
+ schemaVersion: 1,
+ revision: 0,
+ defaultEffect: "allow",
+ rules: [],
+ materialized: false,
+};
+
+function effectivePolicyFromRow(row: typeof companySkillPolicies.$inferSelect): EffectiveSkillPolicy {
+ const document = skillPolicyDocumentSchema.parse({
+ schemaVersion: row.schemaVersion,
+ defaultEffect: row.defaultEffect,
+ rules: row.rules,
+ });
+ return { ...document, revision: row.revision, materialized: true };
+}
+
+function normalizeRole(role: string | null) {
+ return role?.trim().toLowerCase() || null;
+}
+
+function subjectMatches(rule: SkillPolicyRule, principal: SkillPolicyPrincipal) {
+ if (rule.subject.type === "all_agents") return principal.type === "agent";
+ if (rule.subject.type === "agents") {
+ return principal.type === "agent" && rule.subject.agentIds.includes(principal.id);
+ }
+ const role = normalizeRole(principal.role);
+ return Boolean(role && rule.subject.roles.some((candidate) => normalizeRole(candidate) === role));
+}
+
+function resourceMatches(rule: SkillPolicyRule, resource: SkillPolicyEvaluationResource) {
+ const selector = rule.resources;
+ if (!selector) return true;
+ if (selector.skillIds && (!resource.skillId || !selector.skillIds.includes(resource.skillId))) return false;
+ if (selector.skillKeys && (!resource.skillKey || !selector.skillKeys.includes(resource.skillKey))) return false;
+ if (selector.sourceTypes && (!resource.sourceType || !selector.sourceTypes.includes(resource.sourceType))) return false;
+ if (selector.sourceLocators) {
+ // Compare in canonical form on both sides: rules written before locator
+ // normalization existed are stored raw, and callers may pass un-normalized
+ // resources; strict equality on mixed forms would silently skip deny rules.
+ const resourceLocator = resource.sourceLocator ? normalizeSkillPolicySourceLocator(resource.sourceLocator) : null;
+ if (!resourceLocator) return false;
+ if (!selector.sourceLocators.some((locator) => normalizeSkillPolicySourceLocator(locator) === resourceLocator)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function decision(
+ allowed: boolean,
+ action: SkillPolicyAction,
+ reason: SkillPolicyDecision["reason"],
+ revision: number,
+ matchedRuleId: string | null = null,
+): SkillPolicyDecision {
+ return {
+ allowed,
+ action,
+ reason,
+ policyRevision: revision,
+ matchedRuleId,
+ remediation: allowed ? null : "Contact a company administrator to change the skill policy.",
+ };
+}
+
+export function normalizeSkillPolicySourceType(sourceType: string | null | undefined): SkillPolicySourceType {
+ switch (sourceType?.trim().toLowerCase()) {
+ case "local_path":
+ case "workspace":
+ case "project_scan":
+ return "workspace";
+ case "catalog":
+ case "bundled":
+ case "optional":
+ return "catalog";
+ case "git":
+ case "github":
+ return "git";
+ case "skills_sh":
+ case "external_package":
+ case "npm":
+ return "external_package";
+ case "generated":
+ return "generated";
+ default:
+ return "unknown";
+ }
+}
+
+export function companySkillPolicyService(db: Db) {
+ async function get(companyId: string): Promise<EffectiveSkillPolicy> {
+ const row = await db
+ .select()
+ .from(companySkillPolicies)
+ .where(eq(companySkillPolicies.companyId, companyId))
+ .then((rows) => rows[0] ?? null);
+ return row ? effectivePolicyFromRow(row) : { ...OPEN_DEFAULT_POLICY };
+ }
+
+ async function resolveAgentPrincipal(companyId: string, agentId: string): Promise<SkillPolicyPrincipal> {
+ const agent = await db
+ .select({ id: agents.id, companyId: agents.companyId, role: agents.role })
+ .from(agents)
+ .where(eq(agents.id, agentId))
+ .then((rows) => rows[0] ?? null);
+ if (!agent) throw notFound("Agent not found");
+ if (agent.companyId !== companyId) {
+ throw forbidden("Agent cannot be evaluated for another company", {
+ code: "skill_company_boundary_denied",
+ });
+ }
+ return { type: "agent", id: agent.id, role: agent.role };
+ }
+
+ async function hasLegacyBroadMutationGrant(companyId: string, principal: SkillPolicyPrincipal) {
+ const principalType = principal.type === "agent" ? "agent" : "user";
+ const row = await db
+ .select({ permissionKey: principalPermissionGrants.permissionKey })
+ .from(principalPermissionGrants)
+ .where(and(
+ eq(principalPermissionGrants.companyId, companyId),
+ eq(principalPermissionGrants.principalType, principalType),
+ eq(principalPermissionGrants.principalId, principal.id),
+ inArray(principalPermissionGrants.permissionKey, ["skills:create", "skills:suggest-changes"]),
+ ))
+ .limit(1)
+ .then((rows) => rows[0] ?? null);
+ return Boolean(row);
+ }
+
+ async function evaluate(input: {
+ companyId: string;
+ principal: SkillPolicyPrincipal;
+ action: SkillPolicyAction;
+ resource?: SkillPolicyEvaluationResource;
+ }): Promise<SkillPolicyDecision> {
+ const policy = await get(input.companyId);
+ if (!policy.materialized) {
+ return decision(true, input.action, "no_policy_default", policy.revision);
+ }
+ const resource = input.resource ?? {};
+ const matchingRule = [...policy.rules]
+ .sort((left, right) => left.priority - right.priority || left.id.localeCompare(right.id))
+ .find((rule) => rule.actions.includes(input.action)
+ && subjectMatches(rule, input.principal)
+ && resourceMatches(rule, resource));
+ if (matchingRule) {
+ return decision(
+ matchingRule.effect === "allow",
+ input.action,
+ "explicit_rule",
+ policy.revision,
+ matchingRule.id,
+ );
+ }
+ // These grants historically authorized the full company-skill mutation surface.
+ // Preserve that broad scope only as a default-deny compatibility fallback;
+ // explicit policy rules and platform invariants still take precedence.
+ if (policy.defaultEffect === "deny" && await hasLegacyBroadMutationGrant(input.companyId, input.principal)) {
+ return decision(true, input.action, "legacy_compatibility", policy.revision);
+ }
+ return decision(policy.defaultEffect === "allow", input.action, "policy_default", policy.revision);
+ }
+
+ async function replace(input: {
+ companyId: string;
+ expectedRevision: number;
+ policy: SkillPolicyDocument;
+ activity: Omit<LogActivityInput, "companyId" | "action" | "entityType" | "entityId" | "details">;
+ }) {
+ return db.transaction(async (tx) => {
+ const transactionDb = tx as unknown as Db;
+ const policy = skillPolicyDocumentSchema.parse(input.policy);
+ const existing = await tx
+ .select()
+ .from(companySkillPolicies)
+ .where(eq(companySkillPolicies.companyId, input.companyId))
+ .then((rows) => rows[0] ?? null);
+ const currentRevision = existing?.revision ?? 0;
+ if (currentRevision !== input.expectedRevision) {
+ throw conflict("Skill policy revision is stale", {
+ code: "skill_policy_revision_conflict",
+ expectedRevision: input.expectedRevision,
+ currentRevision,
+ });
+ }
+ const nextRevision = currentRevision + 1;
+ const values = {
+ schemaVersion: policy.schemaVersion,
+ revision: nextRevision,
+ defaultEffect: policy.defaultEffect,
+ rules: policy.rules,
+ updatedAt: new Date(),
+ };
+ if (existing) {
+ const updated = await tx
+ .update(companySkillPolicies)
+ .set(values)
+ .where(and(
+ eq(companySkillPolicies.companyId, input.companyId),
+ eq(companySkillPolicies.revision, currentRevision),
+ ))
+ .returning({ revision: companySkillPolicies.revision })
+ .then((rows) => rows[0] ?? null);
+ if (!updated) {
+ throw conflict("Skill policy revision is stale", {
+ code: "skill_policy_revision_conflict",
+ expectedRevision: input.expectedRevision,
+ });
+ }
+ } else {
+ const inserted = await tx
+ .insert(companySkillPolicies)
+ .values({ companyId: input.companyId, ...values })
+ .onConflictDoNothing()
+ .returning({ revision: companySkillPolicies.revision })
+ .then((rows) => rows[0] ?? null);
+ if (!inserted) {
+ throw conflict("Skill policy revision is stale", {
+ code: "skill_policy_revision_conflict",
+ expectedRevision: input.expectedRevision,
+ });
+ }
+ }
+ await logActivity(transactionDb, {
+ ...input.activity,
+ companyId: input.companyId,
+ action: "company.skill_policy_replaced",
+ entityType: "company_skill_policy",
+ entityId: input.companyId,
+ details: {
+ previousRevision: currentRevision,
+ newRevision: nextRevision,
+ defaultEffect: policy.defaultEffect,
+ ruleCount: policy.rules.length,
+ },
+ });
+ return { ...policy, revision: nextRevision, materialized: true } satisfies EffectiveSkillPolicy;
+ });
+ }
+
+ async function reset(input: {
+ companyId: string;
+ activity: Omit<LogActivityInput, "companyId" | "action" | "entityType" | "entityId" | "details">;
+ }) {
+ return db.transaction(async (tx) => {
+ const transactionDb = tx as unknown as Db;
+ const existing = await tx
+ .delete(companySkillPolicies)
+ .where(eq(companySkillPolicies.companyId, input.companyId))
+ .returning({ revision: companySkillPolicies.revision })
+ .then((rows) => rows[0] ?? null);
+ if (existing) {
+ await logActivity(transactionDb, {
+ ...input.activity,
+ companyId: input.companyId,
+ action: "company.skill_policy_reset",
+ entityType: "company_skill_policy",
+ entityId: input.companyId,
+ details: { previousRevision: existing.revision, newRevision: 0 },
+ });
+ }
+ return { ...OPEN_DEFAULT_POLICY, rules: [] };
+ });
+ }
+
+ return { get, resolveAgentPrincipal, evaluate, replace, reset };
+}
diff --git a/server/src/services/company-skills.ts b/server/src/services/company-skills.ts
index 4cdfb7da81..4ea9d88554 100644
--- a/server/src/services/company-skills.ts
+++ b/server/src/services/company-skills.ts
@@ -89,7 +89,7 @@ import type {
} from "@paperclipai/shared";
import { isUuidLike, normalizeAgentUrlKey, parseFrontmatterMarkdown } from "@paperclipai/shared";
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
-import { conflict, notFound, unprocessable } from "../errors.js";
+import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { ghFetch, gitHubApiBase, resolveRawGitHubUrl } from "./github-fetch.js";
import { agentService } from "./agents.js";
import { issueDocumentSelect, mapIssueDocumentRow } from "./documents.js";
@@ -686,10 +686,13 @@ async function resolveGitHubCommitSha(owner: string, repo: string, ref: string,
}
function parseGitHubSourceUrl(rawUrl: string) {
- const url = new URL(rawUrl);
+ const url = parseRemoteSkillImportUrl(rawUrl);
if (url.protocol !== "https:") {
throw unprocessable("GitHub source URL must use HTTPS");
}
+ if (url.username || url.password || url.search || url.hash) {
+ throw unprocessable("Remote skill source URLs cannot include credentials, query parameters, or fragments.");
+ }
const parts = url.pathname.split("/").filter(Boolean);
if (parts.length < 2) {
throw unprocessable("Invalid GitHub URL");
@@ -713,6 +716,32 @@ function parseGitHubSourceUrl(rawUrl: string) {
return { hostname: url.hostname, owner, repo, ref, basePath, filePath, explicitRef };
}
+function parseRemoteSkillImportUrl(rawUrl: string) {
+ try {
+ return new URL(rawUrl);
+ } catch {
+ throw unprocessable("Invalid remote skill source URL.");
+ }
+}
+
+function normalizeRemoteSkillImportSource(rawUrl: string) {
+ const url = parseRemoteSkillImportUrl(rawUrl);
+ if (url.username || url.password || url.search || url.hash) {
+ throw unprocessable("Remote skill source URLs cannot include credentials, query parameters, or fragments.");
+ }
+ if (isGitRepoSkillImportSource(rawUrl)) {
+ const hostname = url.hostname.toLowerCase() === "www.github.com" ? "github.com" : url.hostname.toLowerCase();
+ const segments = url.pathname.split("/").filter(Boolean);
+ if (segments.length >= 2) {
+ const owner = segments[0]!.toLowerCase();
+ const repo = segments[1]!.replace(/\.git$/i, "").toLowerCase();
+ const suffix = segments.slice(2).join("/");
+ return `https://${hostname}/${owner}/${repo}${suffix ? `/${suffix}` : ""}`;
+ }
+ }
+ return url.toString();
+}
+
async function resolveGitHubPinnedRef(parsed: ReturnType<typeof parseGitHubSourceUrl>) {
const apiBase = gitHubApiBase(parsed.hostname);
if (/^[0-9a-f]{40}$/i.test(parsed.ref.trim())) {
@@ -773,10 +802,14 @@ export function parseSkillImportSourceInput(rawInput: string): ParsedSkillImport
if (!normalizedSource) {
throw unprocessable("Skill source is required.");
}
+ const normalizedRemoteSource = /^https?:\/\//i.test(normalizedSource)
+ ? normalizeRemoteSkillImportSource(normalizedSource)
+ : null;
+ const canonicalSource = normalizedRemoteSource ?? normalizedSource;
// Key-style imports (org/repo/skill) originate from the skills.sh registry
- if (!/^https?:\/\//i.test(normalizedSource) && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalizedSource)) {
- const [owner, repo, skillSlugRaw] = normalizedSource.split("/");
+ if (!/^https?:\/\//i.test(canonicalSource) && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(canonicalSource)) {
+ const [owner, repo, skillSlugRaw] = canonicalSource.split("/");
return {
resolvedSource: `https://github.com/${owner}/${repo}`,
requestedSkillSlug: normalizeSkillSlug(skillSlugRaw),
@@ -785,9 +818,9 @@ export function parseSkillImportSourceInput(rawInput: string): ParsedSkillImport
};
}
- if (!/^https?:\/\//i.test(normalizedSource) && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalizedSource)) {
+ if (!/^https?:\/\//i.test(canonicalSource) && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(canonicalSource)) {
return {
- resolvedSource: `https://github.com/${normalizedSource}`,
+ resolvedSource: `https://github.com/${canonicalSource}`,
requestedSkillSlug,
originalSkillsShUrl: null,
warnings,
@@ -795,25 +828,44 @@ export function parseSkillImportSourceInput(rawInput: string): ParsedSkillImport
}
// Detect skills.sh URLs and resolve to GitHub: https://skills.sh/org/repo/skill → org/repo/skill key
- const skillsShMatch = normalizedSource.match(/^https?:\/\/(?:www\.)?skills\.sh\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/([A-Za-z0-9_.-]+))?(?:[?#].*)?$/i);
+ const skillsShMatch = canonicalSource.match(/^https?:\/\/(?:www\.)?skills\.sh\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/([A-Za-z0-9_.-]+))?$/i);
if (skillsShMatch) {
const [, owner, repo, skillSlugRaw] = skillsShMatch;
return {
resolvedSource: `https://github.com/${owner}/${repo}`,
requestedSkillSlug: skillSlugRaw ? normalizeSkillSlug(skillSlugRaw) : requestedSkillSlug,
- originalSkillsShUrl: normalizedSource,
+ originalSkillsShUrl: canonicalSource,
warnings,
};
}
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(canonicalSource) && !/^https:\/\//i.test(canonicalSource)) {
+ throw unprocessable("Remote skill sources must use HTTPS", {
+ code: "skill_source_validation_failed",
+ });
+ }
+
return {
- resolvedSource: normalizedSource,
+ resolvedSource: canonicalSource,
requestedSkillSlug,
originalSkillsShUrl: null,
warnings,
};
}
+export function isGitRepoSkillImportSource(source: string) {
+ try {
+ const parsed = new URL(source.trim());
+ if (parsed.protocol !== "https:") return false;
+ const hostname = parsed.hostname.toLowerCase();
+ if (hostname.endsWith(".githubusercontent.com") || hostname === "gist.github.com") return false;
+ const segments = parsed.pathname.split("/").filter(Boolean);
+ return segments.length >= 2 && !parsed.pathname.endsWith(".md");
+ } catch {
+ return false;
+ }
+}
+
function resolveBundledSkillsRoot() {
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
return [
@@ -1285,14 +1337,7 @@ async function readUrlSkillImports(
): Promise<{ skills: ImportedSkill[]; warnings: string[] }> {
const url = sourceUrl.trim();
const warnings: string[] = [];
- const looksLikeRepoUrl = (() => { try {
- const parsed = new URL(url);
- if (parsed.protocol !== "https:") return false;
- const h = parsed.hostname.toLowerCase();
- if (h.endsWith(".githubusercontent.com") || h === "gist.github.com") return false;
- const segments = parsed.pathname.split("/").filter(Boolean);
- return segments.length >= 2 && !parsed.pathname.endsWith(".md");
- } catch { return false; } })();
+ const looksLikeRepoUrl = isGitRepoSkillImportSource(url);
if (looksLikeRepoUrl) {
const parsed = parseGitHubSourceUrl(url);
const apiBase = gitHubApiBase(parsed.hostname);
@@ -2576,6 +2621,32 @@ export function companySkillService(db: Db) {
const agents = agentService(db);
const projects = projectService(db);
+ async function assertLocalImportSourceAllowed(companyId: string, source: string) {
+ const sourceRealPath = await fs.realpath(path.resolve(source)).catch(() => null);
+ if (!sourceRealPath) {
+ throw unprocessable("Local skill source is not available", {
+ code: "skill_source_validation_failed",
+ });
+ }
+ const projectRows = await projects.list(companyId);
+ const configuredRoots = [
+ resolveManagedSkillsRoot(companyId),
+ ...projectRows.flatMap((project) => project.workspaces.map((workspace) => workspace.cwd)),
+ ].filter((root): root is string => typeof root === "string" && root.trim().length > 0);
+ const approvedRoots = (await Promise.all(
+ configuredRoots.map((root) => fs.realpath(path.resolve(root)).catch(() => null)),
+ )).filter((root): root is string => Boolean(root));
+ const allowed = approvedRoots.some(
+ (root) => sourceRealPath === root || sourceRealPath.startsWith(`${root}${path.sep}`),
+ );
+ if (!allowed) {
+ throw forbidden("Local skill source is outside approved company workspace roots", {
+ code: "skill_workspace_boundary_denied",
+ remediation: "Import from a configured Paperclip workspace or the company managed-skill directory.",
+ });
+ }
+ }
+
async function ensureBundledSkills(companyId: string) {
for (const skillsRoot of resolveBundledSkillsRoot()) {
const stats = await fs.stat(skillsRoot).catch(() => null);
@@ -5099,6 +5170,9 @@ export function companySkillService(db: Db) {
await ensureSkillInventoryCurrent(companyId);
const parsed = parseSkillImportSourceInput(source);
const local = !/^https?:\/\//i.test(parsed.resolvedSource);
+ if (local) {
+ await assertLocalImportSourceAllowed(companyId, parsed.resolvedSource);
+ }
const { skills, warnings } = local
? {
skills: (await readLocalSkillImports(companyId, parsed.resolvedSource))
diff --git a/server/src/services/index.ts b/server/src/services/index.ts
index d549acff65..bce7184929 100644
--- a/server/src/services/index.ts
+++ b/server/src/services/index.ts
@@ -3,6 +3,7 @@ export { companyArtifactsService } from "./company-artifacts.js";
export { companySearchService } from "./company-search.js";
export { feedbackService } from "./feedback.js";
export { companySkillService } from "./company-skills.js";
+export { companySkillPolicyService, normalizeSkillPolicySourceType } from "./company-skill-policy.js";
export { agentService, deduplicateAgentName } from "./agents.js";
export {
builtInAgentService,
diff --git a/skills/paperclip/references/company-skills.md b/skills/paperclip/references/company-skills.md
index 8bb103ec8a..37ba590ab8 100644
--- a/skills/paperclip/references/company-skills.md
+++ b/skills/paperclip/references/company-skills.md
@@ -22,7 +22,7 @@ set.
## Permission Model
- Company skill reads: any same-company actor
-- Company skill mutations: board, a human/agent principal with an explicit `skills:create` grant, or an agent whose `canCreateSkills` permission is enabled. `canCreateSkills` defaults on for agents unless explicitly disabled.
+- Company skill mutations: open to same-company actors by default. Missing `skills:create` grants and `canCreateSkills` settings do not deny ordinary skill work; only an explicit company skill policy restriction does. Core safety and company-boundary checks always remain enforced.
- Agent skill assignment: same permission model as updating that agent
- Team installs continue to require `agents:create` because they import or create agents in addition to attaching skills.
diff --git a/ui/src/components/skill-studio/SkillPolicySurfaces.test.tsx b/ui/src/components/skill-studio/SkillPolicySurfaces.test.tsx
new file mode 100644
index 0000000000..472c2d370f
--- /dev/null
+++ b/ui/src/components/skill-studio/SkillPolicySurfaces.test.tsx
@@ -0,0 +1,124 @@
+// @vitest-environment jsdom
+
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import type { ReactNode } from "react";
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ SkillPolicyDenialNotice,
+ useSkillPolicyDenial,
+} from "./SkillPolicySurfaces";
+import { classifySkillDenial } from "@/lib/skill-policy-denial";
+import { ApiError } from "@/api/client";
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: ReturnType<typeof createRoot> | null = null;
+let container: HTMLDivElement | null = null;
+
+function act<T>(cb: () => T): T {
+ let result: T | undefined;
+ flushSync(() => {
+ result = cb();
+ });
+ return result as T;
+}
+
+function render(node: ReactNode) {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => root!.render(node));
+ return container;
+}
+
+afterEach(() => {
+ if (root) act(() => root!.unmount());
+ root = null;
+ container?.remove();
+ container = null;
+});
+
+function policyDenial() {
+ return classifySkillDenial(
+ new ApiError("denied", 403, {
+ code: "skill_policy_denied",
+ reason: "explicit_rule",
+ remediation: "A company administrator can change the skill policy to allow this.",
+ }),
+ "Installing external skills",
+ )!;
+}
+
+function platformDenial() {
+ return classifySkillDenial(
+ new ApiError("blocked", 403, {
+ code: "skill_secret_handling_blocked",
+ reason: "platform_invariant",
+ }),
+ )!;
+}
+
+describe("SkillPolicyDenialNotice", () => {
+ it("renders a State B policy denial with title and remediation", () => {
+ const el = render(<SkillPolicyDenialNotice denial={policyDenial()} />);
+ expect(el.textContent).toContain("restricted by your company policy");
+ expect(el.textContent).toContain("administrator can change the skill policy");
+ });
+
+ it("renders a State C platform-safety denial", () => {
+ const el = render(<SkillPolicyDenialNotice denial={platformDenial()} />);
+ expect(el.textContent).toContain("secret value");
+ });
+
+ it("supports dismissing the persistent banner", () => {
+ let dismissed = false;
+ const el = render(
+ <SkillPolicyDenialNotice denial={policyDenial()} onDismiss={() => { dismissed = true; }} />,
+ );
+ act(() => (el.querySelector("button") as HTMLButtonElement).click());
+ expect(dismissed).toBe(true);
+ });
+});
+
+describe("useSkillPolicyDenial", () => {
+ const policyError = new ApiError("denied", 403, {
+ code: "skill_policy_denied",
+ reason: "explicit_rule",
+ });
+ const transientError = new ApiError("conflict", 409, { message: "try again" });
+
+ function Harness({ error, label }: { error: unknown; label?: string }) {
+ const controller = useSkillPolicyDenial();
+ return (
+ <div>
+ <span data-testid="captured">
+ {controller.denial ? `banner:${controller.denial.state}` : "no-banner"}
+ </span>
+ <button data-testid="capture" onClick={() => controller.capture(error, label)}>
+ capture
+ </button>
+ <button data-testid="reset" onClick={() => controller.reset()}>
+ reset
+ </button>
+ </div>
+ );
+ }
+
+ it("captures an explicit-policy denial into the banner and clears on reset", () => {
+ const el = render(<Harness error={policyError} label="Installing external skills" />);
+ expect(el.querySelector("[data-testid=captured]")!.textContent).toBe("no-banner");
+ act(() => (el.querySelector("[data-testid=capture]") as HTMLButtonElement).click());
+ expect(el.querySelector("[data-testid=captured]")!.textContent).toBe("banner:policy");
+ act(() => (el.querySelector("[data-testid=reset]") as HTMLButtonElement).click());
+ expect(el.querySelector("[data-testid=captured]")!.textContent).toBe("no-banner");
+ });
+
+ it("ignores transient errors so they stay on the caller's toast path", () => {
+ const el = render(<Harness error={transientError} />);
+ act(() => (el.querySelector("[data-testid=capture]") as HTMLButtonElement).click());
+ expect(el.querySelector("[data-testid=captured]")!.textContent).toBe("no-banner");
+ });
+});
diff --git a/ui/src/components/skill-studio/SkillPolicySurfaces.tsx b/ui/src/components/skill-studio/SkillPolicySurfaces.tsx
new file mode 100644
index 0000000000..ee1b05a072
--- /dev/null
+++ b/ui/src/components/skill-studio/SkillPolicySurfaces.tsx
@@ -0,0 +1,91 @@
+/**
+ * @fileoverview Core Skill Studio permission surfaces (PAP-13865, Phase 3).
+ *
+ * These are the *only* permission-related visuals core renders, and they follow
+ * the north star from the approved UX spec (PAP-13863): under the open default
+ * there is no permission chrome at all. A denial banner (`SkillPolicyDenialNotice`)
+ * appears only when an explicit company policy (State B) or a platform invariant
+ * (State C) actually denied an action.
+ */
+
+import { AlertTriangle, ShieldCheck } from "lucide-react";
+import { useCallback, useState } from "react";
+
+import { InlineBanner } from "@/components/InlineBanner";
+import { Button } from "@/components/ui/button";
+import { classifySkillDenial, type SkillDenial } from "@/lib/skill-policy-denial";
+
+// ---------------------------------------------------------------------------
+// Denial banner state hook
+// ---------------------------------------------------------------------------
+
+export interface SkillPolicyDenialController {
+ /** The active denial to render as a persistent banner, or null when clear. */
+ denial: SkillDenial | null;
+ /**
+ * Classify a failed skill mutation. Explicit-policy (State B) and
+ * platform-invariant (State C) denials are captured into the banner and
+ * `true` is returned so the caller can suppress its transient error toast.
+ * Everything else returns `false` — the caller keeps the existing toast path.
+ */
+ capture: (error: unknown, actionLabel?: string) => boolean;
+ /** Clear the banner (dismiss, or on a subsequent successful action). */
+ reset: () => void;
+}
+
+/**
+ * Page-level controller for the skill-policy denial banner. A denial is a
+ * durable, actionable state (not a transient toast), so it persists until the
+ * operator dismisses it or a later action clears it. Transient errors never
+ * reach the banner — they stay on the caller's toast path.
+ */
+export function useSkillPolicyDenial(): SkillPolicyDenialController {
+ const [denial, setDenial] = useState<SkillDenial | null>(null);
+ const capture = useCallback((error: unknown, actionLabel?: string) => {
+ const classified = classifySkillDenial(error, actionLabel);
+ if (classified) {
+ setDenial(classified);
+ return true;
+ }
+ return false;
+ }, []);
+ const reset = useCallback(() => setDenial(null), []);
+ return { denial, capture, reset };
+}
+
+// ---------------------------------------------------------------------------
+// Denial notice (State B / State C)
+// ---------------------------------------------------------------------------
+
+/**
+ * Persistent, actionable denial banner. Rendered only when `classifySkillDenial`
+ * returns a denial (explicit policy or platform invariant) — never for transient
+ * errors, which stay on the toast path.
+ */
+export function SkillPolicyDenialNotice({
+ denial,
+ onDismiss,
+ className,
+}: {
+ denial: SkillDenial;
+ onDismiss?: () => void;
+ className?: string;
+}) {
+ const actions = onDismiss ? (
+ <Button variant="ghost" size="sm" onClick={onDismiss}>
+ Dismiss
+ </Button>
+ ) : undefined;
+
+ return (
+ <InlineBanner
+ tone="warning"
+ icon={denial.state === "policy" ? ShieldCheck : AlertTriangle}
+ title={denial.title}
+ actions={actions}
+ className={className}
+ >
+ <p>{denial.remediation}</p>
+ </InlineBanner>
+ );
+}
diff --git a/ui/src/lib/skill-policy-denial.test.ts b/ui/src/lib/skill-policy-denial.test.ts
new file mode 100644
index 0000000000..b0a8d805e7
--- /dev/null
+++ b/ui/src/lib/skill-policy-denial.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from "vitest";
+
+import { ApiError } from "../api/client";
+import {
+ classifySkillDenial,
+ SKILL_PLATFORM_INVARIANT_CODES,
+ SKILL_POLICY_ADMIN_CODE,
+ SKILL_POLICY_DENIAL_CODE,
+} from "./skill-policy-denial";
+
+function apiError(status: number, body: unknown): ApiError {
+ return new ApiError("Request failed", status, body);
+}
+
+describe("classifySkillDenial", () => {
+ it("returns null for non-ApiError inputs (State A / unexpected)", () => {
+ expect(classifySkillDenial(new Error("boom"))).toBeNull();
+ expect(classifySkillDenial(null)).toBeNull();
+ expect(classifySkillDenial("nope")).toBeNull();
+ });
+
+ it("returns null for transient errors so the caller keeps the retry toast (State D)", () => {
+ expect(classifySkillDenial(apiError(409, { code: "issue_run_conflict" }))).toBeNull();
+ expect(classifySkillDenial(apiError(500, { error: "Internal error" }))).toBeNull();
+ expect(classifySkillDenial(apiError(422, { error: "This skill does not support updates." }))).toBeNull();
+ });
+
+ it("classifies the redacted mutation denial payload as State B (policy)", () => {
+ const denial = classifySkillDenial(
+ apiError(403, {
+ code: SKILL_POLICY_DENIAL_CODE,
+ reason: "explicit_rule",
+ action: "skills.install",
+ remediation: "Contact a company administrator to change the skill policy.",
+ }),
+ "Installing external skills",
+ );
+ expect(denial).not.toBeNull();
+ expect(denial?.state).toBe("policy");
+ expect(denial?.title).toBe("Installing external skills is restricted by your company policy.");
+ expect(denial?.remediation).toBe("Contact a company administrator to change the skill policy.");
+ });
+
+ it("recognises a policy denial from reason alone (policy_default) and falls back to default remediation", () => {
+ const denial = classifySkillDenial(apiError(403, { reason: "policy_default" }));
+ expect(denial?.state).toBe("policy");
+ expect(denial?.title).toBe("This action is restricted by your company policy.");
+ expect(denial?.remediation).toContain("administrator can change the skill policy");
+ });
+
+ it("classifies the policy-admin requirement as State C (platform_admin)", () => {
+ const denial = classifySkillDenial(apiError(403, { code: SKILL_POLICY_ADMIN_CODE }));
+ expect(denial?.state).toBe("platform_admin");
+ expect(denial?.title).toContain("administration access");
+ });
+
+ it.each(SKILL_PLATFORM_INVARIANT_CODES)(
+ "classifies platform invariant %s as State C",
+ (code) => {
+ const denial = classifySkillDenial(apiError(403, { code, reason: "platform_invariant" }));
+ expect(denial?.state).toBe("platform");
+ expect(denial?.title.length).toBeGreaterThan(0);
+ expect(denial?.remediation.length).toBeGreaterThan(0);
+ },
+ );
+
+ it("prefers a server-supplied remediation over the default for platform invariants", () => {
+ const denial = classifySkillDenial(
+ apiError(403, {
+ code: "skill_workspace_boundary_denied",
+ reason: "platform_invariant",
+ remediation: "Import from an approved managed-skill root.",
+ }),
+ );
+ expect(denial?.remediation).toBe("Import from an approved managed-skill root.");
+ });
+
+ it("treats reason=platform_invariant without a known code as a generic safety block", () => {
+ const denial = classifySkillDenial(apiError(403, { reason: "platform_invariant" }));
+ expect(denial?.state).toBe("platform");
+ expect(denial?.title).toContain("platform safety rule");
+ });
+
+ it("never surfaces raw rule internals — only title + remediation are exposed", () => {
+ const denial = classifySkillDenial(
+ apiError(403, {
+ code: SKILL_POLICY_DENIAL_CODE,
+ reason: "explicit_rule",
+ matchedRuleId: "secret-internal-rule-id",
+ }),
+ "Editing skills",
+ );
+ // matchedRuleId must not leak into any user-facing string.
+ expect(JSON.stringify(denial)).not.toContain("secret-internal-rule-id");
+ });
+});
diff --git a/ui/src/lib/skill-policy-denial.ts b/ui/src/lib/skill-policy-denial.ts
new file mode 100644
index 0000000000..4f2f489ab2
--- /dev/null
+++ b/ui/src/lib/skill-policy-denial.ts
@@ -0,0 +1,164 @@
+/**
+ * @fileoverview Classifies a failed skill mutation into the four visual states
+ * from the Phase 3 UX spec (PAP-13865 / §9.10 Company Skill Policy Contract).
+ *
+ * The contract inverts the old model: **skill permissions are opt-in
+ * restrictions, not opt-in capabilities.** Under the open default there is no
+ * permission chrome at all — install / edit / update / test / reset / remove
+ * are just live buttons. A denial notice only appears when an explicit company
+ * policy (State B) or a non-configurable platform invariant (State C) actually
+ * denied the action. Everything else (network, 409 conflict, 5xx) is a
+ * transient error (State D) that keeps the existing toast path.
+ *
+ * This classifier is deliberately pure and framework-free so it can be unit
+ * tested exhaustively without a DOM. `classifySkillDenial()` returns `null` for
+ * State A (allowed / nothing to show) and State D (transient — let the caller
+ * toast it); the UI renders a persistent banner only for B and C.
+ */
+
+import { ApiError } from "../api/client";
+
+/** Machine-readable error codes the server attaches to skill mutation failures. */
+export const SKILL_POLICY_DENIAL_CODE = "skill_policy_denied";
+
+/**
+ * Non-configurable platform-invariant failure codes (§9.10). Policy can never
+ * loosen these — the remediation is always to fix the artifact/source/input,
+ * never to change a permission.
+ */
+export const SKILL_PLATFORM_INVARIANT_CODES = [
+ "skill_authentication_required",
+ "skill_company_boundary_denied",
+ "skill_workspace_boundary_denied",
+ "skill_source_validation_failed",
+ "skill_unsafe_content_blocked",
+ "skill_secret_handling_blocked",
+ "skill_actor_restricted",
+] as const;
+
+/**
+ * Requires board-administration authority (`users:manage_permissions`). This is
+ * a platform boundary — not something the current agent can self-serve — so we
+ * treat it as State C but with admin-oriented remediation.
+ */
+export const SKILL_POLICY_ADMIN_CODE = "skill_policy_admin_required";
+
+export type SkillDenialState = "policy" | "platform" | "platform_admin";
+
+export interface SkillDenial {
+ /** Which visual treatment applies. `policy` = State B, `platform*` = State C. */
+ state: SkillDenialState;
+ /** Machine-readable error code from the server, when present. */
+ code: string | null;
+ /** §9.10 decision `reason`, when the server surfaced the decision shape. */
+ reason: string | null;
+ /** Plain-language title for the banner. */
+ title: string;
+ /** Human remediation — never a curl/API-key snippet. */
+ remediation: string;
+}
+
+const DEFAULT_POLICY_REMEDIATION =
+ "A company administrator can change the skill policy to allow this.";
+const DEFAULT_ADMIN_REMEDIATION =
+ "This requires company administration access. Ask an administrator to make this change.";
+
+/** Human-readable titles for the platform-invariant codes (State C). */
+const PLATFORM_TITLES: Record<string, string> = {
+ skill_authentication_required: "Sign in to manage skills.",
+ skill_company_boundary_denied: "This skill belongs to another company.",
+ skill_workspace_boundary_denied: "This skill source is outside an allowed workspace.",
+ skill_source_validation_failed: "This skill source failed validation.",
+ skill_unsafe_content_blocked: "This skill contains unsafe content.",
+ skill_secret_handling_blocked: "This skill exposes a secret value.",
+ skill_actor_restricted: "This action isn't available for the current actor.",
+};
+
+/** Default remediation copy per platform-invariant code — framed as a fix, never a grant. */
+const PLATFORM_REMEDIATIONS: Record<string, string> = {
+ skill_authentication_required: "Sign in and try again.",
+ skill_company_boundary_denied: "Open the skill from the company that owns it.",
+ skill_workspace_boundary_denied:
+ "Import from a configured Paperclip workspace or the company managed-skill directory.",
+ skill_source_validation_failed: "Fix the flagged source and retry.",
+ skill_unsafe_content_blocked:
+ "Remove the fetch-and-execute or unsafe pattern before saving.",
+ skill_secret_handling_blocked: "Remove the secret value before saving.",
+ skill_actor_restricted: "Retry from an account with access to this action.",
+};
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
+}
+
+function asString(value: unknown): string | null {
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
+}
+
+/**
+ * Turn a caller-supplied error into a denial descriptor, or `null` when there
+ * is nothing to render as a persistent notice (State A allowed / State D
+ * transient). The `actionLabel` (e.g. "Installing external skills") lets the
+ * caller phrase State B's title around the specific action.
+ */
+export function classifySkillDenial(
+ error: unknown,
+ actionLabel?: string,
+): SkillDenial | null {
+ if (!(error instanceof ApiError)) return null;
+
+ const body = asRecord(error.body);
+ const code = asString(body?.code);
+ const reason = asString(body?.reason);
+ const remediation = asString(body?.remediation);
+
+ // State B — explicit company-policy denial. Resolvable by an administrator.
+ const isPolicyDenial =
+ code === SKILL_POLICY_DENIAL_CODE
+ || reason === "explicit_rule"
+ || reason === "policy_default";
+ if (isPolicyDenial) {
+ const title = actionLabel
+ ? `${actionLabel} is restricted by your company policy.`
+ : "This action is restricted by your company policy.";
+ return {
+ state: "policy",
+ code,
+ reason,
+ title,
+ remediation: remediation ?? DEFAULT_POLICY_REMEDIATION,
+ };
+ }
+
+ // State C — policy administration boundary (needs users:manage_permissions).
+ if (code === SKILL_POLICY_ADMIN_CODE) {
+ return {
+ state: "platform_admin",
+ code,
+ reason,
+ title: "This change needs administration access.",
+ remediation: remediation ?? DEFAULT_ADMIN_REMEDIATION,
+ };
+ }
+
+ // State C — non-configurable platform-safety invariant. Never waivable.
+ const isPlatformInvariant =
+ (code !== null && (SKILL_PLATFORM_INVARIANT_CODES as readonly string[]).includes(code))
+ || reason === "platform_invariant";
+ if (isPlatformInvariant) {
+ return {
+ state: "platform",
+ code,
+ reason,
+ title: (code && PLATFORM_TITLES[code]) ?? "This action is blocked by a platform safety rule.",
+ remediation:
+ remediation
+ ?? (code && PLATFORM_REMEDIATIONS[code])
+ ?? "Fix the flagged issue and try again.",
+ };
+ }
+
+ // State D — transient (network / 409 conflict / 5xx / uncoded 4xx). Let the
+ // caller keep the existing retry toast; do not render a policy banner.
+ return null;
+}
diff --git a/ui/src/pages/CompanySkills.tsx b/ui/src/pages/CompanySkills.tsx
index fbe873a8b0..ef65f25a37 100644
--- a/ui/src/pages/CompanySkills.tsx
+++ b/ui/src/pages/CompanySkills.tsx
@@ -36,6 +36,10 @@ import { Identity } from "../components/Identity";
import { AgentIcon } from "../components/AgentIconPicker";
import { AgentMultiSelect } from "../components/AgentMultiSelect";
import { useAdapterCapabilities } from "../adapters/use-adapter-capabilities";
+import {
+ SkillPolicyDenialNotice,
+ useSkillPolicyDenial,
+} from "@/components/skill-studio/SkillPolicySurfaces";
import {
Dialog,
DialogContent,
@@ -3491,6 +3495,19 @@ export function CompanySkills() {
const { setBreadcrumbs } = useBreadcrumbs();
const { pushToast } = useToastActions();
const adapterCaps = useAdapterCapabilities();
+ const policyDenial = useSkillPolicyDenial();
+ // Route a failed skill mutation to the persistent policy banner when it is an
+ // explicit-policy (State B) or platform-safety (State C) denial; otherwise keep
+ // the existing transient error toast. This is the core "actionable denial only
+ // for real restrictions" behavior from §9.10 (PAP-13865).
+ const reportSkillError = (error: unknown, title: string, fallbackBody: string, actionLabel?: string) => {
+ if (policyDenial.capture(error, actionLabel)) return;
+ pushToast({
+ tone: "error",
+ title,
+ body: error instanceof Error && error.message ? error.message : fallbackBody,
+ });
+ };
const [skillFilter, setSkillFilter] = useState("");
const [source, setSource] = useState("");
const [emptySourceHelpOpen, setEmptySourceHelpOpen] = useState(false);
@@ -3782,11 +3799,7 @@ export function CompanySkills() {
setSource("");
},
onError: (error) => {
- pushToast({
- tone: "error",
- title: "Skill import failed",
- body: error instanceof Error ? error.message : "Failed to import skill source.",
- });
+ reportSkillError(error, "Skill import failed", "Failed to import skill source.", "Importing skills");
},
});
@@ -3821,11 +3834,7 @@ export function CompanySkills() {
},
onError: (error) => {
setScanStatusMessage(null);
- pushToast({
- tone: "error",
- title: "Project skill scan failed",
- body: error instanceof Error ? error.message : "Failed to scan project workspaces.",
- });
+ reportSkillError(error, "Project skill scan failed", "Failed to scan project workspaces.", "Scanning projects for skills");
},
});
@@ -3845,11 +3854,7 @@ export function CompanySkills() {
onError: (error) => {
const message = error instanceof Error ? error.message : "Failed to create skill.";
setCreateError(message);
- pushToast({
- tone: "error",
- title: "Skill creation failed",
- body: message,
- });
+ reportSkillError(error, "Skill creation failed", "Failed to create skill.", "Creating a skill");
},
});
@@ -3950,11 +3955,7 @@ export function CompanySkills() {
});
},
onError: (error) => {
- pushToast({
- tone: "error",
- title: "Update failed",
- body: error instanceof Error ? error.message : "Failed to install skill update.",
- });
+ reportSkillError(error, "Update failed", "Failed to install skill update.", "Updating this skill");
},
});
@@ -4090,6 +4091,9 @@ export function CompanySkills() {
onError: (error) => {
const message = error instanceof Error ? error.message : "Failed to install catalog skill.";
setInstallDialogState((current) => ({ ...current, error: message }));
+ // Also surface explicit-policy / platform denials in the persistent banner
+ // so the reason stays visible after the dialog closes.
+ policyDenial.capture(error, "Installing this skill");
},
});
@@ -4212,11 +4216,7 @@ export function CompanySkills() {
});
},
onError: (error) => {
- pushToast({
- tone: "error",
- title: "Remove failed",
- body: error instanceof Error ? error.message : "Failed to remove skill.",
- });
+ reportSkillError(error, "Remove failed", "Failed to remove skill.", "Removing this skill");
},
});
@@ -4266,6 +4266,11 @@ export function CompanySkills() {
return (
<>
+ {policyDenial.denial ? (
+ <div className="px-4 pt-4">
+ <SkillPolicyDenialNotice denial={policyDenial.denial} onDismiss={policyDenial.reset} />
+ </div>
+ ) : null}
<Dialog open={deleteOpen} onOpenChange={closeDeleteDialog}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
diff --git a/ui/src/pages/SkillStudio.tsx b/ui/src/pages/SkillStudio.tsx
index 345889bba6..c77f5d72c4 100644
--- a/ui/src/pages/SkillStudio.tsx
+++ b/ui/src/pages/SkillStudio.tsx
@@ -48,6 +48,7 @@ import {
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { useCompany } from "../context/CompanyContext";
import { useOptionalToastActions } from "../context/ToastContext";
+import { classifySkillDenial } from "@/lib/skill-policy-denial";
import { agentsApi } from "@/api/agents";
import { companySkillsApi } from "@/api/companySkills";
import { issuesApi } from "@/api/issues";
@@ -187,6 +188,16 @@ function useMutationErrorToast() {
const toast = useOptionalToastActions();
return useCallback(
(title: string) => (error: unknown) => {
+ // Under the open default there is no permission chrome. When an action is
+ // actually denied — by an explicit company policy (State B) or a platform
+ // safety invariant (State C) — show the actionable denial title/remediation
+ // instead of a generic "try again" error (§9.10, PAP-13865). Transient
+ // failures keep the plain error toast.
+ const denial = classifySkillDenial(error);
+ if (denial) {
+ toast?.pushToast({ tone: "warn", title: denial.title, body: denial.remediation });
+ return;
+ }
const body =
error instanceof Error && error.message ? error.message : "Please try again.";
toast?.pushToast({ tone: "error", title, body });
diff --git a/ui/storybook/stories/skill-policy-surfaces.stories.tsx b/ui/storybook/stories/skill-policy-surfaces.stories.tsx
new file mode 100644
index 0000000000..1b3356d2c1
--- /dev/null
+++ b/ui/storybook/stories/skill-policy-surfaces.stories.tsx
@@ -0,0 +1,73 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+
+import { ApiError } from "@/api/client";
+import { SkillPolicyDenialNotice } from "@/components/skill-studio/SkillPolicySurfaces";
+import { classifySkillDenial } from "@/lib/skill-policy-denial";
+
+function policyDenial() {
+ return classifySkillDenial(
+ new ApiError("denied", 403, {
+ code: "skill_policy_denied",
+ reason: "explicit_rule",
+ remediation: "A company administrator can change the skill policy to allow this.",
+ }),
+ "Installing external skills",
+ )!;
+}
+
+function platformDenial() {
+ return classifySkillDenial(
+ new ApiError("blocked", 403, {
+ code: "skill_unsafe_content_blocked",
+ reason: "platform_invariant",
+ }),
+ )!;
+}
+
+function Frame({ label, width, children }: { label: string; width: number; children: React.ReactNode }) {
+ return (
+ <div className="space-y-2 p-6" style={{ maxWidth: `${width}px` }}>
+ <div className="text-xs uppercase tracking-wide text-muted-foreground">{label}</div>
+ {children}
+ </div>
+ );
+}
+
+const meta = {
+ title: "Product/Skills/Policy surfaces",
+ component: SkillPolicyDenialNotice,
+ args: { denial: policyDenial() },
+ parameters: {
+ docs: {
+ description: {
+ component:
+ "Core Skill Studio permission surfaces. No permission chrome under the open default; an actionable denial banner appears only for explicit policy or platform-safety failures.",
+ },
+ },
+ },
+} satisfies Meta<typeof SkillPolicyDenialNotice>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const Desktop: Story = {
+ render: () => (
+ <Frame label="Skill policy surfaces — desktop" width={720}>
+ <div className="space-y-6">
+ <SkillPolicyDenialNotice denial={policyDenial()} onDismiss={() => {}} />
+ <SkillPolicyDenialNotice denial={platformDenial()} onDismiss={() => {}} />
+ </div>
+ </Frame>
+ ),
+};
+
+export const Narrow: Story = {
+ render: () => (
+ <Frame label="Skill policy surfaces — narrow" width={360}>
+ <div className="space-y-6">
+ <SkillPolicyDenialNotice denial={policyDenial()} onDismiss={() => {}} />
+ <SkillPolicyDenialNotice denial={platformDenial()} onDismiss={() => {}} />
+ </div>
+ </Frame>
+ ),
+};