Files
PaperClipAI/server/src/modules/agent-lifecycle/__tests__/setup.test.ts
Nicky LeachandClaude Opus 5.5 c2a8821809 fix(agents): keep a prepared agent setup when its configuration changes (#23669)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A new agent can use a plugin environment that requires an agent. A
lifecycle plugin prepares that environment before the agent can work.
> - The setup flow creates a draft agent first, so that this preparation
can start before the person finishes setup.
> - Each change to the draft's harness, model, or sign-in started
preparation again. The hire also started it again.
> - Verification cannot start until the last preparation is complete. So
the early preparation did not decrease the wait after the hire.
> - This pull request keeps the preparation when the agent stays on the
same environment driver.
> - The benefit is that a person who finishes setup waits only for
verification.

## Linked Issues or Issue Description

I searched the open and closed issues and pull requests. I did not find
a duplicate.

**What happened?**

Create an agent in setup on a plugin environment that declares
`requiresAgent: true`. The draft is prepared. Then choose a harness,
sign in, and hire the agent. Each of these three steps starts
`preparing` again. The agent page shows preparation after the hire,
although the environment was ready before the person signed in.

**Expected behavior**

A change to the harness, model, credentials, or instructions does not
change the environment. It must not start preparation again. The hire
must go directly to verification. If preparation is in progress, the
hire must join it.

**Steps to reproduce**

1. Install a lifecycle plugin with an environment driver that declares
`requiresAgent: true`.
2. Make that environment the instance default.
3. Create a setup draft and wait until `lifecycleState` is `verifying`.
4. Save a different model on the draft. `lifecycleState` goes back to
`preparing`.
5. Hire the draft. `lifecycleState` goes back to `preparing` again.

**Paperclip version or commit**

`7e025ae65f`

**Deployment mode**

Self-hosted server with a plugin environment that requires an agent.

## What Changed

- A configuration change restarts `preparing` only when the agent moves
to an environment that needs setup. The existing environment and driver
check makes this decision.
- A prepared setup draft stays prepared when its harness, model,
credentials, or runtime configuration change.
- The hire of a prepared draft goes directly to `verifying` with a new
operation.
- The hire of a draft that is still `preparing` keeps the operation and
its version. Verification starts when that operation is complete.
- A hire that moves to an environment that needs setup starts
`preparing` again, as before.
- A save that changes an environment to another driver of the same
plugin now also refuses `preparing` agents, the same as `ready` and
`verifying` ones.
- A change to instructions alone does not restart verification. The hire
writes the managed instruction files immediately after it commits, and
verification does not read them.
- The hire clears an old lifecycle error on the draft.
- These behaviors do not change:
  - a draft that no longer needs preparation goes to `pausing`
  - a hire that needs approval, a hire with a hold, and a company hold
  - an edit to other execution configuration during verification
  - an edit during `resuming`
- `doc/AGENT-LIFECYCLE.md` describes the new rules.

## Verification

- `npx vitest run src/modules/agent-lifecycle`: 224 passed. Four new
tests cover a prepared draft, a hire from a prepared draft, a hire
during preparation, and an instruction change. Three of them failed
before the change. The fourth could not run because a test before it
left the fixture blocked.
- `npx vitest run` on the hire, lifecycle delivery, agent secret,
pending approval, secret binding, managed plugin environment, and plugin
task tests: all passed.
- `npx vitest run` on the two Dot onboarding files: 25 passed.
- `pnpm --filter @paperclipai/server typecheck`: passed.
- Not done: a live test with a plugin environment.

Three existing tests used an agent in `preparing` to test that a
configuration change fences verification. They now use `verifying`.

## Risks

- A lifecycle plugin that reads the agent's harness or model during
`preparing` is not called again when they change. The lifecycle request
does not carry them. Verification still tests the final configuration.
- A prepared environment can be lost between preparation and hire.
Verification then fails and retries, and a pause and resume prepares it
again. Before this change, the hire prepared it again.
- An edit during `preparing` does not cancel the attempt in progress. A
plugin must not fail because the agent's configuration changed during
its call.
- No migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with
extended thinking, tool use and code 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 15:55:56 -08:00

258 lines
18 KiB
TypeScript

import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { eq } from "drizzle-orm";
import { agents, companies, companyMemberships, principalPermissionGrants, environments, plugins, createDb, type Db } from "@paperclipai/db";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
import { createAgentLifecycle, configureAgentLifecycle, createAgentLifecycleEffects } from "../../../services/agent-lifecycle.js";
import { agentService as agentConfiguration } from "../../../services/agents.js";
import { createLifecycleDriver } from "../../../services/agent-lifecycle-driver.js";
import { agentRoutes } from "../../../routes/agents.js";
import { errorHandler } from "../../../middleware/error-handler.js";
import { createLifecycleStore as createStore } from "../adapters/postgres.js";
import type { LifecycleAgent, LifecycleDriver } from "../application/ports.js";
const createLifecycleStore = (db: Db) => createStore(db, createAgentLifecycleEffects());
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("agent setup lifecycle", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
let companyId: string;
const workers: ReturnType<typeof configureAgentLifecycle>[] = [];
const releases: (() => void)[] = [];
beforeAll(async () => { database = await startEmbeddedPostgresTestDatabase("paperclip-agent-setup-"); db = createDb(database.connectionString); }, 90_000);
afterEach(() => { for (const release of releases.splice(0)) release(); });
afterAll(async () => { for (const work of workers) await work.stop(); await database?.cleanup(); });
beforeEach(async () => {
for (const work of workers) await work.stop();
companyId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Setup test", issuePrefix: `S${companyId.slice(0, 7)}` });
});
function worker(runHost: LifecycleDriver["runHost"] = async () => "complete") {
const work = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost });
workers.push(work); return work;
}
async function current(id: string) { return (await db.select().from(agents).where(eq(agents.id, id)))[0]!; }
it("keeps early setup inactive and completes the same record without renaming it", async () => {
const runHost = vi.fn(async () => "complete" as const);
const work = worker(runHost);
const lifecycle = createAgentLifecycle(db);
const id = randomUUID();
const input = { id, name: "Early agent", adapterType: "process" };
const first = await lifecycle.requestHire(companyId, input, { setupOnly: true });
const retry = await lifecycle.requestHire(companyId, input, { setupOnly: true });
expect(first.id).toBe(id);
expect(retry.id).toBe(id);
await work.process(id);
expect(runHost).not.toHaveBeenCalled();
expect(await current(id)).toMatchObject({ status: "paused", lifecycleState: "paused", lifecycleHolds: ["setup"] });
expect(await db.select().from(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, id))).toHaveLength(0);
await expect(agentConfiguration(db).createApiKey(id, "Incomplete setup")).rejects.toThrow("Finish agent setup");
await expect(lifecycle.resumeAgent(id)).rejects.toThrow("Finish agent setup");
const finished = await lifecycle.requestHire(companyId, { id, name: "Early agent", adapterType: "process", status: "idle" }, { setupAgentId: id });
expect(finished).toMatchObject({ id, name: "Early agent" });
await work.process(id);
expect(await current(id)).toMatchObject({ status: "idle", lifecycleState: "ready", lifecycleHolds: [] });
expect(await db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(1);
await expect(lifecycle.requestHire(companyId, { id, name: "Early agent" }, { setupAgentId: id })).rejects.toThrow("no longer available");
});
async function agentEnvironment(hold?: () => Promise<unknown>) {
const pluginId = randomUUID(), environmentId = randomUUID();
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "agent-environment-test", version: "1.0.0", status: "ready",
manifestJson: { agentLifecycle: true, capabilities: ["agents.lifecycle.manage", "environment.drivers.register"],
environmentDrivers: ["tasks", "desktop"].map(driverKey => ({ driverKey, requiresAgent: true, supportsTasks: true })) } as never });
const environment = async (id: string, driverKey: string) => {
await db.insert(environments).values({ id, name: `Agent-owned ${id}`, driver: "plugin", status: "active",
config: { pluginKey: pluginId, driverKey, driverConfig: {} } });
return id;
};
await environment(environmentId, "tasks");
const call = vi.fn(async (_id, _method, input) => {
if (input.phase === "preparing") await hold?.();
return { operationId: input.operationId, version: input.version, status: "complete" };
});
const runHost = vi.fn<LifecycleDriver["runHost"]>(async () => "complete");
const driver = createLifecycleDriver(db, { call } as never);
const work = configureAgentLifecycle(db, { ...driver, runHost });
workers.push(work);
const phases = () => call.mock.calls.map(([, , request]) => request.phase);
return { pluginId, environmentId, environment, call, runHost, work, phases };
}
it("prepares agent-dependent drafts, stays idle until finish, and invalidates changed environments", async () => {
const { environmentId, call, runHost, work } = await agentEnvironment();
const lifecycle = createAgentLifecycle(db);
const id = randomUUID();
const input = { id, name: "Early computer", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId };
const draft = await lifecycle.requestHire(companyId, input, { setupOnly: true, runnerResolved: true });
expect(draft).toMatchObject({ lifecycleState: "preparing", status: "paused", pauseReason: "setup" });
await work.process(id);
expect(await current(id)).toMatchObject({ lifecycleState: "verifying", status: "paused", lifecycleHolds: ["setup"] });
expect(call.mock.calls.map(([, , request]) => request.phase)).toEqual(["preparing"]);
const store = createLifecycleStore(db);
expect(await store.pending(100, new Date())).not.toContain(id);
expect(await store.claim(id, "unexpected", new Date())).toBeNull();
await work.process(id);
expect(runHost).toHaveBeenCalledTimes(1);
await expect(agentConfiguration(db).createApiKey(id, "Incomplete computer")).rejects.toThrow("Finish agent setup");
await expect(lifecycle.resumeAgent(id)).rejects.toThrow("Finish agent setup");
await lifecycle.pauseAgent(id, "budget"); await work.process(id);
expect(await current(id)).toMatchObject({ lifecycleState: "paused", lifecycleHolds: ["setup", "budget"] });
await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "codex", model: "changed" } });
expect((await current(id)).lifecycleState).toBe("paused");
await store.change(id, "reconcile"); await work.process(id);
expect(await current(id)).toMatchObject({ lifecycleState: "verifying", lifecycleHolds: ["setup"] });
await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "codex", model: "prepared" } });
await work.process(id);
expect((await current(id)).lifecycleState).toBe("verifying");
const [local] = await db.select().from(environments).where(eq(environments.driver, "local"));
await lifecycle.updateConfiguration(id, { defaultEnvironmentId: local.id }); await work.process(id);
expect((await current(id)).lifecycleState).toBe("paused");
await lifecycle.updateConfiguration(id, { defaultEnvironmentId: environmentId }); await work.process(id);
expect((await current(id)).lifecycleState).toBe("verifying");
await lifecycle.updateConfiguration(id, { defaultEnvironmentId: local.id });
expect((await current(id)).lifecycleState).toBe("pausing");
await lifecycle.updateConfiguration(id, { defaultEnvironmentId: environmentId });
await work.process(id);
expect((await current(id)).lifecycleState).toBe("verifying");
const finished = await lifecycle.requestHire(companyId, input, { setupAgentId: id, runnerResolved: true });
expect(finished.id).toBe(id);
await work.process(id);
expect(await current(id)).toMatchObject({ lifecycleState: "ready", lifecycleHolds: [] });
expect(call.mock.calls.map(([, , request]) => request.phase).at(-1)).toBe("verifying");
});
it("does not prepare agent-owned resources before required hire approval", async () => {
const pluginId = randomUUID(), environmentId = randomUUID();
await db.update(companies).set({ requireBoardApprovalForNewAgents: true }).where(eq(companies.id, companyId));
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "approval-computer-test", version: "1.0.0", status: "ready",
manifestJson: { agentLifecycle: true, capabilities: ["agents.lifecycle.manage", "environment.drivers.register"],
environmentDrivers: [{ driverKey: "tasks", requiresAgent: true, supportsTasks: true }] } as never });
await db.insert(environments).values({ id: environmentId, name: "Approval computer", driver: "plugin", status: "active",
config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } });
const runHost = vi.fn(async () => "complete" as const);
const work = worker(runHost);
const lifecycle = createAgentLifecycle(db);
const draft = await lifecycle.requestHire(companyId, { name: "Unapproved computer", adapterType: "paperclip_runner",
adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId }, { setupOnly: true, runnerResolved: true });
await work.process(draft.id);
await lifecycle.updateConfiguration(draft.id, { adapterConfig: { provider: "codex", model: "changed" } });
await work.process(draft.id);
expect(await current(draft.id)).toMatchObject({ lifecycleState: "paused", lifecycleHolds: ["setup"] });
expect(runHost).not.toHaveBeenCalled();
});
it("keeps a prepared draft prepared while its harness, model, sign-in and instructions change", async () => {
const { environmentId, environment, work, phases } = await agentEnvironment();
const lifecycle = createAgentLifecycle(db);
const id = randomUUID();
await lifecycle.requestHire(companyId, { id, name: "Prepared", adapterType: "paperclip_runner",
adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId }, { setupOnly: true, runnerResolved: true });
await work.process(id);
const prepared = await current(id);
expect(prepared.lifecycleState).toBe("verifying");
await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "claude", model: "changed", env: { TOKEN: { type: "plain", value: "saved" } } } });
await lifecycle.updateConfiguration(id, { runtimeConfig: { heartbeat: { enabled: false } } });
await lifecycle.updateConfiguration(id, { defaultEnvironmentId: await environment(randomUUID(), "tasks") });
await work.process(id);
expect(await current(id)).toMatchObject({ lifecycleState: "verifying", lifecycleVersion: prepared.lifecycleVersion,
lifecycleOperation: { id: prepared.lifecycleOperation!.id } });
expect(phases()).toEqual(["preparing"]);
await lifecycle.updateConfiguration(id, { defaultEnvironmentId: await environment(randomUUID(), "desktop") });
expect((await current(id)).lifecycleState).toBe("preparing");
await work.process(id);
expect(phases()).toEqual(["preparing", "preparing"]);
expect((await current(id)).lifecycleState).toBe("verifying");
});
it("verifies a prepared draft at hire without preparing it again", async () => {
const { environmentId, environment, work, phases } = await agentEnvironment();
const lifecycle = createAgentLifecycle(db);
const hire = async (finalEnvironmentId: string) => {
const id = randomUUID();
const input = { id, name: "Hired", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId };
await lifecycle.requestHire(companyId, input, { setupOnly: true, runnerResolved: true });
await work.process(id);
const prepared = await current(id);
await lifecycle.requestHire(companyId, { ...input, adapterConfig: { provider: "claude", model: "chosen" }, status: "idle",
defaultEnvironmentId: finalEnvironmentId }, { setupAgentId: id, runnerResolved: true, responsibleUserId: "owner" });
return { prepared, hired: await current(id) };
};
const same = await hire(environmentId);
expect(same.hired).toMatchObject({ lifecycleState: "verifying", lifecycleHolds: [], lifecycleOperation: { responsibleUserId: "owner" } });
expect(same.hired.lifecycleVersion).toBeGreaterThan(same.prepared.lifecycleVersion);
expect(same.hired.lifecycleOperation!.id).not.toBe(same.prepared.lifecycleOperation!.id);
await work.process(same.hired.id);
expect((await current(same.hired.id)).lifecycleState).toBe("ready");
expect(phases()).toEqual(["preparing", "verifying"]);
expect((await hire(await environment(randomUUID(), "desktop"))).hired.lifecycleState).toBe("preparing");
});
it("joins the preparation in progress when a draft is edited and hired", async () => {
let entered!: () => void, release!: () => void;
const started = new Promise<void>(resolve => { entered = resolve; });
const held = new Promise<void>(resolve => { release = resolve; });
const { environmentId, work, phases } = await agentEnvironment(() => { entered(); return held; });
releases.push(release);
const lifecycle = createAgentLifecycle(db);
const id = randomUUID();
const input = { id, name: "Joined", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId };
await lifecycle.requestHire(companyId, input, { setupOnly: true, runnerResolved: true });
const processing = work.process(id);
await started;
const preparing = await current(id);
await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "claude" } });
await lifecycle.requestHire(companyId, { ...input, adapterConfig: { provider: "claude" }, status: "idle" },
{ setupAgentId: id, runnerResolved: true, responsibleUserId: "owner" });
expect(await current(id)).toMatchObject({ lifecycleState: "preparing", lifecycleHolds: [], lifecycleVersion: preparing.lifecycleVersion,
lifecycleOperation: { id: preparing.lifecycleOperation!.id, leaseOwner: preparing.lifecycleOperation!.leaseOwner, responsibleUserId: "owner" } });
release();
await processing;
expect(await current(id)).toMatchObject({ lifecycleState: "ready", lifecycleHolds: [], lifecycleOperation: { responsibleUserId: "owner" } });
expect(phases()).toEqual(["preparing", "verifying"]);
});
it("keeps a running verification when only instructions change", async () => {
const { environmentId, work } = await agentEnvironment();
const lifecycle = createAgentLifecycle(db);
const id = randomUUID();
await lifecycle.requestHire(companyId, { id, name: "Verified", adapterType: "paperclip_runner",
adapterConfig: { provider: "codex", promptTemplate: "Old" }, defaultEnvironmentId: environmentId, status: "idle" }, { runnerResolved: true });
await db.update(agents).set({ lifecycleState: "verifying" }).where(eq(agents.id, id));
const verifying = await current(id);
await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "codex", instructionsBundleMode: "managed",
instructionsRootPath: "/managed", instructionsEntryFile: "AGENTS.md", instructionsFilePath: "/managed/AGENTS.md" } });
expect(await current(id)).toMatchObject({ lifecycleVersion: verifying.lifecycleVersion,
adapterConfig: { instructionsFilePath: "/managed/AGENTS.md" }, lifecycleOperation: { id: verifying.lifecycleOperation!.id } });
await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "codex", model: "changed" } });
expect((await current(id)).lifecycleVersion).toBe(verifying.lifecycleVersion + 1);
});
it("lets only the setup creator configure and retry a stopping draft with creation permission", async () => {
await db.insert(companyMemberships).values(["setup-owner", "setup-other"].map(principalId => ({ companyId,
principalType: "user", principalId, membershipRole: "member" })));
await db.insert(principalPermissionGrants).values(["setup-owner", "setup-other"].map(principalId => ({ companyId,
principalType: "user", principalId, permissionKey: "agents:create" })));
const lifecycle = createAgentLifecycle(db);
const draft = await lifecycle.requestHire(companyId, { name: "Stopping setup", adapterType: "process" },
{ setupOnly: true, createdByUserId: "setup-owner" });
await db.update(agents).set({ lifecycleState: "pausing" }).where(eq(agents.id, draft.id));
function app(userId: string) {
const value = express(); value.use(express.json());
value.use((req, _res, next) => { req.actor = { type: "board", source: "session", userId,
companyIds: [companyId], memberships: [{ companyId, membershipRole: "member", status: "active" }] }; next(); });
value.use("/api", agentRoutes(db)); value.use(errorHandler); return value;
}
const updated = await request(app("setup-owner")).patch(`/api/agents/${draft.id}`).send({ runtimeConfig: { heartbeat: { enabled: false } } });
expect(updated.status, JSON.stringify(updated.body)).toBe(200);
await request(app("setup-owner")).post(`/api/agents/${draft.id}/lifecycle/retry`).send({}).expect(200);
await request(app("setup-other")).patch(`/api/agents/${draft.id}`).send({ runtimeConfig: { heartbeat: { enabled: true } } }).expect(403);
await request(app("setup-other")).post(`/api/agents/${draft.id}/lifecycle/retry`).send({}).expect(403);
await expect(lifecycle.requestHire(companyId, { name: draft.name }, { setupAgentId: draft.id })).rejects.toThrow("no longer available");
expect((await current(draft.id)).lifecycleState).toBe("pausing");
});
});