Handle incomplete task policies and preserve review limits (#15593)

Apply the reviewed change for Handle incomplete task policies and preserve review limits.

Validation: local typecheck/build and focused regression tests, passing exact-head CI, Greptile 5/5, and independent source review. The PR records full-suite evidence and any local environment limitations.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-10-08 10:20:32 -07:00
1 parent 3d0e74e743
commit 317ed367d4
13 files changed
+452 -30

No files matched your search

@@ -0,0 +1,70 @@
// @vitest-environment jsdom
import { act, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { issueExecutionPolicySchema, type Issue } from "@paperclipai/shared";
import { describe, expect, it, vi } from "vitest";
import { ExecutionParticipantPicker } from "./ExecutionParticipantPicker";
vi.mock("../api/access", () => ({ accessApi: { listUserDirectory: async () => ({ users: [] }) } }));
vi.mock("../lib/sentry", () => ({ captureBrowserException: vi.fn() }));
vi.mock("@/components/ui/popover", () => ({
Popover: ({ children }: { children: ReactNode }) => <div>{children}</div>,
PopoverTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
PopoverContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
function renderPicker(policy: unknown) {
const container = document.createElement("div");
const root = createRoot(container);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const onUpdate = vi.fn();
const issue = { companyId: "company-fixture", executionPolicy: policy } as Issue;
act(() => root.render(<QueryClientProvider client={client}>
<ExecutionParticipantPicker issue={issue} stageType="review" agents={[]} currentUserId="board-reviewer" onUpdate={onUpdate} />
</QueryClientProvider>));
return { container, onUpdate, cleanup: () => { act(() => root.unmount()); client.clear(); } };
}
describe("ExecutionParticipantPicker", () => {
it("adds a reviewer to a valid policy that omits stages without dropping authorization", () => {
const policy = { authorizationPolicy: { trustPreset: "standard" }, maxReviewRounds: 4 };
const { container, onUpdate, cleanup } = renderPicker(policy);
expect(container.textContent).not.toContain("Execution policy unavailable");
const assign = Array.from(container.querySelectorAll("button")).find((button) => button.textContent === "Assign to me");
expect(assign).toBeTruthy();
act(() => assign!.click());
expect(onUpdate).toHaveBeenCalledTimes(1);
const updated = onUpdate.mock.calls[0][0].executionPolicy;
expect(issueExecutionPolicySchema.safeParse(updated).success).toBe(true);
expect(updated).toMatchObject({ ...policy, stages: [{ type: "review", participants: [{ type: "user", userId: "board-reviewer" }] }] });
expect(policy).not.toHaveProperty("stages");
cleanup();
});
it("shows an existing reviewer and preserves other policy settings when that reviewer is removed", () => {
const policy = {
authorizationPolicy: { trustPreset: "standard" }, maxReviewRounds: 4,
stages: [{ type: "review", participants: [{ type: "user", userId: "board-reviewer" }] }],
};
const { container, onUpdate, cleanup } = renderPicker(policy);
expect(container.querySelector("button")?.textContent).toBe("You");
const remove = Array.from(container.querySelectorAll("button")).find((button) => button.textContent === "No reviewers");
expect(remove).toBeTruthy();
act(() => remove!.click());
expect(onUpdate).toHaveBeenCalledWith({ executionPolicy: {
mode: "normal", commentRequired: true, stages: [],
authorizationPolicy: policy.authorizationPolicy, maxReviewRounds: 4,
} });
expect(policy.stages[0].participants).toHaveLength(1);
cleanup();
});
it("keeps a malformed policy unavailable and exposes no mutation controls", () => {
const { container, onUpdate, cleanup } = renderPicker({ stages: [{ type: "review", participants: {} }] });
expect(container.textContent).toBe("Execution policy unavailable. Refresh to try again.");
expect(container.querySelector("button")).toBeNull();
expect(onUpdate).not.toHaveBeenCalled();
cleanup();
});
});
@@ -11,6 +11,7 @@ import {
buildExecutionPolicy,
stageParticipantValues,
} from "../lib/issue-execution-policy";
import { useExecutionPolicy } from "../hooks/useExecutionPolicy";
import { cn } from "../lib/utils";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { User, Eye, ShieldCheck } from "lucide-react";
@@ -34,6 +35,7 @@ export function ExecutionParticipantPicker({
}: ExecutionParticipantPickerProps) {
const [open, setOpen] = useState(false);
const [search, setSearch] = useState("");
const policyAvailable = useExecutionPolicy(issue.executionPolicy).success;
const reviewerValues = stageParticipantValues(issue.executionPolicy, "review");
const approverValues = stageParticipantValues(issue.executionPolicy, "approval");
@@ -73,6 +75,7 @@ export function ExecutionParticipantPicker({
};
const updatePolicy = (nextValues: string[]) => {
if (!policyAvailable) return;
onUpdate({
executionPolicy: buildExecutionPolicy({
existingPolicy: issue.executionPolicy ?? null,
@@ -92,6 +95,10 @@ export function ExecutionParticipantPicker({
const label = stageType === "review" ? "Reviewers" : "Approvers";
const Icon = stageType === "review" ? Eye : ShieldCheck;
if (!policyAvailable) {
return <span role="status" className="text-xs text-muted-foreground">Execution policy unavailable. Refresh to try again.</span>;
}
return (
<Popover open={open} onOpenChange={(o) => { setOpen(o); if (!o) setSearch(""); }}>
<PopoverTrigger asChild>
+62 -8
View File
@@ -2735,10 +2735,10 @@ describe("IssueProperties", () => {
executionPolicy: createExecutionPolicy({
stages: [
{
id: "review-stage",
id: "00000000-0000-4000-8000-000000000010",
type: "review",
approvalsNeeded: 1,
participants: [{ id: "participant-1", type: "agent", agentId: "agent-1", userId: null }],
participants: [{ id: "00000000-0000-4000-8000-000000000012", type: "agent", agentId: "00000000-0000-4000-8000-000000000013", userId: null }],
},
],
}),
@@ -2767,10 +2767,10 @@ describe("IssueProperties", () => {
executionPolicy: createExecutionPolicy({
stages: [
{
id: "approval-stage",
id: "00000000-0000-4000-8000-000000000011",
type: "approval",
approvalsNeeded: 1,
participants: [{ id: "participant-2", type: "user", agentId: null, userId: "user-1" }],
participants: [{ id: "00000000-0000-4000-8000-000000000014", type: "user", agentId: null, userId: "user-1" }],
},
],
}),
@@ -2793,10 +2793,10 @@ describe("IssueProperties", () => {
executionPolicy: createExecutionPolicy({
stages: [
{
id: "review-stage",
id: "00000000-0000-4000-8000-000000000010",
type: "review",
approvalsNeeded: 1,
participants: [{ id: "participant-1", type: "agent", agentId: "agent-1", userId: null }],
participants: [{ id: "00000000-0000-4000-8000-000000000012", type: "agent", agentId: "00000000-0000-4000-8000-000000000013", userId: null }],
},
],
}),
@@ -2819,10 +2819,10 @@ describe("IssueProperties", () => {
executionPolicy: createExecutionPolicy({
stages: [
{
id: "review-stage",
id: "00000000-0000-4000-8000-000000000010",
type: "review",
approvalsNeeded: 1,
participants: [{ id: "participant-1", type: "agent", agentId: "agent-1", userId: null }],
participants: [{ id: "00000000-0000-4000-8000-000000000012", type: "agent", agentId: "00000000-0000-4000-8000-000000000013", userId: null }],
},
],
}),
@@ -2924,6 +2924,60 @@ describe("IssueProperties", () => {
dateNowSpy.mockRestore();
});
it.each([true, false])("clears a monitor with omitted stages while preserving independent limits (authorization: %s)", async (withAuthorization) => {
const onUpdate = vi.fn();
const executionPolicy = {
...(withAuthorization ? { authorizationPolicy: { trustPreset: "standard" } } : {}),
maxReviewRounds: 4,
monitor: { nextCheckAt: "2099-01-01T12:00:00.000Z", notes: "Check service", scheduledBy: "board" },
} as IssueExecutionPolicy;
const before = structuredClone(executionPolicy);
const root = renderProperties(container, {
issue: createIssue({ executionPolicy }), childIssues: [], onUpdate, inline: true,
});
await flush();
expect(container.textContent).toContain("Reviewers");
expect(container.textContent).not.toContain("Execution policy unavailable");
const monitorTrigger = container.querySelector('[data-testid="monitor-row-trigger"]')?.closest("button");
expect(monitorTrigger).toBeTruthy();
await act(async () => { monitorTrigger!.dispatchEvent(new MouseEvent("click", { bubbles: true })); });
const clearButton = Array.from(container.querySelectorAll("button")).find((button) => button.textContent === "Clear");
expect(clearButton).toBeTruthy();
await act(async () => { clearButton!.dispatchEvent(new MouseEvent("click", { bubbles: true })); });
expect(onUpdate).toHaveBeenCalledWith({ executionPolicy: {
mode: "normal", commentRequired: true, stages: [],
...(withAuthorization ? { authorizationPolicy: before.authorizationPolicy } : {}), maxReviewRounds: 4,
} });
expect(executionPolicy).toEqual(before);
act(() => root.unmount());
});
it.each([
{ stages: {} },
{ stages: [null] },
{ stages: [{ type: "review", participants: {} }] },
{ monitor: { nextCheckAt: {}, notes: {} } },
])("keeps malformed policies unavailable without exposing destructive edits: %j", async (executionPolicy) => {
const onUpdate = vi.fn();
const root = renderProperties(container, {
issue: createIssue({ executionPolicy: executionPolicy as unknown as IssueExecutionPolicy }),
childIssues: [], onUpdate, inline: true,
});
await flush();
expect(container.textContent).toContain("Execution policy unavailable. Refresh to try again.");
expect(container.textContent).toContain("Assignee");
expect(container.textContent).not.toContain("No reviewers");
expect(container.textContent).not.toContain("No approvers");
expect(container.textContent).not.toContain("Run review now");
expect(container.querySelector('[data-testid="monitor-row-trigger"]')).toBeNull();
expect(container.querySelector('input[type="datetime-local"]')).toBeNull();
expect(onUpdate).not.toHaveBeenCalled();
act(() => root.unmount());
});
it("renders scheduled, retrying, due, overdue, cleared, and empty monitor row states", async () => {
// Anchored to a fixed *local* time, not a fixed UTC instant. The row renders
// these in the machine's timezone and labels them "Today" only while they
@@ -47,6 +47,7 @@ import { getRecentProjectIds } from "../../lib/recent-projects";
import { orderItemsBySelectedAndRecent } from "../../lib/recent-selections";
import { formatAssigneeUserLabel, formatUserLabel } from "../../lib/assignees";
import { buildExecutionPolicy, stageParticipantValues } from "../../lib/issue-execution-policy";
import { useExecutionPolicy } from "../../hooks/useExecutionPolicy";
import {
formatMonitorAbsolute,
formatMonitorAbsoluteFull,
@@ -246,6 +247,9 @@ export function IssueProperties({
documentDeepLink,
sidePanelContentOnly = false,
}: IssuePropertiesProps) {
const policyResult = useExecutionPolicy(issue.executionPolicy);
const policyAvailable = policyResult.success;
const executionPolicy = policyResult.success ? policyResult.data : null;
const { selectedCompanyId } = useCompany();
const { isMobile } = useSidebar();
const queryClient = useQueryClient();
@@ -392,9 +396,9 @@ export function IssueProperties({
const [newLabelName, setNewLabelName] = useState("");
// token-extraction: allowlisted — color-picker seed state, persisted into label-create payload; a var() string would break that payload.
const [newLabelColor, setNewLabelColor] = useState("#6366f1");
const [monitorAtInput, setMonitorAtInput] = useState(() => toDateTimeLocalValue(issue.executionPolicy?.monitor?.nextCheckAt));
const [monitorNotesInput, setMonitorNotesInput] = useState(issue.executionPolicy?.monitor?.notes ?? "");
const [monitorServiceInput, setMonitorServiceInput] = useState(issue.executionPolicy?.monitor?.serviceName ?? "");
const [monitorAtInput, setMonitorAtInput] = useState(() => toDateTimeLocalValue(executionPolicy?.monitor?.nextCheckAt));
const [monitorNotesInput, setMonitorNotesInput] = useState(executionPolicy?.monitor?.notes ?? "");
const [monitorServiceInput, setMonitorServiceInput] = useState(executionPolicy?.monitor?.serviceName ?? "");
const [runtimeActionMessage, setRuntimeActionMessage] = useState<string | null>(null);
const [runtimeActionErrorMessage, setRuntimeActionErrorMessage] = useState<string | null>(null);
const [unarchiveErrorMessage, setUnarchiveErrorMessage] = useState<string | null>(null);
@@ -999,6 +1003,7 @@ export function IssueProperties({
applyAssignee(next, track);
};
const updateExecutionPolicy = (nextReviewers: string[], nextApprovers: string[]) => {
if (!policyAvailable) return;
onUpdate({
executionPolicy: buildExecutionPolicy({
existingPolicy: issue.executionPolicy ?? null,
@@ -1073,13 +1078,13 @@ export function IssueProperties({
return `${stageLabel} pending${participantLabel ? ` with ${participantLabel}` : ""}`;
})();
useEffect(() => {
setMonitorAtInput(toDateTimeLocalValue(issue.executionPolicy?.monitor?.nextCheckAt));
setMonitorNotesInput(issue.executionPolicy?.monitor?.notes ?? "");
setMonitorServiceInput(issue.executionPolicy?.monitor?.serviceName ?? "");
setMonitorAtInput(toDateTimeLocalValue(executionPolicy?.monitor?.nextCheckAt));
setMonitorNotesInput(executionPolicy?.monitor?.notes ?? "");
setMonitorServiceInput(executionPolicy?.monitor?.serviceName ?? "");
}, [
issue.executionPolicy?.monitor?.nextCheckAt,
issue.executionPolicy?.monitor?.notes,
issue.executionPolicy?.monitor?.serviceName,
executionPolicy?.monitor?.nextCheckAt,
executionPolicy?.monitor?.notes,
executionPolicy?.monitor?.serviceName,
]);
// Re-sync watchdog editor inputs when the persisted watchdog changes (and reset on close).
useEffect(() => {
@@ -1261,6 +1266,7 @@ export function IssueProperties({
? M | null
: never
: never) => {
if (!policyAvailable) return;
const basePolicy = buildExecutionPolicy({
existingPolicy: issue.executionPolicy ?? null,
reviewerValues,
@@ -1270,8 +1276,10 @@ export function IssueProperties({
onUpdate({ executionPolicy: null });
return;
}
const { monitor: _previousMonitor, ...policyWithoutMonitor } = basePolicy ?? {};
onUpdate({
executionPolicy: {
...policyWithoutMonitor,
mode: basePolicy?.mode ?? issue.executionPolicy?.mode ?? "normal",
commentRequired: true,
stages: basePolicy?.stages ?? [],
@@ -1299,11 +1307,11 @@ export function IssueProperties({
setMonitorOpen(false);
};
const monitorState = issue.executionState?.monitor ?? null;
const monitorNextCheckAt = monitorState?.nextCheckAt ?? issue.monitorNextCheckAt ?? issue.executionPolicy?.monitor?.nextCheckAt ?? null;
const monitorNextCheckAt = monitorState?.nextCheckAt ?? issue.monitorNextCheckAt ?? executionPolicy?.monitor?.nextCheckAt ?? null;
const monitorAttemptCount = issue.monitorAttemptCount ?? monitorState?.attemptCount ?? 0;
const monitorLastTriggeredAt = issue.monitorLastTriggeredAt ?? monitorState?.lastTriggeredAt ?? null;
const monitorServiceName = issue.executionPolicy?.monitor?.serviceName ?? monitorState?.serviceName ?? null;
const monitorNotes = issue.executionPolicy?.monitor?.notes ?? monitorState?.notes ?? null;
const monitorServiceName = executionPolicy?.monitor?.serviceName ?? monitorState?.serviceName ?? null;
const monitorNotes = executionPolicy?.monitor?.notes ?? monitorState?.notes ?? null;
const monitorNow = useMonitorCountdown(monitorNextCheckAt);
const monitorRelative = monitorNextCheckAt ? formatMonitorEta(monitorNextCheckAt, monitorNow) : null;
const monitorIsDueNow = monitorRelative === "due now";
@@ -1585,7 +1593,7 @@ export function IssueProperties({
>
Schedule
</button>
{issue.executionPolicy?.monitor ? (
{executionPolicy?.monitor ? (
<button
type="button"
className="inline-flex items-center rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
@@ -2621,6 +2629,11 @@ export function IssueProperties({
</PropertyRow>
) : null}
{!policyAvailable ? (
<PropertyRow label="Execution policy" wrap>
<span role="status" className="text-sm text-muted-foreground">Execution policy unavailable. Refresh to try again.</span>
</PropertyRow>
) : (<>
<PropertyPicker
inline={inline}
label="Reviewers"
@@ -2658,6 +2671,7 @@ export function IssueProperties({
)}
</PropertyPicker>
{nextRunnableExecutionStage === "approval" && approverValues.length > 0 ? runExecutionButton("approval") : null}
</>)}
{currentExecutionLabel && (
<PropertyRow label="Execution">
@@ -2684,6 +2698,7 @@ export function IssueProperties({
</PropertyPicker>
) : null}
{policyAvailable ? (
<PropertyPicker
inline={inline}
label="Monitor"
@@ -2695,6 +2710,7 @@ export function IssueProperties({
>
{monitorContent}
</PropertyPicker>
) : null}
<PropertyPicker
inline={inline}
+49
View File
@@ -0,0 +1,49 @@
// @vitest-environment jsdom
import { StrictMode, act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useExecutionPolicy } from "./useExecutionPolicy";
const capture = vi.hoisted(() => vi.fn());
vi.mock("../lib/sentry", () => ({ captureBrowserException: capture }));
function Policy({ value }: { value: unknown }) {
const result = useExecutionPolicy(value);
return <span>{result.success ? "available" : "unavailable"}</span>;
}
afterEach(() => capture.mockClear());
describe("execution policy diagnostics", () => {
it("normalizes valid omissions quietly", () => {
const container = document.createElement("div");
const root = createRoot(container);
act(() => root.render(<StrictMode><Policy value={{ monitor: { nextCheckAt: "2099-01-01T00:00:00Z" } }} /></StrictMode>));
expect(container.textContent).toBe("available");
expect(capture).not.toHaveBeenCalled();
act(() => root.unmount());
});
it("reports only a closed category once despite repeated rendering and refreshed objects", () => {
const container = document.createElement("div");
const root = createRoot(container);
const invalid = { stages: "synthetic-private-value", taskId: "synthetic-task-id", monitor: { notes: "synthetic-notes" } };
act(() => root.render(<StrictMode><Policy value={invalid} /></StrictMode>));
act(() => root.render(<StrictMode><Policy value={structuredClone(invalid)} /></StrictMode>));
expect(container.textContent).toBe("unavailable");
expect(capture).toHaveBeenCalledTimes(1);
const [error, details] = capture.mock.calls[0];
expect(error).toBeInstanceOf(Error);
expect(error.message).toBe("Invalid task execution policy (stages)");
expect(error.cause).toBeUndefined();
expect(details).toBeUndefined();
expect(Object.keys(error)).toEqual([]);
expect(error.stack).not.toContain("synthetic-");
act(() => root.render(<StrictMode><Policy value={{ stages: [] }} /></StrictMode>));
expect(container.textContent).toBe("available");
act(() => root.render(<StrictMode><Policy value={invalid} /></StrictMode>));
expect(capture).toHaveBeenCalledTimes(1);
act(() => root.unmount());
});
});
+23
View File
@@ -0,0 +1,23 @@
import { useEffect, useMemo, useRef } from "react";
import { readExecutionPolicy } from "../lib/issue-execution-policy";
import { captureBrowserException } from "../lib/sentry";
/** Keep an invalid policy visible without crashing the task or enabling edits. */
export function useExecutionPolicy(value: unknown) {
const result = useMemo(() => readExecutionPolicy(value), [value]);
const reported = useRef(false);
useEffect(() => {
if (result.success || reported.current) return;
reported.current = true;
// Schema diagnostics can contain the original data. Report only a closed
// field category, once per mounted component, through the existing gate.
const field = result.error.issues[0]?.path[0];
const category = field === "stages" ? "stages"
: field === "monitor" ? "monitor"
: field === "authorizationPolicy" ? "authorization"
: field === "reviewPreset" ? "review_preset"
: "policy";
captureBrowserException(new Error(`Invalid task execution policy (${category})`));
}, [result]);
return result;
}
+102 -2
View File
@@ -1,9 +1,40 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { issueExecutionPolicySchema } from "@paperclipai/shared";
import { buildExecutionPolicy } from "./issue-execution-policy";
import { issueExecutionPolicySchema, type IssueExecutionPolicy } from "@paperclipai/shared";
import { buildExecutionPolicy, stageParticipantValues } from "./issue-execution-policy";
const AGENT_ID = "00000000-0000-4000-8000-000000000001";
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const STAGE_ID = "00000000-0000-4000-8000-000000000002";
const PARTICIPANT_ID = "00000000-0000-4000-8000-000000000003";
describe("reading execution policy defaults", () => {
it.each([
{},
{ authorizationPolicy: { trustPreset: "standard" } },
{ monitor: { nextCheckAt: "2099-01-01T00:00:00.000Z" } },
{ stages: [{ type: "review" }] },
])("reads schema-valid omitted collections without changing the input: %j", (input) => {
expect(issueExecutionPolicySchema.safeParse(input).success).toBe(true);
const before = structuredClone(input);
expect(stageParticipantValues(input as IssueExecutionPolicy, "review")).toEqual([]);
expect(stageParticipantValues(input as IssueExecutionPolicy, "approval")).toEqual([]);
expect(input).toEqual(before);
});
it("retains configured reviewers when an unrelated stage omits participants", () => {
const policy = {
stages: [
{ type: "approval" },
{ id: STAGE_ID, type: "review", participants: [
{ id: PARTICIPANT_ID, type: "agent", agentId: AGENT_ID },
{ type: "user", userId: "board-reviewer" },
] },
],
} as IssueExecutionPolicy;
expect(stageParticipantValues(policy, "review")).toEqual([`agent:${AGENT_ID}`, "user:board-reviewer"]);
expect(stageParticipantValues(policy, "approval")).toEqual([]);
});
});
describe("buildExecutionPolicy", () => {
afterEach(() => {
@@ -36,4 +67,73 @@ describe("buildExecutionPolicy", () => {
expect(stage.participants[0]?.id).toMatch(UUID_PATTERN);
}
});
it("adds reviewers to a policy with omitted stages and retains other policy fields", () => {
const existingPolicy = {
authorizationPolicy: { trustPreset: "standard" },
maxReviewRounds: 4,
monitor: { nextCheckAt: "2099-01-01T00:00:00.000Z" },
} as IssueExecutionPolicy;
const before = structuredClone(existingPolicy);
const policy = buildExecutionPolicy({ existingPolicy, reviewerValues: [`agent:${AGENT_ID}`], approverValues: [] });
expect(issueExecutionPolicySchema.safeParse(policy).success).toBe(true);
expect(policy).toMatchObject(before);
expect(stageParticipantValues(policy, "review")).toEqual([`agent:${AGENT_ID}`]);
expect(existingPolicy).toEqual(before);
});
it("keeps stage and participant identities and governance fields when editing reviewers", () => {
const existingPolicy: IssueExecutionPolicy = {
mode: "normal", commentRequired: true, maxReviewRounds: 4,
authorizationPolicy: { trustPreset: "standard" },
stages: [{ id: STAGE_ID, type: "review", approvalsNeeded: 1, participants: [
{ id: PARTICIPANT_ID, type: "agent", agentId: AGENT_ID, userId: null },
] }],
};
const policy = buildExecutionPolicy({
existingPolicy, reviewerValues: [`agent:${AGENT_ID}`, "user:board-reviewer"], approverValues: [],
});
expect(policy).toMatchObject({
authorizationPolicy: existingPolicy.authorizationPolicy,
maxReviewRounds: 4,
stages: [{ id: STAGE_ID, participants: [
existingPolicy.stages[0].participants[0],
{ type: "user", userId: "board-reviewer" },
] }],
});
expect(issueExecutionPolicySchema.safeParse(policy).success).toBe(true);
});
it("does not remove authorization settings when the last reviewer is removed", () => {
const existingPolicy = {
mode: "normal", commentRequired: true, stages: [],
authorizationPolicy: { trustPreset: "standard" },
} as IssueExecutionPolicy;
expect(buildExecutionPolicy({ existingPolicy, reviewerValues: [], approverValues: [] }))
.toEqual(existingPolicy);
});
it.each([
{ maxReviewRounds: 4 },
{ maxReviewRounds: 4, stages: [{ id: STAGE_ID, type: "review", participants: [
{ id: PARTICIPANT_ID, type: "user", userId: "board-reviewer" },
] }] },
])("retains an independent review-round limit when no participants remain: %j", (existingPolicy) => {
expect(buildExecutionPolicy({ existingPolicy: existingPolicy as IssueExecutionPolicy, reviewerValues: [], approverValues: [] }))
.toEqual({ mode: "normal", commentRequired: true, stages: [], maxReviewRounds: 4 });
});
it("still clears a policy with no participants, monitor, or other settings", () => {
expect(buildExecutionPolicy({
existingPolicy: { mode: "normal", commentRequired: true, stages: [] },
reviewerValues: [], approverValues: [],
})).toBeNull();
});
it.each([{ stages: {} }, { stages: [null] }, { stages: [{ type: "review", participants: {} }] }])(
"refuses to manufacture a replacement for a malformed policy: %j", (input) => {
expect(() => buildExecutionPolicy({ existingPolicy: input as unknown as IssueExecutionPolicy,
reviewerValues: [], approverValues: [] })).toThrow();
},
);
});
+20 -6
View File
@@ -1,8 +1,15 @@
import type { IssueExecutionPolicy, IssueExecutionStageParticipant, IssueExecutionStagePrincipal } from "@paperclipai/shared";
import { issueExecutionPolicySchema } from "@paperclipai/shared";
import { parseAssigneeValue } from "./assignees";
import { createUuid as newId } from "./uuid";
type StageType = "review" | "approval";
const nullablePolicySchema = issueExecutionPolicySchema.nullable();
/** Apply wire-format defaults without treating an invalid policy as no policy. */
export function readExecutionPolicy(policy: unknown) {
return nullablePolicySchema.safeParse(policy ?? null);
}
function principalKey(principal: IssueExecutionStagePrincipal | IssueExecutionStageParticipant) {
return principal.type === "agent" ? `agent:${principal.agentId}` : `user:${principal.userId}`;
@@ -24,12 +31,14 @@ export function selectionValueFromPrincipal(principal: IssueExecutionStagePrinci
}
export function stageParticipantValues(policy: IssueExecutionPolicy | null | undefined, stageType: StageType): string[] {
const stage = policy?.stages.find((candidate) => candidate.type === stageType);
const parsed = readExecutionPolicy(policy);
if (!parsed.success) return [];
const stage = parsed.data?.stages.find((candidate) => candidate.type === stageType);
return stage?.participants.map((participant) => selectionValueFromPrincipal(participant)) ?? [];
}
function mergeParticipants(
existing: IssueExecutionStageParticipant[] | undefined,
existing: Array<IssueExecutionStagePrincipal & { id?: string }> | undefined,
values: string[],
): IssueExecutionStageParticipant[] {
const existingByKey = new Map((existing ?? []).map((participant) => [principalKey(participant), participant]));
@@ -54,11 +63,14 @@ export function buildExecutionPolicy(input: {
reviewerValues: string[];
approverValues: string[];
}): IssueExecutionPolicy | null {
const mode = input.existingPolicy?.mode ?? "normal";
const parsed = readExecutionPolicy(input.existingPolicy);
if (!parsed.success) throw new Error("Execution policy is unavailable");
const existingPolicy = parsed.data;
const mode = existingPolicy?.mode ?? "normal";
const stages: IssueExecutionPolicy["stages"] = [];
const monitor = input.existingPolicy?.monitor ?? null;
const existingReviewStage = input.existingPolicy?.stages.find((stage) => stage.type === "review");
const existingReviewStage = existingPolicy?.stages.find((stage) => stage.type === "review");
const reviewParticipants = mergeParticipants(existingReviewStage?.participants, input.reviewerValues);
if (reviewParticipants.length > 0) {
stages.push({
@@ -69,7 +81,7 @@ export function buildExecutionPolicy(input: {
});
}
const existingApprovalStage = input.existingPolicy?.stages.find((stage) => stage.type === "approval");
const existingApprovalStage = existingPolicy?.stages.find((stage) => stage.type === "approval");
const approvalParticipants = mergeParticipants(existingApprovalStage?.participants, input.approverValues);
if (approvalParticipants.length > 0) {
stages.push({
@@ -80,9 +92,11 @@ export function buildExecutionPolicy(input: {
});
}
if (stages.length === 0 && !monitor) return null;
if (stages.length === 0 && !monitor && !existingPolicy?.authorizationPolicy
&& !existingPolicy?.reviewPreset && existingPolicy?.maxReviewRounds == null) return null;
return {
...input.existingPolicy,
mode,
commentRequired: true,
stages,