Files
PaperClipAI/ui/src/components/IssueWorkspaceCard.test.tsx
T
DottaandPaperclip f554d67377 fix(server): add explicit review verdict policies (#10931)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Issues use `in_review` to request a final decision from an
authorized writer
> - The server rejected an assignee agent that tried to close its own
review, even when the issue had no independent-review rule
> - This rejection stopped the default agent workflow and did not
represent the configured execution-stage rules
> - Paperclip needs an open default and explicit issue-level constraints
for teams that require an independent or human verdict
> - This pull request removes the unconditional rejection and adds
`anyone`, `not_creator`, and `human_only` review policies
> - The benefit is a working default path with opt-in, authenticated
verdict controls

## Linked Issues or Issue Description

Refs #10635, #4429, and #10671.

The related public work covers execution-stage independence,
self-approval fallback behavior, and durable review paths. This change
is distinct. It controls who can resolve an issue review verdict. It
keeps configured execution stages active.

## What Changed

- Added a nullable `review_policy` issue column. Null has the same
meaning as `anyone`. The migration does not backfill existing issues.
- Added shared create, update, response, and compact issue contracts for
`anyone`, `not_creator`, and `human_only`.
- Removed the unconditional agent self-approval rejection for
`in_review` issues.
- Added one reusable verdict-actor check for terminal status changes and
pending interaction accept or reject actions.
- Used the authenticated principal type for `human_only`. Agent keys and
run tokens remain agent principals.
- Used the latest transition into `in_review` to identify the requester
for `not_creator`.
- Added actionable 403 responses that name the policy, the allowed
actor, and the next step.
- Kept the configured execution-stage transition and signoff behavior.
- Added focused contract, helper, status-route, interaction-route, and
execution-stage regression tests.
- Updated the implementation specification for the new issue field.

## Verification

- `pnpm exec vitest run packages/shared/src/validators/issue.test.ts
server/src/__tests__/issue-review-policy.test.ts
server/src/__tests__/issue-stalled-review-decision-routes.test.ts
--reporter=dot` passed: 42 tests.
- `pnpm --filter @paperclipai/shared typecheck` passed.
- `pnpm --filter @paperclipai/db typecheck` passed, including migration
numbering and safety checks.
- `pnpm --filter @paperclipai/server typecheck` passed.
- `pnpm run typecheck:build-gaps` passed across server, CLI, plugin
SDK/examples, plugin wiki, and UI.
- `git diff --check origin/master...HEAD` passed.
- SecurityEngineer review approved the authenticated-principal checks
and accepted policy-relaxation tradeoff with no required changes.
- Greptile reviewed the latest head at 5/5 with zero inline comments or
follow-ups.
- The latest-head GitHub rollup passed build, typecheck,
server/workspace tests, serialized suites, canary, e2e, and external
security checks.

## Risks

- The migration adds one nullable text column. It has no default and no
backfill.
- `not_creator` reads the latest recorded transition into `in_review`.
It denies the verdict when it cannot identify the requester.
- Agents can change or relax `reviewPolicy` when they have issue write
access. This is intentional for this issue-level control.
- Null and `anyone` do not add a database query to the verdict path.
- Configured execution-stage checks still run after the issue-level
policy check.

> This work aligns with the completed "Agent Reviews and Approvals" and
"Enforced Outcomes" roadmap items. It does not add a new roadmap
capability.

## Model Used

- OpenAI Codex, GPT-5. The exact deployment ID and context-window size
are not exposed to the agent. The run used reasoning, repository tools,
code execution, and GitHub CLI access.

## 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:12:41 -05:00

267 lines
7.9 KiB
TypeScript

// @vitest-environment jsdom
import type { ComponentProps } from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import type { ExecutionWorkspace, Issue } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { IssueWorkspaceCard } from "./IssueWorkspaceCard";
function act(callback: () => void | Promise<void>) {
let result: void | Promise<void> | undefined;
flushSync(() => {
result = callback();
});
return result;
}
const useQueryMock = vi.fn();
vi.mock("@tanstack/react-query", async () => {
const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");
return {
...actual,
useQuery: (options: unknown) => useQueryMock(options),
};
});
vi.mock("../context/CompanyContext", () => ({
useCompany: () => ({ selectedCompanyId: "company-1" }),
}));
vi.mock("@/lib/router", () => ({
Link: ({ children, className, ...props }: ComponentProps<"a">) => (
<a className={className} {...props}>{children}</a>
),
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
function createExecutionWorkspace(overrides: Partial<ExecutionWorkspace> = {}): ExecutionWorkspace {
return {
id: "workspace-1",
companyId: "company-1",
projectId: "project-1",
projectWorkspaceId: "project-workspace-1",
sourceIssueId: null,
mode: "isolated_workspace",
strategyType: "git_worktree",
name: "Issue sandbox",
status: "active",
deliveryState: "unknown",
cwd: "/tmp/issue-sandbox",
repoUrl: null,
baseRef: null,
branchName: "paperclip/papa-81",
providerType: "git_worktree",
providerRef: null,
derivedFromExecutionWorkspaceId: null,
lastUsedAt: new Date("2026-04-16T05:00:00.000Z"),
openedAt: new Date("2026-04-16T04:59:00.000Z"),
closedAt: null,
cleanupEligibleAt: null,
cleanupReason: null,
config: {
environmentId: "env-workspace",
provisionCommand: null,
teardownCommand: null,
cleanupCommand: null,
workspaceRuntime: null,
desiredState: null,
},
metadata: null,
runtimeServices: [],
createdAt: new Date("2026-04-16T04:59:00.000Z"),
updatedAt: new Date("2026-04-16T05:00:00.000Z"),
...overrides,
};
}
function createIssue(overrides: Partial<Issue> = {}): Issue {
return {
id: "issue-1",
identifier: "PAPA-81",
companyId: "company-1",
projectId: "project-1",
projectWorkspaceId: "project-workspace-1",
goalId: null,
parentId: null,
title: "Sandboxing",
description: null,
status: "in_progress",
priority: "medium",
reviewPolicy: null,
assigneeAgentId: "agent-1",
assigneeUserId: null,
responsibleUserId: null,
createdByAgentId: null,
createdByUserId: null,
issueNumber: 81,
requestDepth: 0,
billingCode: null,
assigneeAdapterOverrides: null,
executionWorkspaceId: "workspace-1",
executionWorkspacePreference: "isolated_workspace",
executionWorkspaceSettings: {
mode: "isolated_workspace",
environmentId: "env-issue",
},
checkoutRunId: null,
executionRunId: null,
executionAgentNameKey: null,
executionLockedAt: null,
startedAt: null,
completedAt: null,
cancelledAt: null,
hiddenAt: null,
createdAt: new Date("2026-04-16T04:30:00.000Z"),
updatedAt: new Date("2026-04-16T05:30:00.000Z"),
labels: [],
labelIds: [],
currentExecutionWorkspace: null,
...overrides,
workMode: overrides.workMode ?? "standard",
};
}
describe("IssueWorkspaceCard", () => {
let container: HTMLDivElement;
let originalResizeObserver: typeof ResizeObserver | undefined;
beforeEach(() => {
originalResizeObserver = globalThis.ResizeObserver;
globalThis.ResizeObserver = class ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
};
container = document.createElement("div");
document.body.appendChild(container);
useQueryMock.mockReset();
});
afterEach(() => {
globalThis.ResizeObserver = originalResizeObserver!;
container.remove();
});
it("clears the legacy issue environment override when reusing a workspace", () => {
const root = createRoot(container);
const onUpdate = vi.fn();
const reusableWorkspace = createExecutionWorkspace();
useQueryMock.mockImplementation((options: { queryKey: unknown[] }) => {
if (options.queryKey[0] === "instance") {
return { data: { enableEnvironments: true, enableIsolatedWorkspaces: true } };
}
if (options.queryKey[0] === "environments") {
return {
data: [{ id: "env-workspace", name: "Local", driver: "local" }],
};
}
if (options.queryKey[0] === "execution-workspaces") {
return { data: [reusableWorkspace] };
}
return { data: undefined };
});
act(() => {
root.render(
<IssueWorkspaceCard
issue={createIssue()}
project={{
id: "project-1",
executionWorkspacePolicy: {
enabled: true,
defaultMode: "isolated_workspace",
environmentId: "env-project",
},
}}
onUpdate={onUpdate}
/>,
);
});
const editButton = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("Edit"));
expect(editButton).not.toBeUndefined();
act(() => {
editButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
});
const selects = container.querySelectorAll("select");
expect(selects).toHaveLength(1);
expect(container.querySelector("button[role='combobox']")?.textContent).toContain("Issue sandbox");
const saveButton = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("Save"));
expect(saveButton).not.toBeUndefined();
act(() => {
saveButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
});
expect(onUpdate).toHaveBeenCalledWith({
executionWorkspacePreference: "reuse_existing",
executionWorkspaceId: "workspace-1",
executionWorkspaceSettings: {
mode: "isolated_workspace",
environmentId: null,
},
});
act(() => {
root.unmount();
});
});
it("hides environment UI when environments are disabled", () => {
const root = createRoot(container);
useQueryMock.mockImplementation((options: { queryKey: unknown[] }) => {
if (options.queryKey[0] === "instance") {
return { data: { enableEnvironments: false, enableIsolatedWorkspaces: true } };
}
if (options.queryKey[0] === "execution-workspaces") {
return { data: [createExecutionWorkspace()] };
}
return { data: undefined };
});
act(() => {
root.render(
<IssueWorkspaceCard
issue={createIssue()}
project={{
id: "project-1",
executionWorkspacePolicy: {
enabled: true,
defaultMode: "isolated_workspace",
environmentId: "env-project",
},
}}
onUpdate={vi.fn()}
/>,
);
});
expect(container.textContent).not.toContain("Environment:");
const editButton = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("Edit"));
expect(editButton).not.toBeUndefined();
act(() => {
editButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
});
const selects = container.querySelectorAll("select");
expect(selects).toHaveLength(1);
expect(container.querySelector("button[role='combobox']")?.textContent).toContain("Issue sandbox");
expect(container.textContent).not.toContain("Project default environment");
act(() => {
root.unmount();
});
});
});