Files
PaperClipAI/server/src/__tests__/agent-harness-verification-provider-api.test.ts
T
Nicky LeachandPaperclip cc2e1d9d43 Honor plugin task driver concurrency defaults on hire (#23535)
## Thinking Path

> - Paperclip schedules work for agents.
> - Each agent has a limit on simultaneous runs.
> - A task driver can provide an execution environment with its own
capacity.
> - Previously the creation form sent the same limit for every driver.
> - A driver can now declare the value Core saves when a new agent has
no explicit limit.

## Linked Issues or Issue Description

**Subsystem affected**

Agent hiring and plugin environment drivers.

**Current behavior**

The create form, API, and import flow supply the global concurrency
default before the task driver can provide one.

**Proposed behavior**

Let each task driver declare an optional per-agent concurrency default.
Apply it once during hire and honor explicit agent limits.

## What Changed

- Refreshed the three SDK source pins for the changed files.
- Added the optional driver field `defaultMaxConcurrentRuns` with
integer bounds from 1 through 50.
- Applied it during hire using the resolved task environment. Saved the
resolved runtime configuration in hire approvals.
- Removed early defaults from the creation form, routes and new-agent
imports. Preserved saved limits on export, including explicit values
equal to the global default. Kept the current limit when importing an
update with an omitted limit.

## Verification

- [Full PR
CI](https://github.com/paperclipai/paperclip/actions/runs/47000023360)
passed on `83cce42b9a`. Server shard 16 passed on retry after a
PostgreSQL connection reset on the first attempt.
- `pnpm -r typecheck` passed. The SDK source pin check passed. `pnpm
verify` selected broad CI coverage because the SDK input registry
changed.
- On rebased commit `83cce42b9a`, all 441 tests in six focused Vitest
suites passed, including the MCP rollback test corrected in #23560. The
SDK source pin check passed.

## Risks

This affects new hires on drivers that opt in. Existing agents retain
their saved configuration. Single-run provider limits still apply. An
older client that explicitly sends the global default will keep that
value.

## Model Used

OpenAI GPT-6 via Codex. Used local source inspection, code editing,
TypeScript and test execution.

## 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>
2026-12-02 16:23:42 -08:00

166 lines
11 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { eq, sql } from "drizzle-orm";
import { agents, companies, createDb, applyPendingMigrations, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS,
environments, environmentLeases, executionWorkspaces, heartbeatRuns, plugins, type Db } from "@paperclipai/db";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { requireServerAdapter } from "../adapters/index.js";
import { agentHarnessVerificationService } from "../services/agent-harness-verification.js";
import { createAgentLifecycle, configureAgentLifecycle } from "../services/agent-lifecycle.js";
import { createLifecycleDriver } from "../services/agent-lifecycle-driver.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { environmentService } from "../services/environments.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
const externalDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_PROVIDER_API_LIFECYCLE_TEST_DATABASE_URL");
const support = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
describe.skipIf(!support.supported)("Cursor Cloud API controller activation", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
let home: string;
let companyId: string;
const workers: ReturnType<typeof configureAgentLifecycle>[] = [];
const config = { provider: "cursor_cloud", model: "caller-model", repoUrl: "https://github.com/example/qualification",
lifecycleMode: "per_turn", env: { CURSOR_API_KEY: "synthetic-cursor-key" } };
const fetch = vi.fn(async (input: unknown, init?: RequestInit) => {
const url = String(input);
if (url.startsWith("https://callback.example.test/mcp/native-runs/") && init?.method === "POST") return new Response(null, { status: 401 });
if (url === "https://api.cursor.com/v1/models" && init?.method === "GET") return new Response(JSON.stringify({ items: [{ id: config.model, displayName: "Caller model" }] }), { headers: { "Content-Type": "application/json" } });
throw new Error(`Unexpected provider request: ${init?.method} ${url}`);
});
beforeAll(async () => {
home = await mkdtemp(join(tmpdir(), "paperclip-provider-api-lifecycle-"));
vi.stubEnv("PAPERCLIP_HOME", home);
vi.stubEnv("PAPERCLIP_MANAGED_CONFIG", undefined);
vi.stubEnv("PAPERCLIP_SETTING_DEFAULTS", undefined);
vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://callback.example.test");
if (externalDatabaseUrl) await applyPendingMigrations(externalDatabaseUrl);
database = externalDatabaseUrl ? { connectionString: externalDatabaseUrl, cleanup: async () => {} }
: await startEmbeddedPostgresTestDatabase("paperclip-provider-api-lifecycle-");
db = createDb(database.connectionString);
await db.execute(sql`set client_min_messages = warning`);
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
beforeEach(async () => {
for (const worker of workers) await worker.stop();
await instanceSettingsService(db).update({ defaultEnvironmentId: null });
await db.execute(sql`truncate table companies, plugins, environments restart identity cascade`);
await instanceSettingsService(db).updateGeneral({ executionMode: "any" });
await instanceSettingsService(db).updateExperimental({ enableManagedSandboxOnly: true, enableNativeRunner: true });
[companyId] = await db.insert(companies).values({ name: "API controller activation", issuePrefix: "API" }).returning({ id: companies.id }).then(rows => rows.map(row => row.id));
fetch.mockClear();
vi.stubGlobal("fetch", fetch);
});
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
afterAll(async () => {
for (const worker of workers) await worker.stop();
await db?.$client.end();
await database?.cleanup();
vi.unstubAllEnvs();
if (home) await rm(home, { recursive: true, force: true });
});
const current = (id: string) => db.select().from(agents).where(eq(agents.id, id)).then(rows => rows[0]!);
async function saved(adapterType = "paperclip_runner", adapterConfig = config) {
return (await db.insert(agents).values({ companyId, name: "Saved controller", adapterType, adapterConfig,
status: "paused", lifecycleState: "verifying" }).returning())[0]!;
}
async function noComputerWork() {
expect(await db.select().from(environmentLeases)).toHaveLength(0);
expect(await db.select().from(executionWorkspaces)).toHaveLength(0);
expect(await db.select().from(heartbeatRuns)).toHaveLength(0);
}
it.each([false, true])("finishes the same held draft and reaches Ready with an experimental account WARN, inherited plugin Computer=%s", async defaultComputer => {
if (defaultComputer) {
const pluginId = randomUUID();
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "unneeded-computer", version: "1.0.0", status: "ready",
manifestJson: { capabilities: ["environment.drivers.register"], environmentDrivers: [{ driverKey: "tasks", requiresAgent: true, supportsTasks: true, warmTaskVersion: 1 }] } as never });
const [computer] = await db.insert(environments).values({ name: "Inherited Computer", driver: "plugin", status: "active",
config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } }).returning();
await instanceSettingsService(db).update({ defaultEnvironmentId: computer.id });
}
expect(await environmentService(db).findManagedSandboxEnvironment(companyId)).toBeNull();
const lifecycle = createAgentLifecycle(db);
const draft = await lifecycle.requestHire(companyId, { name: "Cursor setup", adapterType: "paperclip_runner",
adapterConfig: { provider: "cursor_cloud" } }, { setupOnly: true, runnerResolved: true });
expect(draft).toMatchObject({ status: "paused", lifecycleState: "paused", lifecycleHolds: ["setup"], defaultEnvironmentId: null });
await lifecycle.updateConfiguration(draft.id, { adapterConfig: config, runtimeConfig: { heartbeat: { enabled: false } } });
expect(await current(draft.id)).toMatchObject({ lifecycleState: "paused", lifecycleHolds: ["setup"] });
const finished = await lifecycle.requestHire(companyId, { id: draft.id, name: draft.name, adapterType: "paperclip_runner",
adapterConfig: config, runtimeConfig: { heartbeat: { enabled: false } }, defaultEnvironmentId: null }, { setupAgentId: draft.id, runnerResolved: true });
expect(finished.id).toBe(draft.id);
expect(finished.adapterConfig.lifecycleMode).toBe("per_turn");
const probe = vi.spyOn(requireServerAdapter("paperclip_runner"), "testEnvironment");
const driver = createLifecycleDriver(db, {} as never);
const worker = configureAgentLifecycle(db, driver);
workers.push(worker);
await worker.process(draft.id);
expect(await current(draft.id)).toMatchObject({ status: "idle", lifecycleState: "ready", lifecycleHolds: [], defaultEnvironmentId: null });
expect(probe).toHaveBeenCalledOnce();
expect(await probe.mock.results[0]!.value).toMatchObject({ status: "warn", checks: [
{ code: "cursor_cloud_account_ready", level: "info" },
{ code: "cursor_cloud_model_listed", level: "info" },
{ code: "cursor_cloud_model_identity_unverified", level: "warn" },
] });
expect(fetch.mock.calls.map(([url, input]) => [String(url), input?.method])).toEqual([
["https://callback.example.test/mcp/native-runs/00000000-0000-4000-8000-000000000000", "POST"],
["https://api.cursor.com/v1/models", "GET"],
]);
await noComputerWork();
});
it.each([undefined, 7, 20])("applies Computer hire defaults with explicit concurrency %s", async maxConcurrentRuns => {
const pluginId = randomUUID();
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "required-computer", version: "1.0.0", status: "ready",
manifestJson: { capabilities: ["environment.drivers.register"], environmentDrivers: [{ driverKey: "tasks", requiresAgent: true, supportsTasks: true, warmTaskVersion: 1, defaultMaxConcurrentRuns: 2 }] } as never });
const [computer] = await db.insert(environments).values({ name: "Required Computer", driver: "plugin", status: "active",
config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } }).returning();
await instanceSettingsService(db).update({ defaultEnvironmentId: computer.id });
const draft = await createAgentLifecycle(db).requestHire(companyId, { name: "Codex setup", adapterType: "paperclip_runner", runtimeConfig: { heartbeat: { maxConcurrentRuns } },
adapterConfig: { provider: "codex", model: "gpt-5.6-luna", lifecycleMode: "per_turn" } }, { setupOnly: true, runnerResolved: true });
expect(draft).toMatchObject({ status: "paused", lifecycleState: "preparing", lifecycleHolds: ["setup"], adapterConfig: { lifecycleMode: "warm" } });
expect(draft.runtimeConfig.heartbeat).toMatchObject({ maxConcurrentRuns: maxConcurrentRuns ?? 2 });
expect(fetch).not.toHaveBeenCalled();
await noComputerWork();
});
it("verifies a saved native controller without resolving an unavailable managed Computer", async () => {
const agent = await saved();
await expect(agentHarnessVerificationService(db, {} as never).verify(agent)).resolves.toBe("complete");
expect(fetch).toHaveBeenCalledTimes(2);
await noComputerWork();
});
it("rejects Kubernetes-only activation before any provider probe", async () => {
const agent = await saved();
await instanceSettingsService(db).updateGeneral({ executionMode: "kubernetes" });
await expect(agentHarnessVerificationService(db, {} as never).verify(agent)).rejects.toMatchObject({
status: 422, details: { code: "provider_api_kubernetes_execution_unsupported" },
});
await expect(createAgentLifecycle(db).requestHire(companyId, { name: "Forbidden hire", adapterType: "paperclip_runner", adapterConfig: config }, { runnerResolved: true }))
.rejects.toMatchObject({ status: 422, details: { code: "provider_api_kubernetes_execution_unsupported" } });
expect(fetch).not.toHaveBeenCalled();
await noComputerWork();
});
it("does not grant API placement to an incomplete active profile", async () => {
const agent = await saved("paperclip_runner", { ...config, model: "" });
await expect(agentHarnessVerificationService(db, {} as never).verify(agent)).rejects.toMatchObject({ code: "paperclip_runner_cursor_cloud_model_required" });
expect(fetch).not.toHaveBeenCalled();
await noComputerWork();
});
it.each(["opencode_local", "cursor_cloud"])("preserves the managed Computer requirement for %s", async adapterType => {
const agent = await saved(adapterType);
await expect(agentHarnessVerificationService(db, {} as never).verify(agent)).rejects.toMatchObject({ details: { code: "managed_sandbox_unavailable" } });
expect(fetch).not.toHaveBeenCalled();
await noComputerWork();
});
});