feat(skills): require explicit merge modes (#10978)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents can select company skills and synchronize them to adapter
runtimes
> - The skill sync API replaced the complete selection without an
explicit destructive choice
> - Company package import also replaced conflicting skills by default
> - These defaults could remove operator edits during setup and import
reruns
> - This pull request adds explicit assignment merge modes and safe
package conflict handling
> - The benefit is that reruns preserve operator work unless the caller
explicitly requests replacement

## Linked Issues or Issue Description

**What existing behavior does this improve?**

This change improves agent skill synchronization and company package
import.

**Subsystem affected**

This is a cross-cutting change across the shared contracts, server, CLI,
and UI.

**Current behavior**

Agent skill synchronization replaces the full desired skill set from a
modeless request. Package import replaces a conflicting skill when the
caller does not select a conflict mode.

**Proposed behavior**

Agent skill synchronization requires `add`, `remove`, or `replace`.
Package import skips conflicts by default. Each imported skill reports
whether it was created, renamed, replaced, or skipped.

**Reason and benefit**

Setup and import reruns must preserve operator edits by default.
Explicit destructive modes make data loss less likely and make each
outcome inspectable.

**Breaking changes**

Callers of the agent skill sync API must now send `mode`. Callers that
need the former behavior must send `replace`. Package import now uses
`skip` when `onConflict` is absent.

## What Changed

- Added required `add`, `remove`, and `replace` modes to the shared
agent skill sync contract.
- Added actionable `422` validation for missing or invalid modes.
- Updated first-party UI and CLI callers with explicit modes.
- Changed package skill conflict handling to use `skip` by default.
- Kept plugin-owned and built-in stock skill imports on explicit
`replace`.
- Added created, renamed, replaced, and skipped results to company
imports.
- Added regression coverage for merge modes and package conflict
outcomes.

## Verification

- `pnpm check:token-gates`
- `pnpm -r typecheck`
- `pnpm build`
- `pnpm test:run:serialized` (128 suites passed)
- `pnpm --filter @paperclipai/skills-catalog test` (20 tests passed)
- Focused agent skill route, company skill service, portability, CLI,
and UI tests passed.
- GitHub CI passed build, typecheck, canary, all general and serialized
test shards, all browser shards, policy, security, and final
verification on commit `2cfbb3e4c5`.
- Greptile reviewed the latest commit at 5/5 with zero unresolved
threads.

## Risks

- This change intentionally rejects modeless agent skill sync requests.
- The safe package default can leave an existing skill unchanged where
the old default overwrote it.
- All first-party callers now select a mode. Regression tests cover each
outcome.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI `gpt-5.6-sol` through Codex. The runtime used agentic
reasoning, tool use, code execution, and repository editing. The runtime
did not expose the context window size.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-08-07 00:42:08 -05:00
1 parent f6c6452b25
commit 5da382fd59
31 files changed
+459 -75

No files matched your search

@@ -488,7 +488,7 @@ describe.sequential("agent skill routes", () => {
await createApp(),
(baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({ desiredSkills: ["paperclip"] }),
.send({ desiredSkills: ["paperclip"], mode: "replace" }),
);
expect(syncRes.status, JSON.stringify(syncRes.body)).toBe(200);
const syncCall = mockSecretService.resolveAdapterConfigForRuntime.mock.calls.at(-1);
@@ -588,7 +588,7 @@ describe.sequential("agent skill routes", () => {
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({ desiredSkills: ["paperclip"] }));
.send({ desiredSkills: ["paperclip"], mode: "replace" }));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockAgentService.update).toHaveBeenCalledWith(
@@ -615,12 +615,102 @@ describe.sequential("agent skill routes", () => {
);
});
it("requires an explicit actionable merge mode for skill sync", async () => {
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({ desiredSkills: ["paperclip"] }));
expect(res.status, JSON.stringify(res.body)).toBe(422);
expect(res.body.error).toContain('"add", "remove", or "replace"');
expect(res.body.error).toContain('"replace" only to overwrite');
expect(mockAgentService.update).not.toHaveBeenCalled();
});
it("adds only named desired skills while preserving existing assignments", async () => {
mockAgentService.getById.mockResolvedValue({
...makeAgent("claude_local"),
adapterConfig: {
paperclipSkillSync: { desiredSkills: ["company-1/keep"] },
},
});
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({ desiredSkills: ["paperclip"], mode: "add" }));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockAgentService.update).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
adapterConfig: expect.objectContaining({
paperclipSkillSync: {
desiredSkills: ["company-1/keep", "paperclipai/paperclip/paperclip"],
},
}),
}),
expect.any(Object),
);
});
it("removes only named desired skills while preserving other assignments", async () => {
mockAgentService.getById.mockResolvedValue({
...makeAgent("claude_local"),
adapterConfig: {
paperclipSkillSync: {
desiredSkills: ["company-1/keep", "paperclipai/paperclip/paperclip"],
},
},
});
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({ desiredSkills: ["paperclip"], mode: "remove" }));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockAgentService.update).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
adapterConfig: expect.objectContaining({
paperclipSkillSync: { desiredSkills: ["company-1/keep"] },
}),
}),
expect.any(Object),
);
});
it("replaces the complete desired skill set only when explicitly requested", async () => {
mockAgentService.getById.mockResolvedValue({
...makeAgent("claude_local"),
adapterConfig: {
paperclipSkillSync: { desiredSkills: ["company-1/keep"] },
},
});
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({ desiredSkills: ["paperclip"], mode: "replace" }));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockAgentService.update).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
adapterConfig: expect.objectContaining({
paperclipSkillSync: {
desiredSkills: ["paperclipai/paperclip/paperclip"],
},
}),
}),
expect.any(Object),
);
});
it("rejects version pins while beta skills are disabled", async () => {
mockAgentService.getById.mockResolvedValue(makeAgent("claude_local"));
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({
mode: "replace",
desiredSkills: [{
key: "paperclipai/paperclip/paperclip",
versionId: "22222222-2222-4222-8222-222222222222",
@@ -640,6 +730,7 @@ describe.sequential("agent skill routes", () => {
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({
mode: "replace",
desiredSkills: [{ key: "paperclipai/paperclip/paperclip", versionId }],
}));
@@ -687,7 +778,7 @@ describe.sequential("agent skill routes", () => {
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({ desiredSkills: ["paperclip", "stale/removed/skill"] }));
.send({ desiredSkills: ["paperclip", "stale/removed/skill"], mode: "replace" }));
expect(res.status, JSON.stringify(res.body)).toBe(200);
// Stale key preserved in the persisted config alongside the resolved skill.
@@ -741,7 +832,7 @@ describe.sequential("agent skill routes", () => {
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({ desiredSkills: ["paperclipai/paperclip/paperclip"] }));
.send({ desiredSkills: ["paperclipai/paperclip/paperclip"], mode: "replace" }));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockAdapter.syncSkills).toHaveBeenCalled();
@@ -796,7 +887,7 @@ describe.sequential("agent skill routes", () => {
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({ desiredSkills: ["paperclipai/paperclip/paperclip"] }));
.send({ desiredSkills: ["paperclipai/paperclip/paperclip"], mode: "replace" }));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockAdapter.syncSkills).toHaveBeenCalledWith(
@@ -816,7 +907,7 @@ describe.sequential("agent skill routes", () => {
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({ desiredSkills: ["paperclip"] }));
.send({ desiredSkills: ["paperclip"], mode: "replace" }));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockAgentService.update).toHaveBeenCalledWith(
@@ -3005,6 +3005,18 @@ describe("company portability", () => {
id: "agent-created",
name: "ClaudeCoder",
});
companySkillSvc.importPackageFiles.mockResolvedValueOnce([{
skill: {
id: "skill-imported",
key: paperclipKey,
slug: "paperclip",
},
action: "renamed",
originalKey: "paperclip",
originalSlug: "paperclip",
requestedRefs: ["paperclip"],
reason: "Existing skill matched; renamed to paperclip-2.",
}]);
const exported = await portability.exportBundle("company-1", {
include: {
@@ -3017,7 +3029,7 @@ describe("company portability", () => {
agentSvc.list.mockResolvedValue([]);
await portability.importBundle({
const result = await portability.importBundle({
source: {
type: "inline",
rootPath: exported.rootPath,
@@ -3039,8 +3051,17 @@ describe("company portability", () => {
const textOnlyFiles = Object.fromEntries(Object.entries(exported.files).filter(([, v]) => typeof v === "string"));
expect(companySkillSvc.importPackageFiles).toHaveBeenCalledWith("company-imported", textOnlyFiles, {
onConflict: "replace",
onConflict: "rename",
});
expect(result.skills).toEqual([{
originalKey: "paperclip",
originalSlug: "paperclip",
key: paperclipKey,
slug: "paperclip",
id: "skill-imported",
action: "renamed",
reason: "Existing skill matched; renamed to paperclip-2.",
}]);
expect(agentSvc.create).toHaveBeenCalledWith("company-imported", expect.objectContaining({
adapterConfig: expect.objectContaining({
paperclipSkillSync: {
@@ -3301,7 +3322,7 @@ describe("company portability", () => {
"agents/cmo/AGENTS.md": expect.any(String),
}),
{
onConflict: "replace",
onConflict: "rename",
},
);
expect(companySkillSvc.importPackageFiles).toHaveBeenCalledWith(
@@ -3310,7 +3331,7 @@ describe("company portability", () => {
"agents/claudecoder/AGENTS.md": expect.any(String),
}),
{
onConflict: "replace",
onConflict: "rename",
},
);
expect(agentSvc.create).toHaveBeenCalledTimes(1);
@@ -1605,6 +1605,72 @@ describeEmbeddedPostgres("companySkillService.list", () => {
]);
});
it("defaults package conflicts to skip and reports skip, rename, and explicit replace outcomes", async () => {
const companyId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
});
const original = await svc.createLocalSkill(companyId, {
name: "Conflict Skill",
slug: "conflict-skill",
markdown: "---\nname: Conflict Skill\n---\n\n# Original\n",
});
const packageFiles = {
"skills/conflict-skill/SKILL.md": [
"---",
"name: Imported Conflict Skill",
"slug: conflict-skill",
"description: Incoming package version",
"---",
"",
"# Imported",
"",
].join("\n"),
};
const skipped = await svc.importPackageFiles(companyId, packageFiles);
expect(skipped).toEqual([
expect.objectContaining({
action: "skipped",
originalSlug: "conflict-skill",
skill: expect.objectContaining({ id: original.id, name: "Conflict Skill" }),
}),
]);
await expect(svc.getById(companyId, original.id)).resolves.toMatchObject({
name: "Conflict Skill",
markdown: expect.stringContaining("# Original"),
});
const renamed = await svc.importPackageFiles(companyId, packageFiles, { onConflict: "rename" });
expect(renamed).toEqual([
expect.objectContaining({
action: "renamed",
originalSlug: "conflict-skill",
skill: expect.objectContaining({
name: "Imported Conflict Skill",
slug: "conflict-skill-2",
}),
}),
]);
expect((await svc.list(companyId)).filter((skill) => skill.slug.startsWith("conflict-skill"))).toHaveLength(2);
const replaced = await svc.importPackageFiles(companyId, packageFiles, { onConflict: "replace" });
expect(replaced).toEqual([
expect.objectContaining({
action: "replaced",
originalSlug: "conflict-skill",
skill: expect.objectContaining({ id: original.id, name: "Imported Conflict Skill" }),
}),
]);
await expect(svc.getById(companyId, original.id)).resolves.toMatchObject({
name: "Imported Conflict Skill",
markdown: expect.stringContaining("# Imported"),
});
});
it("rejects executable external package skills before persistence", async () => {
const companyId = randomUUID();
await db.insert(companies).values({
+72 -14
View File
@@ -1,4 +1,4 @@
import { Router, type Request, type Response } from "express";
import { Router, type NextFunction, type Request, type Response } from "express";
import { generateKeyPairSync, randomUUID } from "node:crypto";
import path from "node:path";
import type { Db } from "@paperclipai/db";
@@ -18,6 +18,7 @@ import {
resetAgentSessionSchema,
testAdapterEnvironmentSchema,
type AgentDesiredSkillEntry,
type AgentSkillAssignmentMode,
type AgentSkillSnapshot,
type InstanceSchedulerHeartbeatAgent,
upsertAgentInstructionsFileSchema,
@@ -117,6 +118,35 @@ import {
touchesAgentProfileChangeConsentFields,
} from "../services/change-consent-gate.js";
const AGENT_SKILL_ASSIGNMENT_MODES = ["add", "remove", "replace"] as const;
function requireAgentSkillAssignmentMode(req: Request, _res: Response, next: NextFunction) {
if (!AGENT_SKILL_ASSIGNMENT_MODES.includes(req.body?.mode)) {
throw unprocessable(
'Skill sync requires mode: "add", "remove", or "replace". '
+ 'Use "replace" only to overwrite the complete desired skill set.',
);
}
next();
}
function mergeDesiredSkillEntries(
current: AgentDesiredSkillEntry[],
requested: AgentDesiredSkillEntry[],
mode: AgentSkillAssignmentMode,
) {
if (mode === "replace") return requested;
const requestedKeys = new Set(requested.map((entry) => entry.key));
if (mode === "remove") {
return current.filter((entry) => !requestedKeys.has(entry.key));
}
const merged = new Map(current.map((entry) => [entry.key, entry]));
for (const entry of requested) merged.set(entry.key, entry);
return Array.from(merged.values());
}
const RUN_LOG_DEFAULT_LIMIT_BYTES = 256_000;
const RUN_LOG_MAX_LIMIT_BYTES = 1024 * 1024;
@@ -1625,6 +1655,7 @@ export function agentRoutes(
adapterType: string,
adapterConfig: Record<string, unknown>,
requestedDesiredSkills: AgentDesiredSkillEntry[] | undefined,
mode: AgentSkillAssignmentMode,
options: { tolerateUnknownDesiredSkills?: boolean } = {},
) {
if (!requestedDesiredSkills) {
@@ -1647,22 +1678,44 @@ export function agentRoutes(
await companySkills.resolveRequestedSkillEntries(companyId, requestedDesiredSkills, {
tolerateUnknownReferences: options.tolerateUnknownDesiredSkills,
});
// Runtime materialization + version selection only ever consider skills that
// actually resolve to the company library; stale keys can't be materialized.
const runtimeSkillEntries = await companySkills.listRuntimeSkillEntries(companyId, {
materializeMissing: shouldMaterializeRuntimeSkillsForAdapter(adapterType),
versionSelections: skillVersionSelectionMap(resolvedRequestedSkillEntries),
});
const resolvedDesiredSkillEntries = resolvedRequestedSkillEntries.filter(
const requestedSkillEntries = [
...resolvedRequestedSkillEntries,
...unresolvedDesiredSkillKeys.map((key) => ({ key, versionId: null })),
].filter(
(entry, index, entries) => entries.findIndex((candidate) => candidate.key === entry.key) === index,
);
// Preserve stale/unresolvable keys in the persisted desired set so they stay
// visible (and explicitly removable) instead of vanishing on the next save.
const desiredSkillEntries: AgentDesiredSkillEntry[] = [
...resolvedDesiredSkillEntries,
...unresolvedDesiredSkillKeys.map((key) => ({ key, versionId: null })),
];
const currentPreference = readPaperclipSkillSyncPreference(adapterConfig);
const { resolved: resolvedCurrentSkillEntries, unresolved: unresolvedCurrentSkillKeys } =
currentPreference.desiredSkillEntries.length > 0
? await companySkills.resolveRequestedSkillEntries(
companyId,
currentPreference.desiredSkillEntries,
{ tolerateUnknownReferences: true },
)
: { resolved: [], unresolved: [] };
const currentSkillEntries = [
...resolvedCurrentSkillEntries,
...unresolvedCurrentSkillKeys.map((key) => ({ key, versionId: null })),
].filter(
(entry, index, entries) => entries.findIndex((candidate) => candidate.key === entry.key) === index,
);
const desiredSkillEntries = mergeDesiredSkillEntries(currentSkillEntries, requestedSkillEntries, mode);
const desiredSkills = desiredSkillEntries.map((entry) => entry.key);
const resolvedKeys = new Set([
...resolvedCurrentSkillEntries.map((entry) => entry.key),
...resolvedRequestedSkillEntries.map((entry) => entry.key),
]);
// Runtime materialization + version selection only ever consider final
// assignments that resolve to the company library; stale keys remain
// persisted and explicitly removable without reaching adapter runtimes.
const runtimeSkillEntries = await companySkills.listRuntimeSkillEntries(companyId, {
materializeMissing: shouldMaterializeRuntimeSkillsForAdapter(adapterType),
versionSelections: skillVersionSelectionMap(
desiredSkillEntries.filter((entry) => resolvedKeys.has(entry.key)),
),
});
return {
adapterConfig: writePaperclipSkillSyncPreference(adapterConfig, desiredSkillEntries),
@@ -1992,6 +2045,7 @@ export function agentRoutes(
router.post(
"/agents/:id/skills/sync",
requireAgentSkillAssignmentMode,
validate(agentSkillSyncSchema),
async (req, res) => {
const id = req.params.id as string;
@@ -2010,6 +2064,7 @@ export function agentRoutes(
agent.adapterType,
agent.adapterConfig as Record<string, unknown>,
requestedSkills,
req.body.mode,
// Toggling a resolvable skill must not fail just because the agent
// already carries stale desired keys (e.g. a skill removed from the
// library). Preserve those keys so they remain visible/removable.
@@ -2074,6 +2129,7 @@ export function agentRoutes(
adapterType: updated.adapterType,
desiredSkills,
desiredSkillEntries,
assignmentMode: req.body.mode,
mode: snapshot.mode,
supported: snapshot.supported,
entryCount: snapshot.entries.length,
@@ -2494,6 +2550,7 @@ export function agentRoutes(
hireInput.adapterType,
requestedAdapterConfig,
normalizeDesiredSkillSelections(Array.isArray(requestedDesiredSkills) ? requestedDesiredSkills : undefined),
"add",
);
const normalizedAdapterConfig = await normalizeMediatedAdapterConfigForPersistence({
companyId,
@@ -2689,6 +2746,7 @@ export function agentRoutes(
createInput.adapterType,
requestedAdapterConfig,
normalizeDesiredSkillSelections(Array.isArray(requestedDesiredSkills) ? requestedDesiredSkills : undefined),
"add",
);
const normalizedAdapterConfig = await normalizeMediatedAdapterConfigForPersistence({
companyId,
+1 -1
View File
@@ -1975,7 +1975,7 @@ registry.registerPath({
params: z.object({ id: z.string() }),
body: jsonBody(agentSkillSyncSchema),
},
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 404: r.notFound },
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 404: r.notFound, 422: r.unprocessable },
});
registry.registerPath({
+11 -2
View File
@@ -203,7 +203,7 @@ function assertInlineSourceComplete(source: CompanyPortabilityImport["source"])
}
function resolveSkillConflictStrategy(mode: ImportMode, collisionStrategy: CompanyPortabilityCollisionStrategy) {
if (mode === "board_full") return "replace" as const;
if (mode === "board_full") return collisionStrategy;
return collisionStrategy === "skip" ? "skip" as const : "rename" as const;
}
@@ -5329,7 +5329,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
desiredSkillRefMap.set(importedSkill.originalSlug, importedSkill.skill.key);
if (importedSkill.action === "skipped") {
warnings.push(`Skipped skill ${importedSkill.originalSlug}; existing skill ${importedSkill.skill.slug} was kept.`);
} else if (importedSkill.originalKey !== importedSkill.skill.key) {
} else if (importedSkill.action === "renamed") {
warnings.push(`Imported skill ${importedSkill.originalSlug} as ${importedSkill.skill.slug} to avoid overwriting an existing skill.`);
}
}
@@ -6148,6 +6148,15 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
action: companyAction,
},
agents: resultAgents,
skills: importedSkills.map((result) => ({
originalKey: result.originalKey,
originalSlug: result.originalSlug,
key: result.skill.key,
slug: result.skill.slug,
id: result.skill.id,
action: result.action,
reason: result.reason,
})),
projects: resultProjects,
routines: resultRoutines,
envInputs: sourceManifest.envInputs ?? [],
+31 -13
View File
@@ -257,7 +257,7 @@ type PackageSkillConflictStrategy = "replace" | "rename" | "skip";
export type ImportPackageSkillResult = {
skill: CompanySkill;
action: "created" | "updated" | "skipped";
action: "created" | "renamed" | "replaced" | "skipped";
originalKey: string;
originalSlug: string;
requestedRefs: string[];
@@ -5826,6 +5826,14 @@ export function companySkillService(db: Db) {
const importedSkills = readInlineSkillImports(companyId, normalizedFiles);
if (importedSkills.length === 0) return [];
// Conflict handling must never bypass source and reserved-key checks. In
// particular, the safe default "skip" path still validates the incoming
// package before returning the existing skill.
for (const skill of importedSkills) {
assertImportedSkillKeyAllowed(skill);
assertImportedSkillSourceAllowed(skill);
}
for (const skill of importedSkills) {
if (skill.sourceType !== "catalog") continue;
const materializedDir = await materializeCatalogSkillFiles(companyId, skill, normalizedFiles);
@@ -5834,7 +5842,7 @@ export function companySkillService(db: Db) {
}
}
const conflictStrategy = options?.onConflict ?? "replace";
const conflictStrategy = options?.onConflict ?? "skip";
const existingSkills = await listFull(companyId);
const existingByKey = new Map(existingSkills.map((skill) => [skill.key, skill]));
const existingBySlug = new Map(
@@ -5848,8 +5856,7 @@ export function companySkillService(db: Db) {
skill: ImportedSkill;
originalKey: string;
originalSlug: string;
existingBefore: CompanySkill | null;
actionHint: "created" | "updated";
actionHint: "created" | "renamed" | "replaced";
reason: string | null;
}> = [];
const out: ImportPackageSkillResult[] = [];
@@ -5863,17 +5870,29 @@ export function companySkillService(db: Db) {
const conflict = existingByIncomingKey ?? existingByIncomingSlug;
if (!conflict || conflictStrategy === "replace") {
toPersist.push(importedSkill);
const skillToPersist = conflict && conflict.key !== importedSkill.key
? {
...importedSkill,
key: conflict.key,
slug: conflict.slug,
metadata: {
...(importedSkill.metadata ?? {}),
skillKey: conflict.key,
importedFromSkillKey: originalKey,
importedFromSkillSlug: originalSlug,
},
}
: importedSkill;
toPersist.push(skillToPersist);
prepared.push({
skill: importedSkill,
skill: skillToPersist,
originalKey,
originalSlug,
existingBefore: existingByIncomingKey,
actionHint: existingByIncomingKey ? "updated" : "created",
reason: existingByIncomingKey ? "Existing skill key matched; replace strategy." : null,
actionHint: conflict ? "replaced" : "created",
reason: conflict ? "Existing skill matched; explicit replace strategy." : null,
});
usedSlugs.add(normalizedSlug);
usedKeys.add(importedSkill.key);
usedSlugs.add(normalizeSkillSlug(skillToPersist.slug) ?? skillToPersist.slug);
usedKeys.add(skillToPersist.key);
continue;
}
@@ -5907,8 +5926,7 @@ export function companySkillService(db: Db) {
skill: renamedSkill,
originalKey,
originalSlug,
existingBefore: null,
actionHint: "created",
actionHint: "renamed",
reason: `Existing skill matched; renamed to ${renamedSlug}.`,
});
usedSlugs.add(renamedSlug);