mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-01 23:43:16 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Operators attach company skills to agents from the skill library. > - Attachment first reads the agent's skill snapshot to preserve other assignments. > - That read materialized and validated repository files for the entire library, even in read-only mode. > - The response also treated resolved runtime versions as stored pins. Saving could then fail with beta pins disabled. > - This pull request makes version-cache inspection lightweight and returns the stored assignment choices. > - The benefit is a responsive attachment flow that preserves Latest and explicit pins. ## Linked Issues or Issue Description **What happened?** Adding a repository skill to an agent could stall before the save request. The prerequisite snapshot read projected or checked every file in every installed repository skill. Once it returned, an existing Latest assignment could become a version pin in the save payload. The server then rejected that save when beta skill pins were disabled. **Expected behavior** Reading assignments must not prepare all repository snapshots for execution. Adding a skill must preserve the other assignments and their Latest or pinned choices. **Steps to reproduce** 1. Install repository-backed skills with stored immutable versions and cold disk caches. 2. Assign one repository skill to a Claude agent with Latest selected. Leave beta skill pins disabled. 3. Open another skill, select Add to agent, choose the same agent, and save. 4. Observe the expensive prerequisite read and the beta-pin rejection after that read completes. **Paperclip version or commit** Reproduced from master at `ac9459bae3329395f10bc81c638a374eef152baa`. **Deployment mode** Observed in hosted staging. Reproduced with a disposable local instance, embedded PostgreSQL, and the Claude local adapter on macOS arm64 with Node 26.4.0. Related: https://github.com/paperclipai/paperclip/pull/9995 adds a separate read-only assignment endpoint for peer-agent access. This fix keeps the existing configuration-gated snapshot and its permissions. ## What Changed - Respect read-only listing for current and pinned version caches. Check directory and entrypoint safety without projecting repository contents, reading all support files, or updating cache access records. - Keep complete snapshot restoration and byte validation at run preparation. Missing caches are restored from stored data. Corrupted files are repaired there. - Return stored assignment version choices in both list and sync responses. Keep runtime version details in the snapshot entries. - Add database-backed regressions for cold and warm reads, pinned versions, execution repair, and unsafe entrypoints. Add HTTP regressions for save round trips and explicit pins. - Update developer documentation and verification recipes. ## Verification - Red: both latest and pinned read-only cache regressions failed on the original code. The original code created caches during listing. - Red: the HTTP save-roundtrip regression returned 400 with the beta-pin error. The explicit-pin regression also failed. - Green: the updated API and cache suites passed all 145 tests. The three related company-skill service suites also passed. - Real browser: attached a repository skill to a paused test agent with another repository skill already set to Latest and beta pins disabled. The success toast appeared. The skill's Agents tab retained the assignment after reload. API reads confirmed both assignments remained unpinned and no repository version caches were created. - Local synthetic fixture: six skills share a 606-file repository snapshot. A cold HTTP skill-list request completed in 241 ms. This is local evidence, not a staging latency measurement. - Real service comparison on that fixture: the baseline cold list wrote 3,648 version/cache files. A warm baseline list read 3,642 version files and wrote six access records (457 ms). The fixed warm list read and wrote zero version/cache files (61 ms). Both services returned the same 16 library entries. - `pnpm -r typecheck` passed. The final API edit also passed the server typecheck. - `pnpm build` passed. - `node scripts/check-maps.mjs` and `git diff --check` passed. - The broad `pnpm test:run` invocation reported six failures in the untouched `tool-gateway-service.test.ts` suite. An isolated rerun passed all 59 tests. The broad run was stopped after recording those failures, so it is not a green full-local result. The PR CI matrix separately passed those suites. Greptile completed on the current commit with 5/5, zero comments, and no open threads. - One CI shard was interrupted by runner shutdown, with no failed assertion in its log. A single failed-job retry passed on the same commit. The aggregate CI gate passed. All current-head PR checks are complete with no failing or pending checks. - This PR does not claim that the fix has been deployed to staging. ## Risks - Settings reads check cache locations and entrypoints. They defer full support-file validation to execution. Regression tests verify that execution still repairs corrupt bytes and restores missing versions. - The response now distinguishes stored pins from resolved runtime versions. Explicit historical pins remain intact. Company, configuration, connector, and beta-pin authorization gates keep their existing behavior. - No schema migration or dependency change. ## Model Used - OpenAI GPT-6 through Codex, with reasoning, code execution, and browser tools. The exact runtime build ID and context-window size are not exposed in this session. ## 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>
1569 lines
63 KiB
TypeScript
1569 lines
63 KiB
TypeScript
import express from "express";
|
|
import { readFile } from "node:fs/promises";
|
|
import request from "supertest";
|
|
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
const runnerTarget = vi.hoisted(() => ({ driver: "local", platform: "linux", architecture: "x64" }));
|
|
vi.mock("../services/agent-runner-selection.js", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("../services/agent-runner-selection.js")>();
|
|
return {
|
|
...actual,
|
|
resolveNewAgentRunnerForCompany: vi.fn(async (...[_db, _companyId, input]: Parameters<typeof actual.resolveNewAgentRunnerForCompany>) =>
|
|
actual.resolveNewAgentRunner({ ...input, target: runnerTarget })),
|
|
};
|
|
});
|
|
|
|
const mockAgentService = vi.hoisted(() => ({
|
|
getById: vi.fn(),
|
|
update: vi.fn(),
|
|
create: vi.fn(),
|
|
resolveByReference: vi.fn(),
|
|
}));
|
|
|
|
const mockAccessService = vi.hoisted(() => ({
|
|
canUser: vi.fn(),
|
|
decide: vi.fn(),
|
|
hasPermission: vi.fn(),
|
|
getMembership: vi.fn(),
|
|
listPrincipalGrants: vi.fn(),
|
|
ensureMembership: vi.fn(),
|
|
setPrincipalPermission: vi.fn(),
|
|
}));
|
|
|
|
const mockApprovalService = vi.hoisted(() => ({
|
|
create: vi.fn(),
|
|
}));
|
|
const mockBudgetService = vi.hoisted(() => ({}));
|
|
const mockEnvironmentService = vi.hoisted(() => ({
|
|
getById: vi.fn(),
|
|
}));
|
|
const mockHeartbeatService = vi.hoisted(() => ({}));
|
|
const mockIssueApprovalService = vi.hoisted(() => ({
|
|
linkManyForApproval: vi.fn(),
|
|
}));
|
|
const mockWorkspaceOperationService = vi.hoisted(() => ({}));
|
|
const mockAgentInstructionsService = vi.hoisted(() => ({
|
|
getBundle: vi.fn(),
|
|
readFile: vi.fn(),
|
|
updateBundle: vi.fn(),
|
|
writeFile: vi.fn(),
|
|
deleteFile: vi.fn(),
|
|
exportFiles: vi.fn(),
|
|
ensureManagedBundle: vi.fn(),
|
|
materializeManagedBundle: vi.fn(),
|
|
}));
|
|
|
|
const mockCompanySkillService = vi.hoisted(() => ({
|
|
listRuntimeSkillEntries: vi.fn(),
|
|
resolveRequestedSkillEntries: vi.fn(),
|
|
resolveRequestedSkillKeys: vi.fn(),
|
|
}));
|
|
|
|
const mockInstanceSettingsService = vi.hoisted(() => ({
|
|
get: vi.fn(),
|
|
getExperimental: vi.fn(),
|
|
}));
|
|
|
|
const mockSecretService = vi.hoisted(() => ({
|
|
resolveAdapterConfigForRuntime: vi.fn(),
|
|
normalizeAdapterConfigForPersistence: vi.fn(async (_companyId: string, config: Record<string, unknown>) => config),
|
|
syncEnvBindingsForTarget: vi.fn(),
|
|
}));
|
|
|
|
const mockLogActivity = vi.hoisted(() => vi.fn());
|
|
const mockTrackAgentCreated = vi.hoisted(() => vi.fn());
|
|
const mockGetTelemetryClient = vi.hoisted(() => vi.fn());
|
|
const mockSyncInstructionsBundleConfigFromFilePath = vi.hoisted(() => vi.fn());
|
|
|
|
const mockAdapter = vi.hoisted(() => ({
|
|
listSkills: vi.fn(),
|
|
syncSkills: vi.fn(),
|
|
}));
|
|
|
|
function expectResponseId(value: unknown): string {
|
|
expect(value).toEqual(expect.any(String));
|
|
expect(value).not.toBe("");
|
|
expect(value).not.toBe("undefined");
|
|
return String(value);
|
|
}
|
|
|
|
vi.mock("@paperclipai/shared/telemetry", () => ({
|
|
trackAgentCreated: mockTrackAgentCreated,
|
|
trackErrorHandlerCrash: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../telemetry.js", () => ({
|
|
getTelemetryClient: mockGetTelemetryClient,
|
|
}));
|
|
|
|
vi.mock("../services/index.js", () => ({
|
|
agentService: () => mockAgentService,
|
|
agentInstructionsService: () => mockAgentInstructionsService,
|
|
accessService: () => mockAccessService,
|
|
approvalService: () => mockApprovalService,
|
|
builtInAgentService: () => ({ ensureCompanyDefaultAgentGrants: vi.fn() }),
|
|
companySkillService: () => mockCompanySkillService,
|
|
budgetService: () => mockBudgetService,
|
|
environmentService: () => mockEnvironmentService,
|
|
heartbeatService: () => mockHeartbeatService,
|
|
issueApprovalService: () => mockIssueApprovalService,
|
|
issueService: () => ({}),
|
|
logActivity: mockLogActivity,
|
|
secretService: () => mockSecretService,
|
|
syncInstructionsBundleConfigFromFilePath: mockSyncInstructionsBundleConfigFromFilePath,
|
|
workspaceOperationService: () => mockWorkspaceOperationService,
|
|
}));
|
|
|
|
vi.mock("../services/secrets.js", () => ({
|
|
secretService: () => mockSecretService,
|
|
}));
|
|
|
|
vi.mock("../services/instance-settings.js", async (importOriginal) => ({
|
|
...(await importOriginal<typeof import("../services/instance-settings.js")>()),
|
|
instanceSettingsService: () => mockInstanceSettingsService,
|
|
}));
|
|
|
|
vi.mock("../adapters/index.js", () => ({
|
|
findServerAdapter: vi.fn(() => mockAdapter),
|
|
findActiveServerAdapter: vi.fn((adapterType: string) => adapterType === "paperclip_runner"
|
|
? { ...mockAdapter, supportsInstructionsBundle: true }
|
|
: mockAdapter),
|
|
listAdapterModels: vi.fn(),
|
|
detectAdapterModel: vi.fn(),
|
|
}));
|
|
|
|
function registerModuleMocks() {
|
|
vi.doMock("@paperclipai/shared/telemetry", () => ({
|
|
trackAgentCreated: mockTrackAgentCreated,
|
|
trackErrorHandlerCrash: vi.fn(),
|
|
}));
|
|
|
|
vi.doMock("../telemetry.js", () => ({
|
|
getTelemetryClient: mockGetTelemetryClient,
|
|
}));
|
|
|
|
vi.doMock("../services/index.js", () => ({
|
|
agentService: () => mockAgentService,
|
|
agentInstructionsService: () => mockAgentInstructionsService,
|
|
accessService: () => mockAccessService,
|
|
approvalService: () => mockApprovalService,
|
|
builtInAgentService: () => ({ ensureCompanyDefaultAgentGrants: vi.fn() }),
|
|
companySkillService: () => mockCompanySkillService,
|
|
budgetService: () => mockBudgetService,
|
|
heartbeatService: () => mockHeartbeatService,
|
|
issueApprovalService: () => mockIssueApprovalService,
|
|
issueService: () => ({}),
|
|
logActivity: mockLogActivity,
|
|
secretService: () => mockSecretService,
|
|
syncInstructionsBundleConfigFromFilePath: mockSyncInstructionsBundleConfigFromFilePath,
|
|
workspaceOperationService: () => mockWorkspaceOperationService,
|
|
}));
|
|
|
|
vi.doMock("../services/secrets.js", () => ({
|
|
secretService: () => mockSecretService,
|
|
}));
|
|
|
|
vi.doMock("../services/instance-settings.js", async (importOriginal) => ({
|
|
...(await importOriginal<typeof import("../services/instance-settings.js")>()),
|
|
instanceSettingsService: () => mockInstanceSettingsService,
|
|
}));
|
|
|
|
vi.doMock("../adapters/index.js", () => ({
|
|
findServerAdapter: vi.fn(() => mockAdapter),
|
|
findActiveServerAdapter: vi.fn((adapterType: string) => adapterType === "paperclip_runner"
|
|
? { ...mockAdapter, supportsInstructionsBundle: true }
|
|
: mockAdapter),
|
|
listAdapterModels: vi.fn(),
|
|
detectAdapterModel: vi.fn(),
|
|
}));
|
|
}
|
|
|
|
function createDb(requireBoardApprovalForNewAgents = false) {
|
|
return {
|
|
select: vi.fn(() => ({
|
|
from: vi.fn(() => ({
|
|
where: vi.fn(async () => [
|
|
{
|
|
id: "company-1",
|
|
requireBoardApprovalForNewAgents,
|
|
},
|
|
]),
|
|
})),
|
|
})),
|
|
};
|
|
}
|
|
|
|
let agentRoutes: (typeof import("../routes/agents.js"))["agentRoutes"];
|
|
let errorHandler: (typeof import("../middleware/index.js"))["errorHandler"];
|
|
|
|
async function createApp(db: Record<string, unknown> = createDb(), actor?: Record<string, unknown>) {
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((req, _res, next) => {
|
|
(req as any).actor = actor ?? {
|
|
type: "board",
|
|
userId: "local-board",
|
|
companyIds: ["company-1"],
|
|
source: "local_implicit",
|
|
isInstanceAdmin: false,
|
|
};
|
|
next();
|
|
});
|
|
app.use("/api", agentRoutes(db as any));
|
|
app.use(errorHandler);
|
|
return app;
|
|
}
|
|
|
|
async function requestApp(
|
|
app: express.Express,
|
|
buildRequest: (baseUrl: string) => request.Test,
|
|
) {
|
|
const { createServer } = await vi.importActual<typeof import("node:http")>("node:http");
|
|
const server = createServer(app);
|
|
try {
|
|
await new Promise<void>((resolve) => {
|
|
server.listen(0, "127.0.0.1", resolve);
|
|
});
|
|
const address = server.address();
|
|
if (!address || typeof address === "string") {
|
|
throw new Error("Expected HTTP server to listen on a TCP port");
|
|
}
|
|
return await buildRequest(`http://127.0.0.1:${address.port}`);
|
|
} finally {
|
|
if (server.listening) {
|
|
await new Promise<void>((resolve, reject) => {
|
|
server.close((error) => {
|
|
if (error) reject(error);
|
|
else resolve();
|
|
});
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
function makeAgent(adapterType: string) {
|
|
return {
|
|
id: "11111111-1111-4111-8111-111111111111",
|
|
companyId: "company-1",
|
|
name: "Agent",
|
|
role: "engineer",
|
|
title: "Engineer",
|
|
status: "active",
|
|
reportsTo: null,
|
|
capabilities: null,
|
|
adapterType,
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
defaultEnvironmentId: null,
|
|
permissions: null,
|
|
updatedAt: new Date(),
|
|
};
|
|
}
|
|
|
|
function skillSnapshot(adapterType = "claude_local", mode = "ephemeral") {
|
|
return {
|
|
adapterType: adapterType,
|
|
supported: true,
|
|
mode: mode,
|
|
desiredSkills: ["paperclipai/paperclip/paperclip"],
|
|
entries: [],
|
|
warnings: [],
|
|
};
|
|
}
|
|
|
|
describe("agent skill routes", () => {
|
|
beforeAll(async () => {
|
|
vi.resetModules();
|
|
vi.doUnmock("../routes/agents.js");
|
|
vi.doUnmock("../routes/authz.js");
|
|
vi.doUnmock("../middleware/index.js");
|
|
registerModuleMocks();
|
|
[{ agentRoutes }, { errorHandler }] = await Promise.all([
|
|
vi.importActual<typeof import("../routes/agents.js")>("../routes/agents.js"),
|
|
vi.importActual<typeof import("../middleware/index.js")>("../middleware/index.js"),
|
|
]);
|
|
});
|
|
|
|
beforeEach(() => {
|
|
runnerTarget.platform = "linux";
|
|
runnerTarget.architecture = "x64";
|
|
vi.clearAllMocks();
|
|
for (const mock of Object.values(mockAgentService)) mock.mockReset();
|
|
for (const mock of Object.values(mockAccessService)) mock.mockReset();
|
|
for (const mock of Object.values(mockApprovalService)) mock.mockReset();
|
|
for (const mock of Object.values(mockIssueApprovalService)) mock.mockReset();
|
|
for (const mock of Object.values(mockAgentInstructionsService)) mock.mockReset();
|
|
for (const mock of Object.values(mockCompanySkillService)) mock.mockReset();
|
|
for (const mock of Object.values(mockInstanceSettingsService)) mock.mockReset();
|
|
for (const mock of Object.values(mockSecretService)) mock.mockReset();
|
|
mockLogActivity.mockReset();
|
|
mockTrackAgentCreated.mockReset();
|
|
mockGetTelemetryClient.mockReset();
|
|
mockSyncInstructionsBundleConfigFromFilePath.mockReset();
|
|
mockAdapter.listSkills.mockReset();
|
|
mockAdapter.syncSkills.mockReset();
|
|
mockSyncInstructionsBundleConfigFromFilePath.mockImplementation((_agent, config) => config);
|
|
mockGetTelemetryClient.mockReturnValue({ track: vi.fn() });
|
|
let persistedAgent: Record<string, unknown> | null = null;
|
|
mockAgentService.resolveByReference.mockResolvedValue({
|
|
ambiguous: false,
|
|
agent: makeAgent("claude_local"),
|
|
});
|
|
mockSecretService.resolveAdapterConfigForRuntime.mockResolvedValue({ config: { env: {} } });
|
|
mockInstanceSettingsService.get.mockResolvedValue({ defaultEnvironmentId: null, experimental: {}, general: {} });
|
|
mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableBetaSkills: false });
|
|
mockSecretService.syncEnvBindingsForTarget.mockResolvedValue(undefined);
|
|
mockCompanySkillService.listRuntimeSkillEntries.mockResolvedValue([
|
|
{
|
|
key: "paperclipai/paperclip/paperclip",
|
|
runtimeName: "paperclip",
|
|
source: "/tmp/paperclip",
|
|
},
|
|
]);
|
|
mockCompanySkillService.resolveRequestedSkillKeys.mockImplementation(
|
|
async (_companyId: string, requested: string[]) =>
|
|
requested.map((value) =>
|
|
value === "paperclip"
|
|
? "paperclipai/paperclip/paperclip"
|
|
: value,
|
|
),
|
|
);
|
|
mockCompanySkillService.resolveRequestedSkillEntries.mockImplementation(
|
|
async (_companyId: string, requested: Array<{ key: string; versionId?: string | null }>) => ({
|
|
resolved: requested.map((entry) => ({
|
|
key: entry.key === "paperclip" ? "paperclipai/paperclip/paperclip" : entry.key,
|
|
versionId: entry.versionId ?? null,
|
|
})),
|
|
unresolved: [],
|
|
}),
|
|
);
|
|
mockAdapter.listSkills.mockResolvedValue(skillSnapshot());
|
|
mockAdapter.syncSkills.mockResolvedValue(skillSnapshot());
|
|
mockAgentService.update.mockImplementation(async (_id: string, patch: Record<string, unknown>) => {
|
|
const previousAgent = persistedAgent ?? makeAgent("claude_local");
|
|
persistedAgent = {
|
|
...previousAgent,
|
|
...patch,
|
|
adapterConfig: patch.adapterConfig ?? previousAgent.adapterConfig ?? {},
|
|
};
|
|
return persistedAgent;
|
|
});
|
|
mockAgentService.create.mockImplementation(async (_companyId: string, input: Record<string, unknown>) => {
|
|
persistedAgent = {
|
|
...makeAgent(String(input.adapterType ?? "claude_local")),
|
|
...input,
|
|
adapterConfig: input.adapterConfig ?? {},
|
|
runtimeConfig: input.runtimeConfig ?? {},
|
|
budgetMonthlyCents: Number(input.budgetMonthlyCents ?? 0),
|
|
permissions: null,
|
|
};
|
|
return persistedAgent;
|
|
});
|
|
mockApprovalService.create.mockImplementation(async (_companyId: string, input: Record<string, unknown>) => ({
|
|
id: "approval-1",
|
|
companyId: "company-1",
|
|
type: "hire_agent",
|
|
status: "pending",
|
|
payload: input.payload ?? {},
|
|
}));
|
|
mockAgentInstructionsService.materializeManagedBundle.mockImplementation(
|
|
async (agent: Record<string, unknown>, files: Record<string, string>) => ({
|
|
bundle: null,
|
|
adapterConfig: {
|
|
...((agent.adapterConfig as Record<string, unknown> | undefined) ?? {}),
|
|
instructionsBundleMode: "managed",
|
|
instructionsRootPath: `/tmp/${String(agent.id)}/instructions`,
|
|
instructionsEntryFile: "AGENTS.md",
|
|
instructionsFilePath: `/tmp/${String(agent.id)}/instructions/AGENTS.md`,
|
|
promptTemplate: files["AGENTS.md"] ?? "",
|
|
},
|
|
}),
|
|
);
|
|
mockLogActivity.mockResolvedValue(undefined);
|
|
mockAccessService.canUser.mockResolvedValue(true);
|
|
mockAccessService.decide.mockResolvedValue({
|
|
allowed: true,
|
|
reason: "allow_explicit_grant",
|
|
explanation: "Allowed by test grant",
|
|
});
|
|
mockAccessService.hasPermission.mockResolvedValue(true);
|
|
mockAccessService.getMembership.mockResolvedValue(null);
|
|
mockAccessService.listPrincipalGrants.mockResolvedValue([]);
|
|
mockAccessService.ensureMembership.mockResolvedValue(undefined);
|
|
mockAccessService.setPrincipalPermission.mockResolvedValue(undefined);
|
|
});
|
|
|
|
it("skips runtime materialization when listing Claude skills", async () => {
|
|
mockAgentService.getById.mockResolvedValue(makeAgent("claude_local"));
|
|
|
|
const res = await requestApp(
|
|
await createApp(),
|
|
(baseUrl) => request(baseUrl)
|
|
.get("/api/agents/11111111-1111-4111-8111-111111111111/skills?companyId=company-1"),
|
|
);
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
|
expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", expect.objectContaining({
|
|
materializeMissing: false,
|
|
versionSelections: expect.any(Map),
|
|
}));
|
|
expect(mockAdapter.listSkills).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
adapterType: "claude_local",
|
|
config: expect.objectContaining({
|
|
paperclipRuntimeSkills: expect.any(Array),
|
|
}),
|
|
}),
|
|
);
|
|
}, 10_000);
|
|
|
|
it("round-trips latest assignments without inventing beta version pins", async () => {
|
|
const existing = "github/fixture/existing";
|
|
const added = "github/fixture/added";
|
|
const resolvedVersionId = "22222222-2222-4222-8222-222222222222";
|
|
mockAgentService.getById.mockResolvedValue({
|
|
...makeAgent("claude_local"),
|
|
adapterConfig: { paperclipSkillSync: { desiredSkills: [existing] } },
|
|
});
|
|
// Adapters describe the resolved runtime version. It is not an assignment pin.
|
|
mockAdapter.listSkills.mockResolvedValue({
|
|
...skillSnapshot(), desiredSkills: [existing],
|
|
desiredSkillEntries: [{ key: existing, versionId: resolvedVersionId }],
|
|
});
|
|
mockAdapter.syncSkills.mockResolvedValue({
|
|
...skillSnapshot(), desiredSkills: [existing, added],
|
|
desiredSkillEntries: [{ key: existing, versionId: resolvedVersionId }, { key: added, versionId: resolvedVersionId }],
|
|
});
|
|
const app = await createApp();
|
|
const snapshot = await requestApp(app, baseUrl => request(baseUrl)
|
|
.get("/api/agents/11111111-1111-4111-8111-111111111111/skills?companyId=company-1"));
|
|
expect(snapshot.status).toBe(200);
|
|
const saved = await requestApp(app, baseUrl => request(baseUrl)
|
|
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
|
|
.send({ desiredSkills: [...snapshot.body.desiredSkillEntries, { key: added, versionId: null }], mode: "replace" }));
|
|
expect(saved.status, JSON.stringify(saved.body)).toBe(200);
|
|
expect(saved.body.desiredSkillEntries).toEqual([{ key: existing, versionId: null }, { key: added, versionId: null }]);
|
|
expect(mockAgentService.update.mock.calls.at(-1)?.[1].adapterConfig.paperclipSkillSync.desiredSkills).toEqual([existing, added]);
|
|
});
|
|
|
|
it("keeps explicit historical assignment pins in skill snapshots", async () => {
|
|
const key = "github/fixture/pinned";
|
|
const pinnedVersionId = "22222222-2222-4222-8222-222222222222";
|
|
mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableBetaSkills: true });
|
|
mockAgentService.getById.mockResolvedValue({ ...makeAgent("claude_local"),
|
|
adapterConfig: { paperclipSkillSync: { desiredSkills: [{ key, versionId: pinnedVersionId }] } } });
|
|
mockAdapter.listSkills.mockResolvedValue({ ...skillSnapshot(), desiredSkills: [key], desiredSkillEntries: [{ key, versionId: null }] });
|
|
const snapshot = await requestApp(await createApp(), baseUrl => request(baseUrl)
|
|
.get("/api/agents/11111111-1111-4111-8111-111111111111/skills?companyId=company-1"));
|
|
expect(snapshot.status).toBe(200);
|
|
expect(snapshot.body.desiredSkillEntries).toEqual([{ key, versionId: pinnedVersionId }]);
|
|
});
|
|
|
|
it("lists skills without resolving required user-secret env bindings", async () => {
|
|
const adapterConfig = {
|
|
env: {
|
|
HOME: "/home/agent",
|
|
GH_TOKEN: {
|
|
type: "user_secret_ref" as const,
|
|
key: "github_pat_read_only",
|
|
version: "latest" as const,
|
|
required: true,
|
|
},
|
|
},
|
|
};
|
|
mockAgentService.getById.mockResolvedValue({
|
|
...makeAgent("claude_local"),
|
|
adapterConfig,
|
|
});
|
|
mockSecretService.resolveAdapterConfigForRuntime.mockImplementationOnce(
|
|
async (
|
|
_companyId: string,
|
|
config: Record<string, unknown>,
|
|
context?: unknown,
|
|
opts?: { skipUserSecrets?: boolean },
|
|
) => {
|
|
expect(config).toBe(adapterConfig);
|
|
// Audit-only actor context is threaded through for company `secret_ref`
|
|
// attribution; user secrets are still skipped (skipUserSecrets: true).
|
|
expect(context).toEqual({
|
|
consumerType: "agent",
|
|
consumerId: "11111111-1111-4111-8111-111111111111",
|
|
actorType: "user",
|
|
actorId: "local-board",
|
|
actorSource: "local_implicit",
|
|
responsibleUserId: "local-board",
|
|
});
|
|
expect(opts).toEqual({ adapterType: "claude_local", skipUserSecrets: true });
|
|
return { config: { env: { HOME: "/home/agent" } } };
|
|
},
|
|
);
|
|
|
|
const res = await requestApp(
|
|
await createApp(),
|
|
(baseUrl) => request(baseUrl)
|
|
.get("/api/agents/11111111-1111-4111-8111-111111111111/skills?companyId=company-1"),
|
|
);
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
|
expect(mockAdapter.listSkills).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
adapterType: "claude_local",
|
|
config: expect.objectContaining({
|
|
env: { HOME: "/home/agent" },
|
|
paperclipRuntimeSkills: expect.any(Array),
|
|
}),
|
|
}),
|
|
);
|
|
});
|
|
|
|
|
|
|
|
it("skips runtime materialization when listing Codex skills", async () => {
|
|
mockAgentService.getById.mockResolvedValue(makeAgent("codex_local"));
|
|
mockAdapter.listSkills.mockResolvedValue(skillSnapshot("codex_local"));
|
|
|
|
const res = await requestApp(
|
|
await createApp(),
|
|
(baseUrl) => request(baseUrl)
|
|
.get("/api/agents/11111111-1111-4111-8111-111111111111/skills?companyId=company-1"),
|
|
);
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
|
expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", expect.objectContaining({
|
|
materializeMissing: false,
|
|
versionSelections: expect.any(Map),
|
|
}));
|
|
});
|
|
|
|
it("passes ACPX Claude config through the agent skill listing route", async () => {
|
|
mockAgentService.getById.mockResolvedValue({
|
|
...makeAgent("acpx_local"),
|
|
adapterConfig: { agent: "claude" },
|
|
});
|
|
mockSecretService.resolveAdapterConfigForRuntime.mockResolvedValueOnce({
|
|
config: { agent: "claude" },
|
|
});
|
|
mockAdapter.listSkills.mockResolvedValue(skillSnapshot("acpx_local"));
|
|
|
|
const res = await requestApp(
|
|
await createApp(),
|
|
(baseUrl) => request(baseUrl)
|
|
.get("/api/agents/11111111-1111-4111-8111-111111111111/skills?companyId=company-1"),
|
|
);
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
|
expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", expect.objectContaining({
|
|
materializeMissing: false,
|
|
versionSelections: expect.any(Map),
|
|
}));
|
|
expect(mockAdapter.listSkills).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
adapterType: "acpx_local",
|
|
config: expect.objectContaining({
|
|
agent: "claude",
|
|
paperclipRuntimeSkills: expect.any(Array),
|
|
}),
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("persists ACPX Codex desired skills through the agent skill sync route", async () => {
|
|
mockAgentService.getById.mockResolvedValue({
|
|
...makeAgent("acpx_local"),
|
|
adapterConfig: { agent: "codex" },
|
|
});
|
|
mockAgentService.update.mockImplementationOnce(async (_id: string, patch: Record<string, unknown>) => ({
|
|
...makeAgent("acpx_local"),
|
|
adapterConfig: patch.adapterConfig ?? {},
|
|
}));
|
|
mockSecretService.resolveAdapterConfigForRuntime.mockResolvedValueOnce({
|
|
config: {
|
|
agent: "codex",
|
|
paperclipSkillSync: {
|
|
desiredSkills: ["paperclipai/paperclip/paperclip"],
|
|
},
|
|
},
|
|
});
|
|
mockAdapter.syncSkills.mockResolvedValue(skillSnapshot("acpx_local"));
|
|
|
|
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({
|
|
agent: "codex",
|
|
paperclipSkillSync: expect.objectContaining({
|
|
desiredSkills: ["paperclipai/paperclip/paperclip"],
|
|
}),
|
|
}),
|
|
}),
|
|
expect.any(Object),
|
|
);
|
|
expect(mockAdapter.syncSkills).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
adapterType: "acpx_local",
|
|
config: expect.objectContaining({
|
|
agent: "codex",
|
|
paperclipRuntimeSkills: expect.any(Array),
|
|
}),
|
|
}),
|
|
["paperclipai/paperclip/paperclip"],
|
|
);
|
|
});
|
|
|
|
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",
|
|
}],
|
|
}));
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(400);
|
|
expect(res.body.error).toContain("Beta skills experimental setting");
|
|
expect(mockAgentService.update).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("accepts version pins while beta skills are enabled", async () => {
|
|
mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableBetaSkills: true });
|
|
mockAgentService.getById.mockResolvedValue(makeAgent("claude_local"));
|
|
const versionId = "22222222-2222-4222-8222-222222222222";
|
|
|
|
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 }],
|
|
}));
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
|
expect(mockAgentService.update).toHaveBeenCalledWith(
|
|
expect.any(String),
|
|
expect.objectContaining({
|
|
adapterConfig: expect.objectContaining({
|
|
paperclipSkillSync: expect.objectContaining({
|
|
desiredSkills: [{ key: "paperclipai/paperclip/paperclip", versionId }],
|
|
}),
|
|
}),
|
|
}),
|
|
expect.any(Object),
|
|
);
|
|
});
|
|
|
|
it("preserves stale desired keys instead of 422-ing when syncing (PAP-13222)", async () => {
|
|
mockAgentService.getById.mockResolvedValue(makeAgent("acpx_local"));
|
|
// The agent already carries a stale desired key that no longer resolves to a
|
|
// company-library skill. Toggling a resolvable skill must still succeed and
|
|
// keep the stale key so it stays visible/removable in the UI.
|
|
mockCompanySkillService.resolveRequestedSkillEntries.mockImplementationOnce(
|
|
async (
|
|
_companyId: string,
|
|
requested: Array<{ key: string; versionId?: string | null }>,
|
|
options?: { tolerateUnknownReferences?: boolean },
|
|
) => {
|
|
expect(options?.tolerateUnknownReferences).toBe(true);
|
|
const resolved: Array<{ key: string; versionId: string | null }> = [];
|
|
const unresolved: string[] = [];
|
|
for (const entry of requested) {
|
|
if (entry.key === "stale/removed/skill") {
|
|
unresolved.push(entry.key);
|
|
} else {
|
|
resolved.push({
|
|
key: entry.key === "paperclip" ? "paperclipai/paperclip/paperclip" : entry.key,
|
|
versionId: entry.versionId ?? null,
|
|
});
|
|
}
|
|
}
|
|
return { resolved, unresolved };
|
|
},
|
|
);
|
|
|
|
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
|
|
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
|
|
.send({ desiredSkills: ["paperclip", "stale/removed/skill"], mode: "replace" }));
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
|
// Stale key preserved in the persisted config alongside the resolved skill.
|
|
expect(mockAgentService.update).toHaveBeenCalledWith(
|
|
expect.any(String),
|
|
expect.objectContaining({
|
|
adapterConfig: expect.objectContaining({
|
|
paperclipSkillSync: expect.objectContaining({
|
|
desiredSkills: ["paperclipai/paperclip/paperclip", "stale/removed/skill"],
|
|
}),
|
|
}),
|
|
}),
|
|
expect.any(Object),
|
|
);
|
|
// Runtime version selection only considers resolvable keys.
|
|
expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith(
|
|
"company-1",
|
|
expect.objectContaining({ versionSelections: expect.any(Map) }),
|
|
);
|
|
const versionSelections = mockCompanySkillService.listRuntimeSkillEntries.mock.calls.at(-1)?.[1]
|
|
?.versionSelections as Map<string, unknown> | undefined;
|
|
expect(versionSelections?.has("stale/removed/skill")).toBe(false);
|
|
});
|
|
|
|
it("skips runtime materialization when listing persistent skill adapters", async () => {
|
|
mockAgentService.getById.mockResolvedValue(makeAgent("cursor"));
|
|
mockAdapter.listSkills.mockResolvedValue(skillSnapshot("cursor", "persistent"));
|
|
|
|
const res = await requestApp(
|
|
await createApp(),
|
|
(baseUrl) => request(baseUrl)
|
|
.get("/api/agents/11111111-1111-4111-8111-111111111111/skills?companyId=company-1"),
|
|
);
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
|
expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", expect.objectContaining({
|
|
materializeMissing: false,
|
|
versionSelections: expect.any(Map),
|
|
}));
|
|
});
|
|
|
|
it("skips runtime materialization when syncing Claude skills", 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({ desiredSkills: ["paperclipai/paperclip/paperclip"], mode: "replace" }));
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
|
expect(mockAdapter.syncSkills).toHaveBeenCalled();
|
|
});
|
|
|
|
it("ignores the reserved legacy Paperclip skill for paperclip_runner", async () => {
|
|
mockAgentService.getById.mockResolvedValue(makeAgent("paperclip_runner"));
|
|
|
|
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"], 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: [] },
|
|
}),
|
|
}),
|
|
expect.any(Object),
|
|
);
|
|
expect(mockAdapter.syncSkills).toHaveBeenCalledWith(
|
|
expect.any(Object),
|
|
[],
|
|
);
|
|
});
|
|
|
|
it("allows paperclip_runner to remove a pre-existing legacy Paperclip skill", async () => {
|
|
mockAgentService.getById.mockResolvedValue({
|
|
...makeAgent("paperclip_runner"),
|
|
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: ["paperclipai/paperclip/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("syncs skills without resolving required user-secret env bindings", async () => {
|
|
const adapterConfig = {
|
|
env: {
|
|
HOME: "/home/agent",
|
|
GH_TOKEN: {
|
|
type: "user_secret_ref" as const,
|
|
key: "github_pat_read_only",
|
|
version: "latest" as const,
|
|
required: true,
|
|
},
|
|
},
|
|
};
|
|
mockAgentService.getById.mockResolvedValue({
|
|
...makeAgent("claude_local"),
|
|
adapterConfig,
|
|
});
|
|
mockSecretService.resolveAdapterConfigForRuntime.mockImplementationOnce(
|
|
async (
|
|
_companyId: string,
|
|
config: Record<string, unknown>,
|
|
context?: unknown,
|
|
opts?: { skipUserSecrets?: boolean },
|
|
) => {
|
|
expect((config.env as Record<string, unknown>).GH_TOKEN).toMatchObject({
|
|
type: "user_secret_ref",
|
|
key: "github_pat_read_only",
|
|
});
|
|
// Audit-only actor context is threaded through for company `secret_ref`
|
|
// attribution; user secrets are still skipped (skipUserSecrets: true).
|
|
expect(context).toEqual({
|
|
consumerType: "agent",
|
|
consumerId: "11111111-1111-4111-8111-111111111111",
|
|
actorType: "user",
|
|
actorId: "local-board",
|
|
actorSource: "local_implicit",
|
|
responsibleUserId: "local-board",
|
|
});
|
|
expect(opts).toEqual({ adapterType: "claude_local", skipUserSecrets: true });
|
|
return {
|
|
config: {
|
|
...config,
|
|
env: { HOME: "/home/agent" },
|
|
},
|
|
};
|
|
},
|
|
);
|
|
|
|
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"], mode: "replace" }));
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
|
expect(mockAdapter.syncSkills).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
adapterType: "claude_local",
|
|
config: expect.objectContaining({
|
|
env: { HOME: "/home/agent" },
|
|
paperclipRuntimeSkills: expect.any(Array),
|
|
}),
|
|
}),
|
|
["paperclipai/paperclip/paperclip"],
|
|
);
|
|
});
|
|
|
|
it("persists canonical desired skills when creating an agent directly", async () => {
|
|
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
|
|
.post("/api/companies/company-1/agents")
|
|
.send({
|
|
name: "QA Agent",
|
|
role: "engineer",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
desiredSkills: ["paperclip"],
|
|
adapterConfig: {},
|
|
}));
|
|
|
|
expect([200, 201], JSON.stringify(res.body)).toContain(res.status);
|
|
const createdAgentId = expectResponseId(res.body.id);
|
|
expect(mockAgentService.create).toHaveBeenCalledWith(
|
|
"company-1",
|
|
expect.objectContaining({
|
|
adapterConfig: expect.objectContaining({
|
|
paperclipSkillSync: expect.objectContaining({
|
|
desiredSkills: ["paperclipai/paperclip/paperclip"],
|
|
}),
|
|
}),
|
|
}),
|
|
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "local-board", responsibleUserId: "local-board", claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
|
|
);
|
|
expect(mockTrackAgentCreated).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
agentId: createdAgentId,
|
|
agentRole: "engineer",
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("rejects version pins when creating an agent while beta skills are disabled", async () => {
|
|
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
|
|
.post("/api/companies/company-1/agents")
|
|
.send({
|
|
name: "QA Agent",
|
|
role: "engineer",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
desiredSkills: [{
|
|
key: "paperclipai/paperclip/paperclip",
|
|
versionId: "22222222-2222-4222-8222-222222222222",
|
|
}],
|
|
adapterConfig: {},
|
|
}));
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(400);
|
|
expect(res.body.error).toContain("Beta skills experimental setting");
|
|
expect(mockAgentService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("accepts the security role on direct agent creation and preserves it in telemetry", async () => {
|
|
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
|
|
.post("/api/companies/company-1/agents")
|
|
.send({
|
|
name: "Security Engineer",
|
|
role: "security",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
adapterConfig: {},
|
|
}));
|
|
|
|
expect([200, 201], JSON.stringify(res.body)).toContain(res.status);
|
|
const createdAgentId = expectResponseId(res.body.id);
|
|
expect(res.body).toMatchObject({
|
|
role: "security",
|
|
});
|
|
expect(mockAgentService.create).toHaveBeenCalledWith(
|
|
"company-1",
|
|
expect.objectContaining({
|
|
role: "security",
|
|
}),
|
|
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "local-board", responsibleUserId: "local-board", claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
|
|
);
|
|
expect(mockTrackAgentCreated).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
expect.objectContaining({
|
|
agentId: createdAgentId,
|
|
agentRole: "security",
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("materializes a managed AGENTS.md for directly created local agents", async () => {
|
|
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
|
|
.post("/api/companies/company-1/agents")
|
|
.send({
|
|
name: "QA Agent",
|
|
role: "engineer",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
adapterConfig: {},
|
|
instructionsBundle: {
|
|
files: {
|
|
"AGENTS.md": "You are QA.",
|
|
},
|
|
},
|
|
}));
|
|
|
|
expect([200, 201], JSON.stringify(res.body)).toContain(res.status);
|
|
const createdAgentId = expectResponseId(res.body.id);
|
|
expect(mockAgentService.update).toHaveBeenCalledWith(
|
|
createdAgentId,
|
|
expect.objectContaining({
|
|
adapterConfig: expect.objectContaining({
|
|
instructionsBundleMode: "managed",
|
|
instructionsEntryFile: "AGENTS.md",
|
|
instructionsRootPath: `/tmp/${createdAgentId}/instructions`,
|
|
instructionsFilePath: `/tmp/${createdAgentId}/instructions/AGENTS.md`,
|
|
}),
|
|
}),
|
|
expect.objectContaining({ allowPendingApprovalConfigUpdate: true }),
|
|
);
|
|
expect(mockAgentService.update.mock.calls.at(-1)?.[1]).not.toMatchObject({
|
|
adapterConfig: expect.objectContaining({
|
|
promptTemplate: expect.anything(),
|
|
}),
|
|
});
|
|
});
|
|
|
|
it("rejects legacy prompt templates for directly created local agents", async () => {
|
|
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
|
|
.post("/api/companies/company-1/agents")
|
|
.send({
|
|
name: "QA Agent",
|
|
role: "engineer",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
adapterConfig: {
|
|
instructionsFilePath: "/tmp/existing/AGENTS.md",
|
|
promptTemplate: "You are QA.",
|
|
bootstrapPromptTemplate: "Bootstrap QA.",
|
|
},
|
|
}));
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(422);
|
|
expect(res.body.error).toContain("New agents must use instructionsBundle/AGENTS.md");
|
|
expect(mockAgentService.create).not.toHaveBeenCalled();
|
|
expect(mockAgentInstructionsService.materializeManagedBundle).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each(["claude_local", "paperclip_runner"].flatMap((adapterType) =>
|
|
["agents", "agent-hires"].map((route) => ({ adapterType, route })),
|
|
))("materializes only the CEO entry file for $adapterType via $route", async ({ adapterType, route }) => {
|
|
mockInstanceSettingsService.getExperimental.mockResolvedValue({
|
|
enableBetaSkills: false,
|
|
enableNativeRunner: true,
|
|
});
|
|
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
|
|
.post(`/api/companies/company-1/${route}`)
|
|
.send({
|
|
name: "CEO",
|
|
role: "ceo",
|
|
adapterType,
|
|
...(adapterType === "claude_local" ? { runner: "legacy" } : {}),
|
|
adapterConfig: adapterType === "paperclip_runner" ? { provider: "codex" } : {},
|
|
}));
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(201);
|
|
const createdAgentId = expectResponseId(route === "agents" ? res.body.id : res.body.agent.id);
|
|
const entry = await readFile(new URL("../onboarding-assets/ceo/AGENTS.md", import.meta.url), "utf8");
|
|
expect(mockAgentInstructionsService.materializeManagedBundle).toHaveBeenCalledExactlyOnceWith(
|
|
expect.objectContaining({ id: createdAgentId, role: "ceo", adapterType }),
|
|
{ "AGENTS.md": entry },
|
|
{ entryFile: "AGENTS.md", replaceExisting: false },
|
|
);
|
|
});
|
|
|
|
it.each(["claude_local", "paperclip_runner"].flatMap((adapterType) =>
|
|
["agents", "agent-hires"].map((route) => ({ adapterType, route })),
|
|
))("preserves an explicit CEO instruction bundle for $adapterType via $route", async ({ adapterType, route }) => {
|
|
mockInstanceSettingsService.getExperimental.mockResolvedValue({
|
|
enableBetaSkills: false,
|
|
enableNativeRunner: true,
|
|
});
|
|
const customFiles = {
|
|
"AGENTS.md": "You lead the bespoke research company. Read NOTES.md for its current focus.",
|
|
"NOTES.md": "Focus on the board's research questions.",
|
|
};
|
|
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
|
|
.post(`/api/companies/company-1/${route}`)
|
|
.send({
|
|
name: "Research Lead",
|
|
role: "ceo",
|
|
adapterType,
|
|
...(adapterType === "claude_local" ? { runner: "legacy" } : {}),
|
|
adapterConfig: adapterType === "paperclip_runner" ? { provider: "codex" } : {},
|
|
instructionsBundle: { entryFile: "AGENTS.md", files: customFiles },
|
|
}));
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(201);
|
|
const createdAgentId = expectResponseId(route === "agents" ? res.body.id : res.body.agent.id);
|
|
expect(mockAgentInstructionsService.materializeManagedBundle).toHaveBeenCalledExactlyOnceWith(
|
|
expect.objectContaining({ id: createdAgentId, role: "ceo", adapterType }),
|
|
customFiles,
|
|
{ entryFile: "AGENTS.md", replaceExisting: false },
|
|
);
|
|
const returnedAgent = route === "agents" ? res.body : res.body.agent;
|
|
expect(returnedAgent.adapterConfig).toMatchObject({
|
|
instructionsEntryFile: "AGENTS.md",
|
|
instructionsFilePath: `/tmp/${createdAgentId}/instructions/AGENTS.md`,
|
|
});
|
|
expect(returnedAgent.adapterConfig).not.toHaveProperty("promptTemplate");
|
|
});
|
|
|
|
it("materializes minimal default instructions for non-CEO agents with no prompt template", async () => {
|
|
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
|
|
.post("/api/companies/company-1/agents")
|
|
.send({
|
|
name: "Engineer",
|
|
role: "engineer",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
adapterConfig: {},
|
|
}));
|
|
|
|
expect([200, 201], JSON.stringify(res.body)).toContain(res.status);
|
|
const createdAgentId = expectResponseId(res.body.id);
|
|
await vi.waitFor(() => {
|
|
expect(mockAgentInstructionsService.materializeManagedBundle).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
id: createdAgentId,
|
|
role: "engineer",
|
|
adapterType: "claude_local",
|
|
}),
|
|
expect.objectContaining({
|
|
"AGENTS.md": "You are an agent in a Paperclip company.\n",
|
|
}),
|
|
{ entryFile: "AGENTS.md", replaceExisting: false },
|
|
);
|
|
});
|
|
});
|
|
|
|
it("seeds the chief-of-staff persona for the onboarding first agent", async () => {
|
|
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
|
|
.post("/api/companies/company-1/agents")
|
|
.send({
|
|
name: "Ada",
|
|
role: "general",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
adapterConfig: {},
|
|
onboardingFirstAgent: true,
|
|
}));
|
|
|
|
expect([200, 201], JSON.stringify(res.body)).toContain(res.status);
|
|
const createdAgentId = expectResponseId(res.body.id);
|
|
await vi.waitFor(() => {
|
|
expect(mockAgentInstructionsService.materializeManagedBundle).toHaveBeenCalledWith(
|
|
expect.objectContaining({ id: createdAgentId, role: "general" }),
|
|
expect.objectContaining({
|
|
"AGENTS.md": expect.stringContaining("You are Ada, chief of staff for"),
|
|
}),
|
|
{ entryFile: "AGENTS.md", replaceExisting: false },
|
|
);
|
|
});
|
|
// The generic default persona must NOT be what was seeded over the entry file.
|
|
const seededCalls = mockAgentInstructionsService.materializeManagedBundle.mock.calls;
|
|
const entrySeed = seededCalls.at(-1)?.[1] as Record<string, string> | undefined;
|
|
expect(entrySeed?.["AGENTS.md"]).toContain("chief of staff");
|
|
// The normal onboarding flow has beta skill version selection disabled.
|
|
expect(mockAgentService.create.mock.calls[0][1].adapterConfig.paperclipSkillSync.desiredSkills)
|
|
.toContain("paperclipai/paperclip/first-task");
|
|
});
|
|
|
|
const codexRunnerCases = [
|
|
{ adapterType: "codex_local", runner: "auto", platform: "linux", expectedType: "paperclip_runner" },
|
|
{ adapterType: "codex_local", runner: "legacy", platform: "linux", expectedType: "codex_local" },
|
|
{ adapterType: "codex_local", runner: "auto", platform: "darwin", expectedType: "paperclip_runner" },
|
|
{ adapterType: "codex_local", runner: "legacy", platform: "darwin", expectedType: "codex_local" },
|
|
{ adapterType: "codex_local", runner: "auto", platform: "win32", expectedType: "codex_local" },
|
|
];
|
|
const creationRunnerCases = [...codexRunnerCases,
|
|
{ adapterType: "claude_local", runner: "auto", platform: "linux", expectedType: "paperclip_runner" },
|
|
{ adapterType: "claude_local", runner: "legacy", platform: "linux", expectedType: "claude_local" },
|
|
{ adapterType: "claude_local", runner: "auto", platform: "darwin", expectedType: "paperclip_runner" },
|
|
{ adapterType: "claude_local", runner: "legacy", platform: "darwin", expectedType: "claude_local" },
|
|
];
|
|
it.each(creationRunnerCases.flatMap((runnerCase) => [
|
|
["agents", "paperclipai/paperclip/paperclip-create-agent"],
|
|
["agent-hires", "paperclipai/paperclip/paperclip-create-agent"],
|
|
["agents", "paperclip"],
|
|
["agent-hires", "paperclip"],
|
|
["agents", "paperclipai/paperclip/first-task"],
|
|
["agent-hires", "paperclipai/paperclip/first-task"],
|
|
].map(([route, skill]) => ({ ...runnerCase, route, skill }))))("assigns onboarding skills via $route for $adapterType/$runner on $platform with $skill pins", async ({ adapterType, runner, platform, expectedType, route, skill }) => {
|
|
runnerTarget.platform = platform;
|
|
runnerTarget.architecture = platform === "darwin" ? "arm64" : "x64";
|
|
mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableBetaSkills: true });
|
|
const versionId = "22222222-2222-4222-8222-222222222222";
|
|
const res = await request(await createApp(createDb(route === "agent-hires")))
|
|
.post(`/api/companies/company-1/${route}`)
|
|
.send({
|
|
name: "Chiff", role: "general", adapterType, ...(runner === "auto" ? {} : { runner }),
|
|
onboardingFirstAgent: true,
|
|
desiredSkills: [{ key: skill, versionId }],
|
|
});
|
|
expect(res.status, JSON.stringify(res.body)).toBe(201);
|
|
const input = mockAgentService.create.mock.calls[0][1];
|
|
expect(input.role).toBe("general");
|
|
expect(input.adapterType).toBe(expectedType);
|
|
const native = expectedType === "paperclip_runner";
|
|
if (native) expect(input.adapterConfig).toMatchObject(adapterType === "claude_local" ? { provider: "acpx", acpxAgent: "claude", model: "claude-opus-5-5" } : { provider: "codex" });
|
|
const canonicalKey = skill === "paperclip" ? "paperclipai/paperclip/paperclip" : skill;
|
|
const expected = ["paperclip", "paperclip-board", "paperclip-converting-plans-to-tasks", "paperclip-create-agent", "para-memory-files", "first-task"]
|
|
.filter((name) => !native || name !== "paperclip")
|
|
.map((name) => ({ key: `paperclipai/paperclip/${name}`, versionId: `paperclipai/paperclip/${name}` === canonicalKey ? versionId : null }));
|
|
const desiredSkills = input.adapterConfig.paperclipSkillSync.desiredSkills.map((entry: string | { key: string; versionId: string | null }) =>
|
|
typeof entry === "string" ? { key: entry, versionId: null } : entry);
|
|
expect(desiredSkills).toEqual(expect.arrayContaining(expected));
|
|
expect(desiredSkills).toHaveLength(expected.length);
|
|
});
|
|
|
|
it.each(["agents", "agent-hires"])("leaves ordinary general agents' defaults unchanged via %s", async (route) => {
|
|
const res = await request(await createApp())
|
|
.post(`/api/companies/company-1/${route}`)
|
|
.send({ name: "Biff", role: "general", adapterType: "codex_local" });
|
|
expect(res.status, JSON.stringify(res.body)).toBe(201);
|
|
expect(mockAgentService.create.mock.calls[0][1].adapterConfig.paperclipSkillSync).toBeUndefined();
|
|
});
|
|
|
|
it.each(creationRunnerCases.flatMap((runnerCase) => ["agents", "agent-hires"].map((route) => ({ ...runnerCase, route }))))("assigns core skills without first-task to ordinary CEOs via $route using $runner on $platform", async ({ route, runner, platform, expectedType, adapterType }) => {
|
|
runnerTarget.platform = platform;
|
|
runnerTarget.architecture = platform === "darwin" ? "arm64" : "x64";
|
|
const res = await request(await createApp())
|
|
.post(`/api/companies/company-1/${route}`)
|
|
.send({ name: "CEO", role: "ceo", adapterType, ...(runner === "auto" ? {} : { runner }) });
|
|
expect(res.status, JSON.stringify(res.body)).toBe(201);
|
|
const input = mockAgentService.create.mock.calls[0][1];
|
|
expect(input.adapterType).toBe(expectedType);
|
|
const native = expectedType === "paperclip_runner";
|
|
if (native) expect(input.adapterConfig).toMatchObject(adapterType === "claude_local" ? { provider: "acpx", acpxAgent: "claude", model: "claude-opus-5-5" } : { provider: "codex" });
|
|
const desiredSkills = input.adapterConfig.paperclipSkillSync.desiredSkills;
|
|
const expected = ["paperclip", "paperclip-board", "paperclip-converting-plans-to-tasks", "paperclip-create-agent", "para-memory-files"]
|
|
.filter((name) => !native || name !== "paperclip")
|
|
.map((name) => `paperclipai/paperclip/${name}`);
|
|
expect(desiredSkills).toEqual(expect.arrayContaining(expected));
|
|
expect(desiredSkills).toHaveLength(expected.length);
|
|
expect(desiredSkills).not.toContain("paperclipai/paperclip/first-task");
|
|
});
|
|
|
|
it("does not trust an agent-supplied onboarding marker to select chief-of-staff defaults", async () => {
|
|
mockAgentService.getById.mockResolvedValue(makeAgent("claude_local"));
|
|
const res = await request(await createApp(createDb(), {
|
|
type: "agent", agentId: "11111111-1111-4111-8111-111111111111", companyId: "company-1",
|
|
}))
|
|
.post("/api/companies/company-1/agent-hires")
|
|
.send({ name: "Biff", role: "general", adapterType: "claude_local",
|
|
runner: "legacy", onboardingFirstAgent: true });
|
|
expect(res.status, JSON.stringify(res.body)).toBe(201);
|
|
expect(mockAgentService.create.mock.calls[0][1].adapterConfig.paperclipSkillSync).toBeUndefined();
|
|
await vi.waitFor(() => expect(mockAgentInstructionsService.materializeManagedBundle).toHaveBeenCalled());
|
|
expect(mockAgentInstructionsService.materializeManagedBundle.mock.calls[0][1]["AGENTS.md"])
|
|
.not.toContain("chief of staff");
|
|
});
|
|
|
|
it("creates nothing for rejected Biff payloads and exactly one approval-gated hire after correction", async () => {
|
|
const app = await createApp(createDb(true));
|
|
const hire = { name: "Biff", role: "general", adapterType: "codex_local", capabilities: "Be a friendly, affable robot" };
|
|
const retired = await request(app).post("/api/companies/company-1/agent-hires")
|
|
.send({ ...hire, adapterConfig: { promptTemplate: "Be friendly" } });
|
|
expect(retired.status).toBe(422);
|
|
const malformed = await request(app).post("/api/companies/company-1/agent-hires")
|
|
.send({ ...hire, instructionsBundle: { files: [{ path: "AGENTS.md", content: "Be friendly" }] } });
|
|
expect(malformed.status).toBe(400);
|
|
expect(mockAgentService.create).not.toHaveBeenCalled();
|
|
expect(mockApprovalService.create).not.toHaveBeenCalled();
|
|
const corrected = await request(app).post("/api/companies/company-1/agent-hires")
|
|
.send({ ...hire, instructionsBundle: { files: { "AGENTS.md": "Be a friendly, affable robot." } } });
|
|
expect(corrected.status, JSON.stringify(corrected.body)).toBe(201);
|
|
expect(corrected.body.agent).toMatchObject({ name: "Biff", status: "pending_approval" });
|
|
expect(corrected.body.approval).toMatchObject({ type: "hire_agent", status: "pending" });
|
|
expect(mockAgentService.create).toHaveBeenCalledTimes(1);
|
|
expect(mockApprovalService.create).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("gives a CEO hire the core paperclip skills when none are requested", async () => {
|
|
const res = await request(await createApp(createDb(true)))
|
|
.post("/api/companies/company-1/agent-hires")
|
|
.send({
|
|
name: "First Lead",
|
|
role: "ceo",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
adapterConfig: {},
|
|
});
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(201);
|
|
expect(mockAgentService.create).toHaveBeenCalledWith(
|
|
"company-1",
|
|
expect.objectContaining({
|
|
adapterConfig: expect.objectContaining({
|
|
paperclipSkillSync: expect.objectContaining({
|
|
desiredSkills: expect.arrayContaining([
|
|
"paperclipai/paperclip/paperclip",
|
|
"paperclipai/paperclip/paperclip-board",
|
|
"paperclipai/paperclip/paperclip-converting-plans-to-tasks",
|
|
"paperclipai/paperclip/paperclip-create-agent",
|
|
"paperclipai/paperclip/para-memory-files",
|
|
]),
|
|
}),
|
|
}),
|
|
}),
|
|
expect.anything(),
|
|
);
|
|
});
|
|
|
|
it("omits the legacy operational skill from paperclip_runner CEO defaults", async () => {
|
|
mockInstanceSettingsService.getExperimental.mockResolvedValue({
|
|
enableBetaSkills: false,
|
|
enableNativeRunner: true,
|
|
});
|
|
|
|
const res = await request(await createApp(createDb(true)))
|
|
.post("/api/companies/company-1/agent-hires")
|
|
.send({
|
|
name: "Native Lead",
|
|
role: "ceo",
|
|
adapterType: "paperclip_runner",
|
|
adapterConfig: { provider: "codex" },
|
|
});
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(201);
|
|
const createInput = mockAgentService.create.mock.calls[0]?.[1] as {
|
|
adapterConfig: { paperclipSkillSync: { desiredSkills: string[] } };
|
|
};
|
|
expect(createInput.adapterConfig.paperclipSkillSync.desiredSkills).not.toContain(
|
|
"paperclipai/paperclip/paperclip",
|
|
);
|
|
expect(createInput.adapterConfig.paperclipSkillSync.desiredSkills).toContain(
|
|
"paperclipai/paperclip/paperclip-board",
|
|
);
|
|
});
|
|
|
|
it("unions requested skills with the CEO defaults instead of replacing them", async () => {
|
|
const res = await request(await createApp(createDb(true)))
|
|
.post("/api/companies/company-1/agent-hires")
|
|
.send({
|
|
name: "First Lead",
|
|
role: "ceo",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
desiredSkills: ["paperclip"],
|
|
adapterConfig: {},
|
|
});
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(201);
|
|
const createInput = mockAgentService.create.mock.calls[0]?.[1] as {
|
|
adapterConfig: { paperclipSkillSync: { desiredSkills: string[] } };
|
|
};
|
|
const desired = createInput.adapterConfig.paperclipSkillSync.desiredSkills;
|
|
// "paperclip" resolves to its canonical key and dedupes with the default.
|
|
expect(desired).toHaveLength(5);
|
|
expect(desired).toContain("paperclipai/paperclip/paperclip");
|
|
});
|
|
|
|
it("does not add default skills to non-CEO hires", async () => {
|
|
const res = await request(await createApp(createDb(true)))
|
|
.post("/api/companies/company-1/agent-hires")
|
|
.send({
|
|
name: "QA Agent",
|
|
role: "engineer",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
adapterConfig: {},
|
|
});
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(201);
|
|
const createInput = mockAgentService.create.mock.calls[0]?.[1] as {
|
|
adapterConfig: Record<string, unknown>;
|
|
};
|
|
expect(createInput.adapterConfig.paperclipSkillSync).toBeUndefined();
|
|
});
|
|
|
|
it("rejects version pins in agent hires while beta skills are disabled", async () => {
|
|
const res = await request(await createApp(createDb(true)))
|
|
.post("/api/companies/company-1/agent-hires")
|
|
.send({
|
|
name: "QA Agent",
|
|
role: "engineer",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
desiredSkills: [{
|
|
key: "paperclipai/paperclip/paperclip",
|
|
versionId: "22222222-2222-4222-8222-222222222222",
|
|
}],
|
|
adapterConfig: {},
|
|
});
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(400);
|
|
expect(res.body.error).toContain("Beta skills experimental setting");
|
|
expect(mockAgentService.create).not.toHaveBeenCalled();
|
|
expect(mockApprovalService.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("preserves hire source issues, icons, desired skills, and approval payload details", async () => {
|
|
const db = createDb(true);
|
|
const sourceIssueId = "22222222-2222-4222-8222-222222222222";
|
|
|
|
const res = await request(await createApp(db))
|
|
.post("/api/companies/company-1/agent-hires")
|
|
.send({
|
|
name: "Security Engineer",
|
|
role: "engineer",
|
|
icon: "crown",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
desiredSkills: ["paperclip"],
|
|
adapterConfig: {},
|
|
sourceIssueId,
|
|
});
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(201);
|
|
expect(mockAgentService.create).toHaveBeenCalledWith(
|
|
"company-1",
|
|
expect.objectContaining({
|
|
icon: "crown",
|
|
adapterConfig: expect.objectContaining({
|
|
paperclipSkillSync: expect.objectContaining({
|
|
desiredSkills: ["paperclipai/paperclip/paperclip"],
|
|
}),
|
|
}),
|
|
}),
|
|
{
|
|
runnerResolved: true,
|
|
aiConnectionInstall: undefined,
|
|
createdByUserId: "local-board", responsibleUserId: "local-board",
|
|
claudeLogin: {
|
|
storedSessionId: null,
|
|
ownerUserId: "local-board",
|
|
applyExistingWithoutClaim: false,
|
|
inheritedFromAgentId: null,
|
|
},
|
|
},
|
|
);
|
|
expect(mockApprovalService.create).toHaveBeenCalledWith(
|
|
"company-1",
|
|
expect.objectContaining({
|
|
payload: expect.objectContaining({
|
|
icon: "crown",
|
|
desiredSkills: ["paperclipai/paperclip/paperclip"],
|
|
requestedConfigurationSnapshot: expect.objectContaining({
|
|
desiredSkills: ["paperclipai/paperclip/paperclip"],
|
|
}),
|
|
}),
|
|
}),
|
|
);
|
|
expect(mockIssueApprovalService.linkManyForApproval).toHaveBeenCalledWith(
|
|
"approval-1",
|
|
[sourceIssueId],
|
|
{ agentId: null, userId: "local-board" },
|
|
);
|
|
});
|
|
|
|
it("uses managed AGENTS config in hire approval payloads", async () => {
|
|
const res = await request(await createApp(createDb(true)))
|
|
.post("/api/companies/company-1/agent-hires")
|
|
.send({
|
|
name: "QA Agent",
|
|
role: "engineer",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
adapterConfig: {},
|
|
instructionsBundle: {
|
|
files: {
|
|
"AGENTS.md": "You are QA.",
|
|
},
|
|
},
|
|
});
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(201);
|
|
const approvalInput = mockApprovalService.create.mock.calls.at(-1)?.[1] as
|
|
| { payload?: { agentId?: string; adapterConfig?: Record<string, unknown> } }
|
|
| undefined;
|
|
const hiredAgentId = expectResponseId(approvalInput?.payload?.agentId);
|
|
expect(mockApprovalService.create).toHaveBeenCalledWith(
|
|
"company-1",
|
|
expect.objectContaining({
|
|
payload: expect.objectContaining({
|
|
adapterConfig: expect.objectContaining({
|
|
instructionsBundleMode: "managed",
|
|
instructionsEntryFile: "AGENTS.md",
|
|
instructionsRootPath: `/tmp/${hiredAgentId}/instructions`,
|
|
instructionsFilePath: `/tmp/${hiredAgentId}/instructions/AGENTS.md`,
|
|
}),
|
|
}),
|
|
}),
|
|
);
|
|
expect(approvalInput?.payload?.adapterConfig?.promptTemplate).toBeUndefined();
|
|
});
|
|
|
|
it("rejects legacy prompt templates for hire approval payloads", async () => {
|
|
const res = await request(await createApp(createDb(true)))
|
|
.post("/api/companies/company-1/agent-hires")
|
|
.send({
|
|
name: "QA Agent",
|
|
role: "engineer",
|
|
adapterType: "claude_local",
|
|
runner: "legacy",
|
|
adapterConfig: {
|
|
instructionsFilePath: "/tmp/existing/AGENTS.md",
|
|
promptTemplate: "You are QA.",
|
|
bootstrapPromptTemplate: "Bootstrap QA.",
|
|
},
|
|
});
|
|
|
|
expect(res.status, JSON.stringify(res.body)).toBe(422);
|
|
expect(res.body.error).toContain("New agents must use instructionsBundle/AGENTS.md");
|
|
expect(mockAgentService.create).not.toHaveBeenCalled();
|
|
expect(mockAgentInstructionsService.materializeManagedBundle).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
vi.mock("../services/agent-lifecycle.js", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("../services/agent-lifecycle.js")>();
|
|
return { ...actual, createAgentLifecycle: () => ({
|
|
requestHire: (...args: unknown[]) => mockAgentService.create(...args),
|
|
}) };
|
|
});
|