Files
PaperClipAI/server/src/__tests__/issue-comment-attribution-audit-routes.test.ts
T
Dotta 629281b1e8 fix(test): eliminate Cloud Readiness timeouts in route imports and multi-page arbiter drain tests (#23160)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Post-merge `Cloud readiness` runs the full server test suite with
`--retry=0` before publishing new Core Docker images.
> - Five consecutive `Cloud readiness` runs on `master` failed over 22
hours because two test timeout patterns surfaced under multi-worker CI
shards.
> - First, `issue-activity-events-routes.test.ts` and
`issue-comment-attribution-audit-routes.test.ts` dynamically import
`server/src/routes/issues.ts` inside the first `it()` block, crossing
the 15s `testTimeout` when 5 fork workers simultaneously hit Vite's
transform server.
> - Second, `native-status-arbiter-corpus.test.ts` seeds 103 rows
sequentially in its multi-page drain tests, crossing 60s under 7-worker
shared-Postgres load and causing `afterEach` to time out before
restoring real timers.
> - This pull request moves those module imports into `beforeAll`,
aligns `server/vitest.config.ts` `testTimeout` with `hookTimeout` (30s),
batches the 103-row fixture seeding with bounded concurrency, and guards
timer restoration in `try/finally`.
> - The benefit is green, deterministic post-merge `Cloud readiness`
builds without weakening any test assertion or retry policy.

## Linked Issues or Issue Description

**What happened?**
Five consecutive `Cloud readiness` workflow runs on `master` failed and
cancelled over a 22-hour window, blocking new Core image publication:
- Three runs failed with `Test timed out in 15000ms` on the first test
of `server/src/__tests__/issue-activity-events-routes.test.ts` (twice)
and
`server/src/__tests__/issue-comment-attribution-audit-routes.test.ts`
(once) while dynamically importing `server/src/routes/issues.ts` under
5-worker parallel serialized shards.
- Two runs failed in
`server/src/__tests__/native-status-arbiter-corpus.test.ts` when `drains
more than one reconstruction page without replaying settled reviews`
timed out at `60000ms` during 103 sequential `seedReview()` calls, which
also timed out `afterEach` (`30000ms`) before restoring
`vi.useRealTimers()`.

**Expected behavior**
All server route and native status arbiter tests pass reliably on
post-merge `Cloud readiness` (`--retry=0`) without cold-transform
timeouts or leaked fake timers.

**Steps to reproduce**
1. Run `Cloud readiness` (`release-verify.yml`) on `master` with
`--retry=0` on 8-core runners (`maxWorkers=5` serialized shards,
`maxWorkers=7` general-server shards).
2. Observe cold dynamic imports of `routes/issues.ts` inside `it()`
crossing `15000ms` and the 103-row sequential seed test in
`native-status-arbiter-corpus.test.ts` crossing `60000ms`.

**Paperclip version or commit**
`c57471459f` (`master`)

## What Changed

- **`server/src/__tests__/issue-activity-events-routes.test.ts`**:
Register module mocks and import `routes/issues.js` and
`middleware/index.js` once in `beforeAll` (30s timeout) instead of
calling `vi.resetModules()` and re-importing on every test; keep full
`vi.clearAllMocks()` and mock defaults reset in `beforeEach`.
-
**`server/src/__tests__/issue-comment-attribution-audit-routes.test.ts`**:
Pre-import `routes/activity.js` and `routes/issues.js` in `beforeAll`
alongside embedded Postgres startup (30s timeout) instead of lazily
importing inside `createApp()` on the first test.
- **`server/vitest.config.ts`**: Increase `testTimeout` from `15000` to
`30000` (matching `hookTimeout` and `teardownTimeout`) so parallel cold
Vite transforms on 5-worker CI shards do not flake the first test in
sibling route suites.
- **`server/src/__tests__/native-status-arbiter-corpus.test.ts`**: Seed
the 103 fixtures in both multi-page drain tests in bounded concurrent
batches of 8, parallelize the final status assertions, allow `30_000ms`
for multi-page `flush()`, and wrap `coordinator?.stop()` in
`try/finally` in both `afterEach` hooks so `vi.useRealTimers()` and
`vi.restoreAllMocks()` always run.

## Verification

- `pnpm --filter @paperclipai/server typecheck` — passed
- `pnpm exec vitest run --project @paperclipai/server
server/src/__tests__/issue-activity-events-routes.test.ts
server/src/__tests__/issue-comment-attribution-audit-routes.test.ts
server/src/__tests__/native-status-arbiter-corpus.test.ts` — passed
(`3/3` files, `189/189` tests; `issue-activity-events-routes.test.ts`
ran in `3.95s` total and test 1 of
`issue-comment-attribution-audit-routes.test.ts` ran in `445ms`)

## Risks

- Low risk: test-only and Vitest timeout configuration changes. No
production server behavior, schema, or API contracts are changed, and no
test assertions or retry policies are weakened.

## Model Used

- Google DeepMind Antigravity (Gemini 3.1 Pro, agentic tool use with
shell verification)

## 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)
2026-11-28 14:06:21 +00:00

312 lines
11 KiB
TypeScript

import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { and, desc, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
activityLog,
agents,
authUsers,
companies,
companyMemberships,
createDb,
heartbeatRuns,
issueComments,
issues,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
vi.hoisted(() => {
process.env.PAPERCLIP_HOME = "/tmp/paperclip-test-home";
process.env.PAPERCLIP_INSTANCE_ID = "vitest";
process.env.PAPERCLIP_LOG_DIR = "/tmp/paperclip-test-home/logs";
process.env.PAPERCLIP_IN_WORKTREE = "false";
});
vi.mock("../services/issue-assignment-wakeup.js", () => ({
queueIssueAssignmentWakeup: vi.fn(),
}));
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
type Db = ReturnType<typeof createDb>;
let loadedActivityRoutes!: (typeof import("../routes/activity.js"))["activityRoutes"];
let loadedIssueRoutes!: (typeof import("../routes/issues.js"))["issueRoutes"];
async function createApp(db: Db, actor: Express.Request["actor"]) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = actor;
next();
});
app.use("/api", loadedIssueRoutes(db, {} as never));
app.use("/api", loadedActivityRoutes(db));
app.use((error: any, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
res.status(error.status ?? 500).json({ error: error.message ?? "Internal server error" });
});
return app;
}
describeEmbeddedPostgres("issue comment attribution and patch audit routes", () => {
let db!: Db;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
const [dbResult, activityResult, issueResult] = await Promise.allSettled([
startEmbeddedPostgresTestDatabase("paperclip-comment-attribution-audit-"),
import("../routes/activity.js"),
import("../routes/issues.js"),
]);
if (dbResult.status === "rejected") throw dbResult.reason;
tempDb = dbResult.value;
if (activityResult.status === "rejected") throw activityResult.reason;
if (issueResult.status === "rejected") throw issueResult.reason;
loadedActivityRoutes = activityResult.value.activityRoutes;
loadedIssueRoutes = issueResult.value.issueRoutes;
db = createDb(dbResult.value.connectionString);
}, 30_000);
afterEach(async () => {
await db.delete(activityLog);
await db.delete(issueComments);
await db.delete(heartbeatRuns);
await db.delete(issues);
await db.delete(companyMemberships);
await db.delete(agents);
await db.delete(companies);
await db.delete(authUsers);
});
afterAll(async () => tempDb?.cleanup());
async function seed() {
const company = await db.insert(companies).values({
name: "Attribution Company",
issueCounter: 2,
issuePrefix: `AT${randomUUID().replaceAll("-", "").slice(0, 6).toUpperCase()}`,
}).returning().then((rows) => rows[0]!);
const [actorAgent, targetAgent] = await db.insert(agents).values(["Actor", "Target"].map((name) => ({
companyId: company.id,
name,
role: "engineer",
status: "active" as const,
adapterType: "process",
adapterConfig: {},
runtimeConfig: {},
}))).returning();
const responsibleUserId = `responsible-${randomUUID()}`;
const boardUserId = `board-${randomUUID()}`;
const now = new Date();
await db.insert(authUsers).values([
{
id: responsibleUserId,
name: "Responsible User",
email: `${responsibleUserId}@example.test`,
emailVerified: true,
createdAt: now,
updatedAt: now,
},
{
id: boardUserId,
name: "Board User",
email: `${boardUserId}@example.test`,
emailVerified: true,
createdAt: now,
updatedAt: now,
},
]);
await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "user",
principalId: responsibleUserId,
status: "active",
membershipRole: "member",
});
const [sourceIssue, issue] = await db.insert(issues).values([
{
companyId: company.id,
identifier: `${company.issuePrefix}-1`,
title: "Source issue",
status: "in_progress" as const,
priority: "medium" as const,
assigneeAgentId: actorAgent.id,
},
{
companyId: company.id,
identifier: `${company.issuePrefix}-2`,
title: "Foreign issue",
status: "done" as const,
priority: "medium" as const,
assigneeAgentId: targetAgent.id,
},
]).returning();
const run = await db.insert(heartbeatRuns).values({
companyId: company.id,
agentId: actorAgent.id,
status: "running",
responsibleUserId,
contextSnapshot: { issueId: sourceIssue.id },
}).returning().then((rows) => rows[0]!);
return { company, actorAgent, responsibleUserId, boardUserId, run, issue };
}
function agentActor(input: Awaited<ReturnType<typeof seed>>): Express.Request["actor"] {
return {
type: "agent",
agentId: input.actorAgent.id,
companyId: input.company.id,
runId: input.run.id,
onBehalfOfUserId: input.responsibleUserId,
onBehalfOfMemberships: [{
companyId: input.company.id,
membershipRole: "member",
status: "active",
}],
source: "agent_jwt",
};
}
it("records the human recipient for REST task and child creation", async () => {
const fixture = await seed();
const app = await createApp(db, agentActor(fixture));
for (const [path, action] of [
[`/api/companies/${fixture.company.id}/issues`, "issue.created"],
[`/api/issues/${fixture.issue.id}/children`, "issue.child_created"],
]) {
const response = await request(app).post(path!).send({
title: "Task for the human", status: "todo", assigneeUserId: fixture.responsibleUserId,
});
expect(response.status, JSON.stringify(response.body)).toBe(201);
const events = await db.select().from(activityLog).where(and(
eq(activityLog.entityId, response.body.id), eq(activityLog.action, action!),
));
expect(events).toEqual([expect.objectContaining({
actorType: "agent", actorId: fixture.actorAgent.id,
details: expect.objectContaining({ assigneeAgentId: null, assigneeUserId: fixture.responsibleUserId }),
})]);
}
});
it("attributes foreign-issue agent comments and emits complete agent and human PATCH receipts", async () => {
const fixture = await seed();
const agentApp = await createApp(db, agentActor(fixture));
const commentResponse = await request(agentApp)
.post(`/api/issues/${fixture.issue.id}/comments`)
.send({ body: "Cross-issue collaboration note" });
expect(commentResponse.status, JSON.stringify(commentResponse.body)).toBe(201);
expect(commentResponse.body).toMatchObject({
authorAgentId: fixture.actorAgent.id,
onBehalfOfUserId: fixture.responsibleUserId,
createdByRunId: fixture.run.id,
metadata: {
authorizationReason: "allow_visible_issue_write",
},
});
const agentPatch = await request(agentApp)
.patch(`/api/issues/${fixture.issue.id}`)
.send({ priority: "high" });
expect(agentPatch.status, JSON.stringify(agentPatch.body)).toBe(200);
expect(agentPatch.body.changes).toMatchObject({
priority: { from: "medium", to: "high" },
});
const boardApp = await createApp(db, {
type: "board",
userId: fixture.boardUserId,
companyIds: [fixture.company.id],
source: "local_implicit",
isInstanceAdmin: false,
});
const humanPatch = await request(boardApp)
.patch(`/api/issues/${fixture.issue.id}`)
.send({ title: "Human-edited issue" });
expect(humanPatch.status, JSON.stringify(humanPatch.body)).toBe(200);
const patchEvents = await db
.select()
.from(activityLog)
.where(and(
eq(activityLog.entityId, fixture.issue.id),
eq(activityLog.action, "issue.updated"),
))
.orderBy(desc(activityLog.createdAt));
expect(patchEvents).toEqual(expect.arrayContaining([
expect.objectContaining({
actorType: "agent",
actorId: fixture.actorAgent.id,
agentId: fixture.actorAgent.id,
runId: fixture.run.id,
responsibleUserId: fixture.responsibleUserId,
details: expect.objectContaining({
authorizationReason: "allow_visible_issue_write",
changes: expect.objectContaining({
priority: { from: "medium", to: "high" },
}),
}),
}),
expect.objectContaining({
actorType: "user",
actorId: fixture.boardUserId,
agentId: null,
runId: null,
responsibleUserId: fixture.boardUserId,
details: expect.objectContaining({
authorizationReason: "allow_board_actor",
changes: expect.objectContaining({
title: { from: "Foreign issue", to: "Human-edited issue" },
}),
}),
}),
]));
const activityResponse = await request(boardApp).get(`/api/issues/${fixture.issue.id}/activity`);
expect(activityResponse.status, JSON.stringify(activityResponse.body)).toBe(200);
expect(activityResponse.body).toEqual(expect.arrayContaining([
expect.objectContaining({
action: "issue.updated",
responsibleUserId: fixture.responsibleUserId,
details: expect.objectContaining({ authorizationReason: "allow_visible_issue_write" }),
}),
]));
}, 30_000);
it("rejects and audits an agent-supplied onBehalfOfUserId", async () => {
const fixture = await seed();
const response = await request(await createApp(db, agentActor(fixture)))
.post(`/api/issues/${fixture.issue.id}/comments`)
.send({ body: "Spoof attempt", onBehalfOfUserId: "someone-else" });
expect(response.status).toBe(422);
// Plan §6: the refusal says the write itself was fine and names the fix.
expect(response.body.details.code).toBe("issue_write_attribution_spoof_rejected");
expect(response.body.details.sanctionedPath).toContain("onBehalfOfUserId");
expect(response.body.error).toContain("Who can act:");
expect(await db.select().from(issueComments)).toHaveLength(0);
const event = await db
.select()
.from(activityLog)
.where(eq(activityLog.action, "issue.attribution_spoof_rejected"))
.then((rows) => rows[0]);
expect(event).toMatchObject({
actorId: fixture.actorAgent.id,
runId: fixture.run.id,
responsibleUserId: fixture.responsibleUserId,
details: {
identifier: fixture.issue.identifier,
surface: "issue.comment.create",
field: "onBehalfOfUserId",
requestedValue: "someone-else",
derivedFrom: "authenticated_actor",
},
});
}, 30_000);
});