Files
PaperClipAI/server/src/__tests__/activity-log-responsible-user.test.ts
DottaandPaperclip 814cb33676 feat(server): allow agents to resolve review confirmations (#10939)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Issue reviews use thread confirmations to record explicit verdicts
> - The server allowed users to resolve review confirmations but
rejected all agent actors
> - This one-way rule prevented an eligible agent reviewer from
completing a review
> - The existing review policy already defines which actor can submit a
verdict
> - This pull request applies that policy to agent confirmation verdicts
on writable issues
> - The benefit is a consistent review gate for users and agents with
preserved audit attribution

## Linked Issues or Issue Description

- Builds on: #10931 (merged into master before this PR)
- Refs #8617

## What Changed

- Allow eligible agents to accept or reject pending review confirmations
on issues they can write.
- Allow a creator agent to withdraw its own pending review confirmation
when the review policy permits it.
- Reuse the review verdict policy check for users and agents.
- Require an explicit, same-run review-confirmation binding so unrelated
board-only confirmations stay protected.
- Preserve board-only tool action confirmations and existing user
attribution.
- Add route and service tests for agent accept, reject, withdrawal,
human-only denial, and user attribution.

## Verification

- `pnpm exec vitest run packages/shared/src/validators/issue.test.ts
server/src/__tests__/issue-execution-policy-routes.test.ts
server/src/__tests__/issue-review-policy.test.ts
server/src/__tests__/issue-thread-interaction-routes.test.ts
server/src/__tests__/issue-thread-interactions-service.test.ts
server/src/__tests__/issue-stalled-review-decision-routes.test.ts` (256
passed after rebasing onto master and the atomic binding fix)
- `pnpm --filter @paperclipai/shared typecheck`
- `pnpm --filter @paperclipai/server typecheck`
- `pnpm -r typecheck`
- `env -u AWS_ACCESS_KEY_ID -u AWS_SECRET_ACCESS_KEY pnpm test:run`
- `pnpm build`

## Risks

- The change expands who can resolve pending review confirmations. The
existing issue write checks and review policy limit this access.
- Tool action confirmations remain board-only.
- The pull request depends on the review policy helper from #10931,
which is now merged into master.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

The roadmap marks Agent Reviews and Approvals as shipped. This pull
request fixes a narrow server behavior gap in that shipped capability.

## Model Used

- OpenAI Codex, model `gpt-5.6-sol`, with reasoning, tool use, and code
execution. The runtime does not expose the context window size.

## 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-08-05 23:40:05 -05:00

247 lines
7.7 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { eq } from "drizzle-orm";
import {
activityLog,
agentApiKeys,
agents,
companies,
createDb,
heartbeatRuns,
issues,
type Db,
} from "@paperclipai/db";
import {
logActivity,
resolveResponsibleUserIdForActivity,
type ActivityPublication,
type LogActivityInput,
} from "../services/activity-log.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
type TableRows = Map<unknown, Array<Record<string, unknown>>>;
const companyId = "00000000-0000-4000-8000-000000000001";
const agentId = "00000000-0000-4000-8000-000000000002";
const issueId = "00000000-0000-4000-8000-000000000003";
const runId = "00000000-0000-4000-8000-000000000004";
const missingRunId = "00000000-0000-4000-8000-000000000005";
const agentApiKeyId = "00000000-0000-4000-8000-000000000006";
const missingAgentApiKeyId = "00000000-0000-4000-8000-000000000007";
function createReader(rowsByTable: TableRows) {
return {
select: () => ({
from: (table: unknown) => ({
where: (condition: unknown) => {
expect(condition).toBeDefined();
return Promise.resolve(rowsByTable.get(table) ?? []);
},
}),
}),
} as unknown as Db;
}
function activityInput(overrides: Partial<LogActivityInput> = {}): LogActivityInput {
return {
companyId,
actorType: "agent",
actorId: agentId,
action: "issue.updated",
entityType: "issue",
entityId: issueId,
agentId,
...overrides,
};
}
describe("resolveResponsibleUserIdForActivity", () => {
it("attributes user actions directly without database lookups", async () => {
const db = {
select: () => {
throw new Error("user attribution should not query the database");
},
} as unknown as Db;
await expect(resolveResponsibleUserIdForActivity(db, activityInput({
actorType: "user",
actorId: "user-1",
entityType: "company",
entityId: companyId,
}))).resolves.toBe("user-1");
});
it("prefers the heartbeat run responsible user", async () => {
const db = createReader(new Map([
[heartbeatRuns, [{ responsibleUserId: "run-user" }]],
[issues, [{ responsibleUserId: "issue-user", createdByUserId: null }]],
[agentApiKeys, [{ responsibleUserId: "key-user" }]],
[companies, [{ defaultResponsibleUserId: "default-user" }]],
]));
await expect(resolveResponsibleUserIdForActivity(db, activityInput({
runId,
agentApiKeyId,
}))).resolves.toBe("run-user");
});
it("falls back to issue attribution when the run is unavailable", async () => {
const db = createReader(new Map([
[heartbeatRuns, []],
[issues, [{ responsibleUserId: "issue-user", createdByUserId: "creator-user" }]],
[agentApiKeys, [{ responsibleUserId: "key-user" }]],
[companies, [{ defaultResponsibleUserId: "default-user" }]],
]));
await expect(resolveResponsibleUserIdForActivity(db, activityInput({
runId: missingRunId,
agentApiKeyId,
}))).resolves.toBe("issue-user");
});
it("uses explicit issue context for non-issue activity", async () => {
const db = createReader(new Map([
[issues, [{ responsibleUserId: "issue-user", createdByUserId: null }]],
[companies, [{ defaultResponsibleUserId: "default-user" }]],
]));
await expect(resolveResponsibleUserIdForActivity(db, activityInput({
entityType: "heartbeat_run",
entityId: runId,
issueId,
}))).resolves.toBe("issue-user");
});
it("uses the active agent API key responsible user for no-run actions", async () => {
const db = createReader(new Map([
[agentApiKeys, [{ responsibleUserId: "key-user" }]],
[companies, [{ defaultResponsibleUserId: "default-user" }]],
]));
await expect(resolveResponsibleUserIdForActivity(db, activityInput({
entityType: "agent",
entityId: agentId,
agentApiKeyId,
}))).resolves.toBe("key-user");
});
it("falls back to the company default responsible user", async () => {
const db = createReader(new Map([
[agentApiKeys, []],
[companies, [{ defaultResponsibleUserId: "default-user" }]],
]));
await expect(resolveResponsibleUserIdForActivity(db, activityInput({
entityType: "company",
entityId: companyId,
agentApiKeyId: missingAgentApiKeyId,
}))).resolves.toBe("default-user");
});
it("uses issue creator attribution when responsibleUserId is absent", async () => {
const db = createReader(new Map([
[issues, [{ responsibleUserId: null, createdByUserId: "creator-user" }]],
[companies, [{ defaultResponsibleUserId: "default-user" }]],
]));
await expect(resolveResponsibleUserIdForActivity(db, activityInput())).resolves.toBe("creator-user");
});
it("ignores malformed UUID-backed identifiers", async () => {
const db = createReader(new Map([
[heartbeatRuns, [{ responsibleUserId: "run-user" }]],
[issues, [{ responsibleUserId: "issue-user", createdByUserId: null }]],
[agentApiKeys, [{ responsibleUserId: "key-user" }]],
[companies, [{ defaultResponsibleUserId: "default-user" }]],
]));
await expect(resolveResponsibleUserIdForActivity(db, activityInput({
runId: "not-a-run-uuid",
entityId: "not-an-issue-uuid",
agentApiKeyId: "not-a-key-uuid",
details: { issueId },
}))).resolves.toBe("default-user");
});
});
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
describeEmbeddedPostgres("logActivity responsible-user stamping", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-activity-responsible-user-");
db = createDb(tempDb.connectionString);
}, 20_000);
afterAll(async () => {
await tempDb?.cleanup();
});
it("persists API-key attribution for an out-of-run action", async () => {
const companyId = randomUUID();
const agentId = randomUUID();
const agentApiKeyId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
defaultResponsibleUserId: "default-user",
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values({
id: agentId,
companyId,
name: "CodexCoder",
role: "engineer",
status: "running",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
});
await db.insert(agentApiKeys).values({
id: agentApiKeyId,
companyId,
agentId,
name: "test",
keyHash: `hash-${agentApiKeyId}`,
responsibleUserId: "key-user",
});
const postCommitPublications: ActivityPublication[] = [];
await logActivity(db, activityInput({
companyId,
actorId: agentId,
agentId,
entityType: "agent",
entityId: agentId,
agentApiKeyId,
}), postCommitPublications);
expect(postCommitPublications).toHaveLength(1);
expect(postCommitPublications[0]).toMatchObject({
companyId,
payload: {
action: "issue.updated",
entityType: "agent",
entityId: agentId,
},
});
const row = await db
.select({ responsibleUserId: activityLog.responsibleUserId })
.from(activityLog)
.where(eq(activityLog.companyId, companyId))
.then((rows) => rows[0]);
expect(row?.responsibleUserId).toBe("key-user");
});
});