From ca2107583786f80800be3a895edaa33e21204b73 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:12:34 -0600 Subject: [PATCH] test(server): fold tiny purge suites into the agent lifecycle owner suite (#23719) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The agent lifecycle module owns agent purge and company deletion. > - The repository test budget rule asks to add a narrow database case to the owning suite, not to a small standalone file. > - Two small test files each start their own embedded Postgres for a few purge cases only. > - This pull request moves those cases into the agent lifecycle owner suite and deletes the two small files. > - The benefit is two fewer test workers and two fewer database setups in CI, with the same assertions kept. ## Linked Issues or Issue Description No public GitHub issue exists for this change. The problem is described here, using the enhancement template labels. **What existing behavior does this improve?** The layout of the agent lifecycle test suites and their CI setup cost. **Subsystem affected** server/ — REST API & orchestration services (agent lifecycle and company deletion tests). **Current behavior** Two test files each boot an own embedded Postgres for a few purge cases: - `server/src/services/agent-cost-history-deletion.test.ts` (61 lines) covers the `agent_cost_history_retained` purge guard. - `server/src/services/case-deletion.test.ts` (69 lines) covers company deletion with retained case handoffs and the `agent_case_history_retained` purge guard. Each file pays a separate Vitest worker import and a separate embedded database start. The `rules/test-budget.mdc` rule says: do not keep a standalone embedded-Postgres file for one narrow regression case; add the case to the owning service suite. The owner suite `server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts` already imports the same production modules (`createAgentLifecycle`, `deleteCompany`) and uses the same database fixture. **Proposed behavior** The owner suite holds these cases inside two nested describe blocks. The two small files no longer exist. No assertion changed. **Reason and benefit** CI runs two fewer standalone database files in the general server lane. The moved cases reuse the database the owner suite already started. The historical duration manifest recorded about 6 s and 8 s per file at its recorded revision; these weights are scheduling estimates, not measured savings for this change. **Breaking changes** None. Test code only. ## What Changed - Moved 4 purge cost-history cases (cost event by run, cost event by agent, finance event by run, and the positive purge case) into the owner suite under `describe("agent purge with retained cost history")`. - Moved 3 company-deletion-with-case-handoff cases (an `it.each` over three handoff states, an `it.each` over source and target roles, and the unrelated-agent purge case; 6 test registrations in total) into the owner suite under `describe("deletion with retained case handoffs")`. - Deleted `server/src/services/agent-cost-history-deletion.test.ts` and `server/src/services/case-deletion.test.ts`. - Added the `cases`, `caseAccessSources`, `caseHandoffs`, `costEvents`, and `financeEvents` table imports to the owner suite. - Net change: 131 deleted and 102 added test lines. No production line changed. The owner suite is a test file and was already longer than 1,000 lines before this change. Extending the designated owner suite is the remedy the test budget rule names for these files. ## Verification Commands run on this branch (head `01bc9384`), local sandbox, Node v25.9.0: - `cd server && ../../node_modules/.bin/vitest run src/modules/agent-lifecycle/__tests__/lifecycle.test.ts` — 1 file passed, 86 tests passed, all 10 moved registrations included. - Intended-failure control 1: the `agent_cost_history_retained` guard in `server/src/services/agent-deletion.ts` was disabled for a moment. The 3 moved cost-history cases failed on their expected 409 conflict. The positive purge case still passed. The file was then restored with `git checkout` and the diff was checked clean. - Intended-failure control 2: the `agent_case_history_retained` guard was disabled the same way. The 2 moved handoff purge cases failed on their expected 409 conflict. The other matched cases still passed. The file was restored the same way. - `node scripts/check-test-budget.mjs --files server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts` — PASS. - The full owner suite was run again after the restorations: 86 tests passed. Not run locally: the repository typecheck and the full test suite. The runner build dependency for the typecheck did not fit the free disk of this sandbox. The required CI checks passed on the PR head `01bc9384`: 68 checks succeeded (typecheck, build, all 20 general server test shards, chat and workspaces-b shards, runner support, Greptile). Six conditional lanes were skipped as not applicable. Three independent bot reviews scored the change 5/5 with no findings. ## Risks - Low risk. Test files only; no production code changed. - The moved cases now share the database instance the owner suite starts. Each moved case still creates its own rows with fresh identifiers, and the controls above show each case still fails at its own guard. - The general server shard durations manifest still lists the two deleted files. The manifest is regenerated from CI runs by `scripts/ci/refresh-test-durations.mjs`; stale entries do not route work. ## Model Used GLM 5.3 (z-ai/glm-5.3; exact model ID `openrouter/z-ai/glm-5.3`), run by the Paperclip Test Gardener agent, with tool use and code execution. No extended thinking mode. ## 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 --- .../__tests__/lifecycle.test.ts | 103 +++++++++++++++++- .../agent-cost-history-deletion.test.ts | 61 ----------- server/src/services/case-deletion.test.ts | 69 ------------ 3 files changed, 102 insertions(+), 131 deletions(-) delete mode 100644 server/src/services/agent-cost-history-deletion.test.ts delete mode 100644 server/src/services/case-deletion.test.ts diff --git a/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts b/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts index c03a63a7421..82ca28eaa79 100644 --- a/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts +++ b/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts @@ -19,7 +19,7 @@ import { errorHandler } from "../../../middleware/error-handler.js"; import { createLifecycleDriver } from "../../../services/agent-lifecycle-driver.js"; import { randomUUID } from "node:crypto"; import { and, eq, sql } from "drizzle-orm"; -import { agents, approvals, projects, issues, heartbeatRuns, nativeRunFinalizations, budgetPolicies, environmentLeases, environments, agentApiKeys, activityLog, agentConfigRevisions, userCompanyPreferences, companies, companyMemberships, principalPermissionGrants, plugins, pluginCompanySettings, applyPendingMigrations, closeRegisteredClients, createDb, type Db } from "@paperclipai/db"; +import { agents, approvals, caseAccessSources, caseHandoffs, cases, costEvents, financeEvents, projects, issues, heartbeatRuns, nativeRunFinalizations, budgetPolicies, environmentLeases, environments, agentApiKeys, activityLog, agentConfigRevisions, userCompanyPreferences, companies, companyMemberships, principalPermissionGrants, plugins, pluginCompanySettings, applyPendingMigrations, closeRegisteredClients, createDb, type Db } from "@paperclipai/db"; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; import { createAgentLifecycle, configureAgentLifecycle, startAgentLifecycle } from "../../../services/agent-lifecycle.js"; @@ -615,6 +615,107 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu expect(await db.select().from(agentApiKeys).where(eq(agentApiKeys.id, key.id))).toHaveLength(1); }); + describe("agent purge with retained cost history", () => { + async function costFixture() { + const companyId = randomUUID(), agentId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Cost deletion", issuePrefix: `C${companyId.slice(0, 6)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Billed worker", status: "terminated", lifecycleState: "terminated" }); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded" }).returning(); + return { companyId, agentId, run: run! }; + } + const cost = (companyId: string, values: Partial) => db.insert(costEvents).values({ + companyId, usageKind: "decision", provider: "anthropic", model: "claude", costCents: 1, occurredAt: new Date(), ...values, + }).returning(); + + async function expectRetained(f: Awaited>) { + await expect(createAgentLifecycle(db).purgeAgent(f.agentId)).rejects.toMatchObject({ status: 409, + details: { code: "agent_cost_history_retained" } }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id))).toHaveLength(1); + expect(await db.select().from(agents).where(eq(agents.id, f.agentId))).toMatchObject([{ lifecycleState: "terminated" }]); + } + + it("refuses before cleanup when a cost event references one of the agent's runs", async () => { + const f = await costFixture(); + const [event] = await cost(f.companyId, { heartbeatRunId: f.run.id }); + await expectRetained(f); + expect(await db.select().from(costEvents).where(eq(costEvents.id, event!.id))).toEqual([event]); + }); + + it("refuses when a cost event is attributed to the agent", async () => { + const f = await costFixture(); + await cost(f.companyId, { usageKind: "agent", agentId: f.agentId }); + await expectRetained(f); + }); + + it("refuses when a finance event references one of the agent's runs", async () => { + const f = await costFixture(); + const [event] = await db.insert(financeEvents).values({ companyId: f.companyId, heartbeatRunId: f.run.id, + eventKind: "usage", biller: "anthropic", amountCents: 1, occurredAt: new Date() }).returning(); + await expectRetained(f); + expect(await db.select().from(financeEvents).where(eq(financeEvents.id, event!.id))).toEqual([event]); + }); + + it("still purges an agent whose runs have no cost history", async () => { + const f = await costFixture(); + expect(await createAgentLifecycle(db).purgeAgent(f.agentId)).toMatchObject({ id: f.agentId }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id))).toHaveLength(0); + }); + }); + + describe("deletion with retained case handoffs", () => { + async function caseFixture(state: "delivered" | "cancelled" | "pending_dispatch" = "delivered") { + const companyId = randomUUID(), sourceId = randomUUID(), targetId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Case deletion", issuePrefix: `D${companyId.slice(0, 6)}` }); + await db.insert(agents).values([sourceId, targetId].map(id => ({ id, companyId, + name: "Retained worker", status: "terminated", lifecycleState: "terminated" as const }))); + const [issue] = await db.insert(issues).values({ companyId, title: "Workflow task", status: "todo", + assigneeAgentId: targetId }).returning(); + const [record] = await db.insert(cases).values({ companyId, caseNumber: 1, identifier: `D${companyId}-C1`, + caseType: "deletion", title: "Workflow record", workIssueId: issue!.id }).returning(); + await db.insert(caseAccessSources).values({ companyId, caseId: record!.id, sourceKind: "issue", sourceId: issue!.id }); + const [handoff] = await db.insert(caseHandoffs).values({ companyId, caseId: record!.id, issueId: issue!.id, + version: 1, fromAgentId: sourceId, toAgentId: targetId, phase: "verification", instructions: "Retain this history", + actorType: "user", actorId: "board", wakeupRequestId: randomUUID(), idempotencyKey: randomUUID(), + inputFingerprint: "fixture", state }).returning(); + return { companyId, sourceId, targetId, issue: issue!, record: record!, handoff: handoff! }; + } + + it.each(["delivered", "cancelled", "pending_dispatch"] as const)("deletes the whole company with a %s handoff", async state => { + const f = await caseFixture(state), other = await caseFixture(); + + expect(await deleteCompany(db, f.companyId)).toMatchObject({ id: f.companyId }); + + expect(await db.select().from(companies).where(eq(companies.id, f.companyId))).toHaveLength(0); + expect(await db.select().from(cases).where(eq(cases.id, f.record.id))).toHaveLength(0); + expect(await db.select().from(caseHandoffs).where(eq(caseHandoffs.id, f.handoff.id))).toHaveLength(0); + expect(await db.select().from(caseAccessSources).where(eq(caseAccessSources.caseId, f.record.id))).toHaveLength(0); + expect(await db.select().from(issues).where(eq(issues.id, f.issue.id))).toHaveLength(0); + expect(await db.select().from(caseHandoffs).where(eq(caseHandoffs.id, other.handoff.id))).toEqual([other.handoff]); + }); + + it.each(["sourceId", "targetId"] as const)("preserves history and explains why its %s cannot be purged", async role => { + const f = await caseFixture(); + + await expect(createAgentLifecycle(db).purgeAgent(f[role])).rejects.toMatchObject({ status: 409, + details: { code: "agent_case_history_retained" } }); + + expect(await db.select().from(caseHandoffs).where(eq(caseHandoffs.id, f.handoff.id))).toEqual([f.handoff]); + expect(await db.select().from(issues).where(eq(issues.id, f.issue.id))).toEqual([f.issue]); + expect(await db.select().from(agents).where(eq(agents.id, f[role]))).toMatchObject([{ lifecycleState: "terminated" }]); + }); + + it("still purges an unrelated terminated agent without deleting case history", async () => { + const f = await caseFixture(); + const [unrelated] = await db.insert(agents).values({ companyId: f.companyId, name: "Unrelated worker", + status: "terminated", lifecycleState: "terminated" }).returning(); + + expect(await createAgentLifecycle(db).purgeAgent(unrelated!.id)).toMatchObject({ id: unrelated!.id }); + + expect(await db.select().from(agents).where(eq(agents.id, unrelated!.id))).toHaveLength(0); + expect(await db.select().from(caseHandoffs).where(eq(caseHandoffs.id, f.handoff.id))).toEqual([f.handoff]); + }); + }); + it("deletes terminated and rejected agents only in the requested company", async () => { await db.insert(agents).values((["terminated", "rejected"] as const).map(lifecycleState => ({ companyId, name: lifecycleState, status: "terminated", lifecycleState, diff --git a/server/src/services/agent-cost-history-deletion.test.ts b/server/src/services/agent-cost-history-deletion.test.ts deleted file mode 100644 index 923298a48f6..00000000000 --- a/server/src/services/agent-cost-history-deletion.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { randomUUID } from "node:crypto"; -import { eq } from "drizzle-orm"; -import { agents, companies, costEvents, createDb, financeEvents, heartbeatRuns } from "@paperclipai/db"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; -import { createAgentLifecycle } from "./agent-lifecycle.js"; - -describe("agent purge with retained cost history", () => { - let temporary: Awaited>; - let db: ReturnType; - beforeAll(async () => { - temporary = await startEmbeddedPostgresTestDatabase("agent-cost-deletion-"); - db = createDb(temporary.connectionString); - }); - afterAll(async () => { await temporary?.cleanup(); }); - - async function fixture() { - const companyId = randomUUID(), agentId = randomUUID(); - await db.insert(companies).values({ id: companyId, name: "Cost deletion", issuePrefix: `C${companyId.slice(0, 6)}` }); - await db.insert(agents).values({ id: agentId, companyId, name: "Billed worker", status: "terminated", lifecycleState: "terminated" }); - const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded" }).returning(); - return { companyId, agentId, run: run! }; - } - const cost = (companyId: string, values: Partial) => db.insert(costEvents).values({ - companyId, usageKind: "decision", provider: "anthropic", model: "claude", costCents: 1, occurredAt: new Date(), ...values, - }).returning(); - - async function expectRetained(f: Awaited>) { - await expect(createAgentLifecycle(db).purgeAgent(f.agentId)).rejects.toMatchObject({ status: 409, - details: { code: "agent_cost_history_retained" } }); - expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id))).toHaveLength(1); - expect(await db.select().from(agents).where(eq(agents.id, f.agentId))).toMatchObject([{ lifecycleState: "terminated" }]); - } - - it("refuses before cleanup when a cost event references one of the agent's runs", async () => { - const f = await fixture(); - const [event] = await cost(f.companyId, { heartbeatRunId: f.run.id }); - await expectRetained(f); - expect(await db.select().from(costEvents).where(eq(costEvents.id, event!.id))).toEqual([event]); - }); - - it("refuses when a cost event is attributed to the agent", async () => { - const f = await fixture(); - await cost(f.companyId, { usageKind: "agent", agentId: f.agentId }); - await expectRetained(f); - }); - - it("refuses when a finance event references one of the agent's runs", async () => { - const f = await fixture(); - const [event] = await db.insert(financeEvents).values({ companyId: f.companyId, heartbeatRunId: f.run.id, - eventKind: "usage", biller: "anthropic", amountCents: 1, occurredAt: new Date() }).returning(); - await expectRetained(f); - expect(await db.select().from(financeEvents).where(eq(financeEvents.id, event!.id))).toEqual([event]); - }); - - it("still purges an agent whose runs have no cost history", async () => { - const f = await fixture(); - expect(await createAgentLifecycle(db).purgeAgent(f.agentId)).toMatchObject({ id: f.agentId }); - expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id))).toHaveLength(0); - }); -}); diff --git a/server/src/services/case-deletion.test.ts b/server/src/services/case-deletion.test.ts deleted file mode 100644 index b6ca415e4f6..00000000000 --- a/server/src/services/case-deletion.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { randomUUID } from "node:crypto"; -import { eq } from "drizzle-orm"; -import { agents, caseAccessSources, caseHandoffs, cases, companies, createDb, issues } from "@paperclipai/db"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; -import { createAgentLifecycle } from "./agent-lifecycle.js"; -import { deleteCompany } from "./company-deletion.js"; - -describe("deletion with retained case handoffs", () => { - let temporary: Awaited>; - let db: ReturnType; - beforeAll(async () => { - temporary = await startEmbeddedPostgresTestDatabase("case-deletion-"); - db = createDb(temporary.connectionString); - }); - afterAll(async () => { await temporary?.cleanup(); }); - - async function fixture(state: "delivered" | "cancelled" | "pending_dispatch" = "delivered") { - const companyId = randomUUID(), sourceId = randomUUID(), targetId = randomUUID(); - await db.insert(companies).values({ id: companyId, name: "Case deletion", issuePrefix: `D${companyId.slice(0, 6)}` }); - await db.insert(agents).values([sourceId, targetId].map(id => ({ id, companyId, - name: "Retained worker", status: "terminated", lifecycleState: "terminated" as const }))); - const [issue] = await db.insert(issues).values({ companyId, title: "Workflow task", status: "todo", - assigneeAgentId: targetId }).returning(); - const [record] = await db.insert(cases).values({ companyId, caseNumber: 1, identifier: `D${companyId}-C1`, - caseType: "deletion", title: "Workflow record", workIssueId: issue!.id }).returning(); - await db.insert(caseAccessSources).values({ companyId, caseId: record!.id, sourceKind: "issue", sourceId: issue!.id }); - const [handoff] = await db.insert(caseHandoffs).values({ companyId, caseId: record!.id, issueId: issue!.id, - version: 1, fromAgentId: sourceId, toAgentId: targetId, phase: "verification", instructions: "Retain this history", - actorType: "user", actorId: "board", wakeupRequestId: randomUUID(), idempotencyKey: randomUUID(), - inputFingerprint: "fixture", state }).returning(); - return { companyId, sourceId, targetId, issue: issue!, record: record!, handoff: handoff! }; - } - - it.each(["delivered", "cancelled", "pending_dispatch"] as const)("deletes the whole company with a %s handoff", async state => { - const f = await fixture(state), other = await fixture(); - - expect(await deleteCompany(db, f.companyId)).toMatchObject({ id: f.companyId }); - - expect(await db.select().from(companies).where(eq(companies.id, f.companyId))).toHaveLength(0); - expect(await db.select().from(cases).where(eq(cases.id, f.record.id))).toHaveLength(0); - expect(await db.select().from(caseHandoffs).where(eq(caseHandoffs.id, f.handoff.id))).toHaveLength(0); - expect(await db.select().from(caseAccessSources).where(eq(caseAccessSources.caseId, f.record.id))).toHaveLength(0); - expect(await db.select().from(issues).where(eq(issues.id, f.issue.id))).toHaveLength(0); - expect(await db.select().from(caseHandoffs).where(eq(caseHandoffs.id, other.handoff.id))).toEqual([other.handoff]); - }); - - it.each(["sourceId", "targetId"] as const)("preserves history and explains why its %s cannot be purged", async role => { - const f = await fixture(); - - await expect(createAgentLifecycle(db).purgeAgent(f[role])).rejects.toMatchObject({ status: 409, - details: { code: "agent_case_history_retained" } }); - - expect(await db.select().from(caseHandoffs).where(eq(caseHandoffs.id, f.handoff.id))).toEqual([f.handoff]); - expect(await db.select().from(issues).where(eq(issues.id, f.issue.id))).toEqual([f.issue]); - expect(await db.select().from(agents).where(eq(agents.id, f[role]))).toMatchObject([{ lifecycleState: "terminated" }]); - }); - - it("still purges an unrelated terminated agent without deleting case history", async () => { - const f = await fixture(); - const [unrelated] = await db.insert(agents).values({ companyId: f.companyId, name: "Unrelated worker", - status: "terminated", lifecycleState: "terminated" }).returning(); - - expect(await createAgentLifecycle(db).purgeAgent(unrelated!.id)).toMatchObject({ id: unrelated!.id }); - - expect(await db.select().from(agents).where(eq(agents.id, unrelated!.id))).toHaveLength(0); - expect(await db.select().from(caseHandoffs).where(eq(caseHandoffs.id, f.handoff.id))).toEqual([f.handoff]); - }); -});