[codex] Add issue document locking (#6009)

## Thinking Path

> - Paperclip orchestrates AI-agent companies through company-scoped
issues, comments, and issue documents.
> - Issue documents are the durable place where plans, handoffs, and
other work artifacts are revised over time.
> - Some documents need to be preserved as operator-approved snapshots
while agents continue working on the same issue.
> - Without document locking, a later board or agent write can overwrite
the document key that reviewers expected to remain stable.
> - This pull request adds board-managed issue document locks and makes
agent writes to locked keys create a derived document instead of
mutating the locked document.
> - The benefit is safer document handoffs: approved or frozen issue
documents stay immutable until the board explicitly unlocks them.

## What Changed

- Added `locked_at`, `locked_by_agent_id`, and `locked_by_user_id`
document fields plus migration `0085_tranquil_the_executioner.sql`.
- Added document lock/unlock service behavior, route endpoints, activity
events, and locked-document write protections.
- Made agent document writes to locked keys create a new derived key
such as `plan-2` rather than overwriting the locked document.
- Surfaced lock state through shared issue document types, UI API
methods, document header lock controls, and activity formatting.
- Added server and UI tests for lock/unlock behavior, locked document
immutability, and UI action visibility.
- Updated `doc/SPEC-implementation.md` with the V1 document lock
contract and endpoints.

## Verification

- `git rebase public-gh/master` completed cleanly after committing the
branch changes.
- `git diff --check` passed before commit.
- `pnpm run preflight:workspace-links && pnpm exec vitest run
server/src/__tests__/documents-service.test.ts
server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts
ui/src/components/IssueDocumentsSection.test.tsx
ui/src/components/IssueContinuationHandoff.test.tsx
ui/src/lib/document-revisions.test.ts` passed: 5 files, 32 tests.

## Risks

- Medium risk because this changes the document persistence contract and
adds a migration.
- The migration uses `ADD COLUMN IF NOT EXISTS` and guarded foreign-key
creation so it remains safe for users who may have already applied an
earlier copy of the migration.
- Locked documents intentionally reject board edits/deletes/restores
until unlocked; any existing workflows that expected direct overwrite
need to unlock first.
- Agent writes to locked keys now create derived documents, which may
create extra issue documents when agents retry locked writes.

## Model Used

- OpenAI Codex coding agent based on GPT-5, with tool use and local code
execution in the Paperclip worktree.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Dotta 2026-05-15 08:54:55 -05:00 committed by GitHub
parent 901c088e14
commit 03ad5c5bea
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 684 additions and 27 deletions

View file

@ -259,6 +259,10 @@ export const issuesApi = {
getDocument: (id: string, key: string) => api.get<IssueDocument>(`/issues/${id}/documents/${encodeURIComponent(key)}`),
upsertDocument: (id: string, key: string, data: UpsertIssueDocument) =>
api.put<IssueDocument>(`/issues/${id}/documents/${encodeURIComponent(key)}`, data),
lockDocument: (id: string, key: string) =>
api.post<IssueDocument>(`/issues/${id}/documents/${encodeURIComponent(key)}/lock`, {}),
unlockDocument: (id: string, key: string) =>
api.post<IssueDocument>(`/issues/${id}/documents/${encodeURIComponent(key)}/unlock`, {}),
listDocumentRevisions: (id: string, key: string) =>
api.get<DocumentRevision[]>(`/issues/${id}/documents/${encodeURIComponent(key)}/revisions`),
restoreDocumentRevision: (id: string, key: string, revisionId: string) =>

View file

@ -38,6 +38,9 @@ function createHandoffDocument(): IssueDocument {
createdByUserId: null,
updatedByAgentId: "agent-1",
updatedByUserId: null,
lockedAt: null,
lockedByAgentId: null,
lockedByUserId: null,
createdAt: new Date("2026-04-19T12:00:00.000Z"),
updatedAt: new Date("2026-04-19T12:05:00.000Z"),
};

View file

@ -15,6 +15,8 @@ const mockIssuesApi = vi.hoisted(() => ({
listDocumentRevisions: vi.fn(),
restoreDocumentRevision: vi.fn(),
upsertDocument: vi.fn(),
lockDocument: vi.fn(),
unlockDocument: vi.fn(),
deleteDocument: vi.fn(),
getDocument: vi.fn(),
}));
@ -178,6 +180,9 @@ function createIssueDocument(overrides: Partial<IssueDocument> = {}): IssueDocum
createdByUserId: "user-1",
updatedByAgentId: null,
updatedByUserId: "user-1",
lockedAt: null,
lockedByAgentId: null,
lockedByUserId: null,
createdAt: new Date("2026-03-31T12:00:00.000Z"),
updatedAt: new Date("2026-03-31T12:05:00.000Z"),
...overrides,
@ -306,6 +311,105 @@ describe("IssueDocumentsSection", () => {
queryClient.clear();
});
it("locks documents from the document header action", async () => {
const unlockedDocument = createIssueDocument({
body: "Draftable plan body",
lockedAt: null,
});
const lockedDocument = createIssueDocument({
body: "Draftable plan body",
lockedAt: new Date("2026-03-31T12:06:00.000Z"),
lockedByUserId: "user-1",
updatedAt: new Date("2026-03-31T12:06:00.000Z"),
});
const issue = createIssue();
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
mutations: {
retry: false,
},
},
});
mockIssuesApi.listDocuments
.mockResolvedValueOnce([unlockedDocument])
.mockResolvedValue([lockedDocument]);
mockIssuesApi.lockDocument.mockResolvedValue(lockedDocument);
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<IssueDocumentsSection issue={issue} canDeleteDocuments={false} canManageDocumentLocks />
</QueryClientProvider>,
);
});
await flush();
await flush();
const lockButton = container.querySelector('button[title="Lock document"]');
expect(lockButton).toBeTruthy();
await act(async () => {
lockButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flush();
expect(mockIssuesApi.lockDocument).toHaveBeenCalledWith("issue-1", "plan");
expect(container.querySelector('button[title="Unlock document"]')).toBeTruthy();
await act(async () => {
root.unmount();
});
queryClient.clear();
});
it("hides direct edit and delete actions for locked documents", async () => {
const issue = createIssue();
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
mutations: {
retry: false,
},
},
});
mockIssuesApi.listDocuments.mockResolvedValue([
createIssueDocument({
body: "Locked plan body",
lockedAt: new Date("2026-03-31T12:06:00.000Z"),
lockedByUserId: "user-1",
}),
]);
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<IssueDocumentsSection issue={issue} canDeleteDocuments canManageDocumentLocks />
</QueryClientProvider>,
);
});
await flush();
await flush();
expect(container.textContent).toContain("Locked plan body");
expect(container.textContent).not.toContain("Edit document");
expect(container.textContent).not.toContain("Delete document");
expect(container.querySelector('button[title="Unlock document"]')).toBeTruthy();
await act(async () => {
root.unmount();
});
queryClient.clear();
});
it("shows the restored document body immediately after a revision restore", async () => {
const blankLatestDocument = createIssueDocument({
body: "",

View file

@ -32,7 +32,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Check, ChevronDown, ChevronRight, Copy, Diff, Download, FilePenLine, FileText, MoreHorizontal, Plus, Trash2, X } from "lucide-react";
import { Check, ChevronDown, ChevronRight, Copy, Diff, Download, FilePenLine, FileText, Lock, MoreHorizontal, Plus, Trash2, Unlock, X } from "lucide-react";
import { DocumentDiffModal } from "./DocumentDiffModal";
type DraftState = {
@ -91,6 +91,10 @@ function isDocumentConflictError(error: unknown) {
return error instanceof ApiError && error.status === 409;
}
function isLockedDocumentError(error: unknown) {
return error instanceof ApiError && error.status === 409 && error.message === "Document is locked";
}
function downloadDocumentFile(key: string, body: string) {
const blob = new Blob([body], { type: "text/markdown;charset=utf-8" });
const url = URL.createObjectURL(blob);
@ -128,6 +132,9 @@ function toDocumentSummary(document: IssueDocument) {
createdByUserId: document.createdByUserId,
updatedByAgentId: document.updatedByAgentId,
updatedByUserId: document.updatedByUserId,
lockedAt: document.lockedAt,
lockedByAgentId: document.lockedByAgentId,
lockedByUserId: document.lockedByUserId,
createdAt: document.createdAt,
updatedAt: document.updatedAt,
};
@ -136,6 +143,7 @@ function toDocumentSummary(document: IssueDocument) {
export function IssueDocumentsSection({
issue,
canDeleteDocuments,
canManageDocumentLocks = false,
feedbackVotes = [],
feedbackDataSharingPreference = "prompt",
feedbackTermsUrl = null,
@ -146,6 +154,7 @@ export function IssueDocumentsSection({
}: {
issue: Issue;
canDeleteDocuments: boolean;
canManageDocumentLocks?: boolean;
feedbackVotes?: FeedbackVote[];
feedbackDataSharingPreference?: FeedbackDataSharingPreference;
feedbackTermsUrl?: string | null;
@ -279,6 +288,22 @@ export function IssueDocumentsSection({
},
});
const setDocumentLock = useMutation({
mutationFn: ({ key, locked }: { key: string; locked: boolean }) =>
locked ? issuesApi.lockDocument(issue.id, key) : issuesApi.unlockDocument(issue.id, key),
onSuccess: (document) => {
syncDocumentCaches(document);
setDraft((current) => current?.key === document.key ? null : current);
setDocumentConflict((current) => current?.key === document.key ? null : current);
resetAutosaveState();
setError(null);
invalidateIssueDocuments();
},
onError: (err) => {
setError(err instanceof Error ? err.message : "Failed to update document lock");
},
});
const sortedDocuments = useMemo(() => {
return (documents ?? []).filter((doc) => !isSystemIssueDocumentKey(doc.key)).sort((a, b) => {
if (a.key === "plan" && b.key !== "plan") return -1;
@ -442,6 +467,12 @@ export function IssueDocumentsSection({
}
return true;
} catch (err) {
if (isLockedDocumentError(err)) {
setError("Document is locked. Unlock it before editing.");
resetAutosaveState();
invalidateIssueDocuments();
return false;
}
if (isDocumentConflictError(err)) {
try {
const latestDocument = await issuesApi.getDocument(issue.id, normalizedKey);
@ -563,6 +594,15 @@ export function IssueDocumentsSection({
setError(null);
}, [documentConflict, draft, getDocumentRevisions, resetAutosaveState, returnToLatestRevision]);
const toggleDocumentLock = useCallback((doc: IssueDocument, locked: boolean) => {
if (!canManageDocumentLocks || setDocumentLock.isPending) return;
if (locked && (documentConflict?.key === doc.key || documentHasUnsavedChanges(doc, draft))) {
setError("Save or cancel local changes before changing the document lock.");
return;
}
setDocumentLock.mutate({ key: doc.key, locked });
}, [canManageDocumentLocks, documentConflict, draft, setDocumentLock]);
const handleDraftBlur = async (event: React.FocusEvent<HTMLDivElement>) => {
if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
if (autosaveDebounceRef.current) {
@ -789,8 +829,9 @@ export function IssueDocumentsSection({
<div className="space-y-3">
{sortedDocuments.map((doc) => {
const activeDraft = draft?.key === doc.key && !draft.isNew ? draft : null;
const activeConflict = documentConflict?.key === doc.key ? documentConflict : null;
const isLocked = Boolean(doc.lockedAt);
const activeDraft = !isLocked && draft?.key === doc.key && !draft.isNew ? draft : null;
const activeConflict = !isLocked && documentConflict?.key === doc.key ? documentConflict : null;
const isFolded = foldedDocumentKeys.includes(doc.key);
const rawRevisionHistory = getDocumentRevisions(doc.key);
const revisionState = deriveDocumentRevisionState(doc, rawRevisionHistory);
@ -809,6 +850,7 @@ export function IssueDocumentsSection({
const displayedUpdatedAt = selectedHistoricalRevision?.createdAt ?? currentRevision.createdAt;
const showTitle = !isPlanKey(doc.key) && !!displayedTitle.trim() && !titlesMatchKey(displayedTitle, doc.key);
const canVoteOnDocument = Boolean(doc.latestRevisionId && doc.updatedByAgentId && !doc.updatedByUserId && onVote);
const lockActionPending = setDocumentLock.isPending && setDocumentLock.variables?.key === doc.key;
return (
<div
@ -898,6 +940,26 @@ export function IssueDocumentsSection({
{showTitle && <p className="mt-2 text-sm font-medium">{displayedTitle}</p>}
</div>
<div className="flex items-center gap-1 shrink-0">
{canManageDocumentLocks ? (
<Button
variant="ghost"
size="icon-xs"
className={cn(
"text-muted-foreground transition-colors",
isLocked && "text-amber-300 hover:text-amber-200",
)}
title={isLocked ? "Unlock document" : "Lock document"}
aria-label={isLocked ? `Unlock ${doc.key} document` : `Lock ${doc.key} document`}
onClick={() => toggleDocumentLock(doc, !isLocked)}
disabled={lockActionPending}
>
{isLocked ? <Lock className="h-3.5 w-3.5" /> : <Unlock className="h-3.5 w-3.5" />}
</Button>
) : isLocked ? (
<span title="Locked document" aria-label="Locked document" className="inline-flex h-6 w-6 items-center justify-center text-amber-300">
<Lock className="h-3.5 w-3.5" />
</span>
) : null}
<Button
variant="ghost"
size="icon-xs"
@ -926,13 +988,13 @@ export function IssueDocumentsSection({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{!isHistoricalPreview ? (
{!isHistoricalPreview && !isLocked ? (
<DropdownMenuItem onClick={() => beginEdit(doc.key)}>
<FilePenLine className="h-3.5 w-3.5" />
Edit document
</DropdownMenuItem>
) : null}
{!isHistoricalPreview ? <DropdownMenuSeparator /> : null}
{!isHistoricalPreview && !isLocked ? <DropdownMenuSeparator /> : null}
<DropdownMenuItem
onClick={() => downloadDocumentFile(doc.key, displayedBody)}
>
@ -945,8 +1007,8 @@ export function IssueDocumentsSection({
View diff
</DropdownMenuItem>
) : null}
{canDeleteDocuments ? <DropdownMenuSeparator /> : null}
{canDeleteDocuments ? (
{canDeleteDocuments && !isLocked ? <DropdownMenuSeparator /> : null}
{canDeleteDocuments && !isLocked ? (
<DropdownMenuItem
variant="destructive"
onClick={() => setConfirmDeleteKey(doc.key)}
@ -997,18 +1059,20 @@ export function IssueDocumentsSection({
>
Return to latest
</Button>
<Button
size="sm"
onClick={() => restoreDocumentRevision.mutate({
key: doc.key,
revisionId: selectedHistoricalRevision.id,
})}
disabled={restoreDocumentRevision.isPending}
>
{restoreDocumentRevision.isPending && restoreDocumentRevision.variables?.key === doc.key
? "Restoring..."
: "Restore this revision"}
</Button>
{!isLocked ? (
<Button
size="sm"
onClick={() => restoreDocumentRevision.mutate({
key: doc.key,
revisionId: selectedHistoricalRevision.id,
})}
disabled={restoreDocumentRevision.isPending}
>
{restoreDocumentRevision.isPending && restoreDocumentRevision.variables?.key === doc.key
? "Restoring..."
: "Restore this revision"}
</Button>
) : null}
</div>
</div>
</div>

View file

@ -32,6 +32,8 @@ const ACTIVITY_ROW_VERBS: Record<string, string> = {
"issue.attachment_removed": "removed attachment from",
"issue.document_created": "created document for",
"issue.document_updated": "updated document on",
"issue.document_locked": "locked document on",
"issue.document_unlocked": "unlocked document on",
"issue.document_deleted": "deleted document from",
"issue.monitor_scheduled": "scheduled monitor on",
"issue.monitor_triggered": "triggered monitor for",
@ -88,6 +90,8 @@ const ISSUE_ACTIVITY_LABELS: Record<string, string> = {
"issue.attachment_removed": "removed an attachment",
"issue.document_created": "created a document",
"issue.document_updated": "updated a document",
"issue.document_locked": "locked a document",
"issue.document_unlocked": "unlocked a document",
"issue.document_deleted": "deleted a document",
"issue.monitor_scheduled": "scheduled a monitor",
"issue.monitor_triggered": "triggered a monitor",
@ -333,7 +337,13 @@ export function formatIssueActivityAction(
}
if (
(action === "issue.document_created" || action === "issue.document_updated" || action === "issue.document_deleted") &&
(
action === "issue.document_created" ||
action === "issue.document_updated" ||
action === "issue.document_locked" ||
action === "issue.document_unlocked" ||
action === "issue.document_deleted"
) &&
details
) {
const key = typeof details.key === "string" ? details.key : "document";

View file

@ -17,6 +17,9 @@ function createDocument(overrides: Partial<IssueDocument> = {}): IssueDocument {
createdByUserId: null,
updatedByAgentId: "agent-1",
updatedByUserId: null,
lockedAt: null,
lockedByAgentId: null,
lockedByUserId: null,
createdAt: new Date("2026-04-10T15:00:00.000Z"),
updatedAt: new Date("2026-04-10T16:00:00.000Z"),
...overrides,

View file

@ -3709,6 +3709,7 @@ export function IssueDetail() {
<IssueDocumentsSection
issue={issue}
canDeleteDocuments={Boolean(session?.user?.id)}
canManageDocumentLocks={Boolean(session?.user?.id)}
feedbackVotes={feedbackVotes}
feedbackDataSharingPreference={feedbackDataSharingPreference}
feedbackTermsUrl={FEEDBACK_TERMS_URL}

View file

@ -922,6 +922,9 @@ export const storybookIssueDocuments: IssueDocument[] = [
createdByUserId: null,
updatedByAgentId: "agent-codex",
updatedByUserId: null,
lockedAt: null,
lockedByAgentId: null,
lockedByUserId: null,
createdAt: recent(80),
updatedAt: recent(8),
},
@ -945,6 +948,9 @@ export const storybookIssueDocuments: IssueDocument[] = [
createdByUserId: "user-board",
updatedByAgentId: null,
updatedByUserId: "user-board",
lockedAt: null,
lockedByAgentId: null,
lockedByUserId: null,
createdAt: recent(55),
updatedAt: recent(12),
},
@ -970,6 +976,9 @@ export const storybookContinuationHandoff: IssueDocument = {
createdByUserId: null,
updatedByAgentId: "agent-codex",
updatedByUserId: null,
lockedAt: null,
lockedByAgentId: null,
lockedByUserId: null,
createdAt: recent(18),
updatedAt: recent(5),
};