Files
PaperClipAI/server/src/__tests__/documents-service.test.ts
T
Okan YücelandClaude Opus 5.5 dc8cf1e5d0 fix(documents): return the new body only after a document update or restore (#21036)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents and board users keep plans and specs as issue documents, and
they change them through the documents API
> - An update (`PUT /api/issues/{id}/documents/{key}`) and a revision
restore return the saved document
> - The service builds that result from the row it read before the
write, so the result also carries the old `latestBody`
> - A client that reads `latestBody` from the response gets the previous
revision's text, next to the new `latestRevisionId` and
`latestRevisionNumber`
> - This pull request removes the stale field from the update and
restore results, so they have the same shape as a document read
> - The benefit is that a write response never shows old text as the
latest text

## Linked Issues or Issue Description

I searched open and closed issues and pull requests for this bug and
found no match. The related work below touches the same service, but not
this bug:

- Refs #18277 (open: locks the document row during upsert and restore;
it does not change the result shape)
- Refs #18171 and #12015 (plugin upsert drops `baseRevisionId`; a
different bug)

**What happened?**
`PUT /api/issues/{id}/documents/{key}` on an existing document returned
200. The response had the new `body`, `latestRevisionId` and
`latestRevisionNumber`. It also had a `latestBody` field with the text
of the previous revision. A `GET` on the same document right after
returned only the new body. A restore (`POST
/api/issues/{id}/documents/{key}/revisions/{revisionId}/restore`) has
the same problem.

**Expected behavior**
The update and restore responses have the same document shape as `GET
/api/issues/{id}/documents/{key}` (the shared `IssueDocument` type).
That type has `body` and no `latestBody`. No field in the response holds
text from an older revision.

**Steps to reproduce**
1. Create an issue document with body `A`.
2. Update it with body `B` and `baseRevisionId` set to the current
revision.
3. Read the response: `body` is `B`, but `latestBody` is `A`.
4. Restore revision 1. The response `latestBody` is `B`, the body before
the restore.

**Paperclip version or commit**
Seen on a current npm release. Reproduced on `master` at 51d77648bc with
the new service test.

**Deployment mode**
Not deployment-specific. The bug is in
`server/src/services/documents.ts`.

**Agent adapter(s) involved**
Not adapter-specific (core bug).

## What Changed

- `server/src/services/documents.ts`: the update path of
`upsertIssueDocument` and the `restoreIssueDocumentRevision` path remove
`latestBody` from the row they read before the write. Then they spread
the remaining fields into the result. The `body` field stays the new
text, as before.
- `server/src/__tests__/documents-service.test.ts`: a new test updates a
document and restores its first revision. It checks that each result is
equal to a fresh `getIssueDocumentByKey` read and has no `latestBody`
field.

## Verification

- Red-green, as AGENTS.md section 10 asks:
- Before the fix, the new test failed on the update result: `latestBody:
"# Plan"` (the old body) was in the response.
- With only the update fix applied, the test failed on the restore
result: `latestBody: "# Second plan"` (the body before the restore).
  - With both fixes, the test passes.
- `npx vitest run` on the 9 test files that write or read issue
documents through the service and routes: `documents`,
`documents-service`, `issue-document-restore-routes`,
`document-annotation-routes`, `document-annotations-service`,
`artifact-review-documents-service`, `artifact-review-document-routes`,
`native-plan-proposal-sync`, `case-mutation-fence.integration`. Result:
9 files, 68 tests passed.
- `pnpm --filter @paperclipai/server typecheck` passed.
- I did not run `pnpm verify` locally. The change is in a service that
the routes import, so the selection is very broad. The required CI
checks supply the broad coverage, as AGENTS.md section 7 allows.

## Risks

- Low risk. The response no longer has the undocumented `latestBody`
field. That field is not in the shared `IssueDocument` type, and after
an update or restore it always held old text. A client that read it got
wrong data. The routes read `id`, `key`, `title`, `format`,
`latestRevisionId`, `latestRevisionNumber` and `body` from the result.
Those fields do not change.
- No database or migration change.

## Model Used

- Provider: Anthropic. Model: Claude Opus 5.5 (`claude-opus-5-5`), in
Claude Code, with tool use (shell, file edit) and extended thinking. The
run did not show the context window size to the model, so I do not state
a number.
- The model found the cause, wrote the test and the fix, and ran the
checks above.

## 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 (no
update needed: the documented response shape does not change)
- [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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:34:11 -06:00

298 lines
12 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
agents,
companies,
createDb,
documentRevisions,
documents,
heartbeatRuns,
issueDocuments,
issues,
} from "@paperclipai/db";
import { ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY } from "@paperclipai/shared";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { documentService } from "../services/documents.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
if (!embeddedPostgresSupport.supported) {
console.warn(
`Skipping embedded Postgres document service tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
);
}
describeEmbeddedPostgres("documentService system issue documents", () => {
let db!: ReturnType<typeof createDb>;
let svc!: ReturnType<typeof documentService>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-documents-service-");
db = createDb(tempDb.connectionString);
svc = documentService(db);
}, 20_000);
afterEach(async () => {
await db.delete(documentRevisions);
await db.delete(issueDocuments);
await db.delete(documents);
await db.delete(issues);
await db.delete(heartbeatRuns);
await db.delete(agents);
await db.delete(companies);
});
afterAll(async () => {
await tempDb?.cleanup();
});
async function createIssueWithDocuments() {
const companyId = randomUUID();
const issueId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
});
await db.insert(issues).values({
id: issueId,
companyId,
identifier: "PAP-1600",
title: "System document filtering",
description: "Validate document filtering",
status: "in_progress",
priority: "medium",
});
await svc.upsertIssueDocument({
issueId,
key: "plan",
title: "Plan",
format: "markdown",
body: "# Plan",
createdByUserId: "board-user",
});
await svc.upsertIssueDocument({
issueId,
key: ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,
title: "Continuation Summary",
format: "markdown",
body: "# Handoff",
});
return { issueId, companyId };
}
it("filters continuation summaries from default document lists and issue payload summaries", async () => {
const { issueId } = await createIssueWithDocuments();
const defaultDocuments = await svc.listIssueDocuments(issueId);
expect(defaultDocuments.map((doc) => doc.key)).toEqual(["plan"]);
const payload = await svc.getIssueDocumentPayload({ id: issueId, description: null });
expect(payload.planDocument?.key).toBe("plan");
expect(payload.documentSummaries.map((doc) => doc.key)).toEqual(["plan"]);
});
it("reads one pinned revision and never substitutes a newer or unrelated document", async () => {
const { issueId } = await createIssueWithDocuments();
const original = await svc.getIssueDocumentByKey(issueId, "plan");
await svc.upsertIssueDocument({ issueId, key: "plan", format: "markdown", body: "# Newer plan", baseRevisionId: original!.latestRevisionId });
const pinned = await svc.getIssueDocumentRevision(issueId, "plan", original!.latestRevisionId!);
expect(pinned?.body).toBe("# Plan");
expect(pinned?.id).toBe(original!.latestRevisionId);
const current = await svc.getIssueDocumentByKey(issueId, "plan");
expect(pinned).toMatchObject({ isLatest: false, latestRevisionId: current!.latestRevisionId, latestRevisionNumber: 2 });
expect(await svc.getIssueDocumentRevision(issueId, "plan", current!.latestRevisionId!)).toMatchObject({ isLatest: true, revisionNumber: 2, body: "# Newer plan" });
expect(await svc.getIssueDocumentRevision(issueId, "other-document", original!.latestRevisionId!)).toBeNull();
expect(await svc.getIssueDocumentRevision(randomUUID(), "plan", original!.latestRevisionId!)).toBeNull();
expect(await svc.getIssueDocumentRevision(issueId, "plan", randomUUID())).toBeNull();
});
it("keeps system documents available for includeSystem and direct fetch callers", async () => {
const { issueId } = await createIssueWithDocuments();
const debugDocuments = await svc.listIssueDocuments(issueId, { includeSystem: true });
expect(debugDocuments.map((doc) => doc.key)).toEqual([
ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,
"plan",
]);
const directHandoff = await svc.getIssueDocumentByKey(issueId, ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY);
expect(directHandoff).toEqual(expect.objectContaining({
key: ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,
body: "# Handoff",
}));
});
it("returns each actual writer run in revision history without attributing human revisions to a run", async () => {
const { issueId, companyId } = await createIssueWithDocuments();
const agentId = randomUUID(), firstRunId = randomUUID(), secondRunId = randomUUID();
await db.insert(agents).values({ id: agentId, companyId, name: "Receipt writer", role: "engineer", adapterType: "process" });
await db.insert(heartbeatRuns).values([firstRunId, secondRunId].map(id => ({ id, companyId, agentId,
status: "succeeded", invocationSource: "assignment", triggerDetail: "system", contextSnapshot: { issueId } })));
const first = await svc.upsertIssueDocument({ issueId, key: "receipt", title: "Receipt", format: "markdown",
body: '{"total":6}', createdByAgentId: agentId, createdByRunId: firstRunId });
const second = await svc.upsertIssueDocument({ issueId, key: "receipt", title: "Receipt", format: "markdown",
body: '{"total":6,"currency":"USD"}', createdByAgentId: agentId, createdByRunId: secondRunId,
baseRevisionId: first.document.latestRevisionId });
expect(await svc.listIssueDocumentRevisions(issueId, "receipt")).toMatchObject([
{ id: second.document.latestRevisionId, revisionNumber: 2, createdByAgentId: agentId, createdByRunId: secondRunId,
body: '{"total":6,"currency":"USD"}' },
{ id: first.document.latestRevisionId, revisionNumber: 1, createdByAgentId: agentId, createdByRunId: firstRunId,
body: '{"total":6}' },
]);
expect(await svc.listIssueDocumentRevisions(issueId, "plan")).toMatchObject([{ createdByUserId: "board-user", createdByRunId: null }]);
expect(await svc.listIssueDocumentRevisions(randomUUID(), "receipt")).toEqual([]);
});
it("explains the revision guard and rejects missing or stale update revisions without changing the document", async () => {
const { issueId } = await createIssueWithDocuments();
const current = (await svc.getIssueDocumentByKey(issueId, "plan"))!;
const update = {
issueId,
key: "plan",
title: "Plan",
format: "markdown" as const,
body: "# Revised plan",
};
await expect(svc.upsertIssueDocument(update)).rejects.toMatchObject({
status: 409,
message: expect.stringContaining("set baseRevisionId to that latestRevisionId"),
details: { currentRevisionId: current.latestRevisionId },
});
expect(await svc.getIssueDocumentByKey(issueId, "plan")).toMatchObject({
body: current.body,
latestRevisionId: current.latestRevisionId,
});
const saved = await svc.upsertIssueDocument({ ...update, baseRevisionId: current.latestRevisionId });
expect(saved.document.body).toBe(update.body);
expect(saved.document.latestRevisionNumber).toBe(current.latestRevisionNumber + 1);
await expect(svc.upsertIssueDocument({
...update,
body: "# Stale replacement",
baseRevisionId: current.latestRevisionId,
})).rejects.toMatchObject({ status: 409, message: "Document was updated by someone else" });
expect(await svc.getIssueDocumentByKey(issueId, "plan")).toMatchObject({
body: saved.document.body,
latestRevisionId: saved.document.latestRevisionId,
});
});
it("returns the saved document from update and restore exactly as a fresh read returns it", async () => {
const { issueId } = await createIssueWithDocuments();
const original = (await svc.getIssueDocumentByKey(issueId, "plan"))!;
const updated = await svc.upsertIssueDocument({
issueId,
key: "plan",
title: "Plan",
format: "markdown",
body: "# Second plan",
baseRevisionId: original.latestRevisionId,
});
expect(updated.document).toEqual(await svc.getIssueDocumentByKey(issueId, "plan"));
expect(updated.document).not.toHaveProperty("latestBody");
const restored = await svc.restoreIssueDocumentRevision({
issueId,
key: "plan",
revisionId: original.latestRevisionId!,
});
expect(restored.document.body).toBe(original.body);
expect(restored.document).toEqual(await svc.getIssueDocumentByKey(issueId, "plan"));
expect(restored.document).not.toHaveProperty("latestBody");
});
it("locks and unlocks issue documents", async () => {
const { issueId } = await createIssueWithDocuments();
const locked = await svc.lockIssueDocument({
issueId,
key: "plan",
lockedByUserId: "board-user",
});
expect(locked.changed).toBe(true);
expect(locked.document.lockedAt).toBeInstanceOf(Date);
expect(locked.document.lockedByUserId).toBe("board-user");
await expect(svc.upsertIssueDocument({
issueId,
key: "plan",
title: "Plan",
format: "markdown",
body: "# Updated plan",
baseRevisionId: locked.document.latestRevisionId,
createdByUserId: "board-user",
})).rejects.toMatchObject({
status: 409,
message: "Document is locked",
});
const unlocked = await svc.unlockIssueDocument(issueId, "plan");
expect(unlocked.changed).toBe(true);
expect(unlocked.document.lockedAt).toBeNull();
const updated = await svc.upsertIssueDocument({
issueId,
key: "plan",
title: "Plan",
format: "markdown",
body: "# Updated plan",
baseRevisionId: unlocked.document.latestRevisionId,
createdByUserId: "board-user",
});
expect(updated.created).toBe(false);
expect(updated.document.body).toBe("# Updated plan");
});
it("creates a new document instead of updating a locked document when requested", async () => {
const { issueId } = await createIssueWithDocuments();
const locked = await svc.lockIssueDocument({
issueId,
key: "plan",
lockedByUserId: "board-user",
});
const fallback = await svc.upsertIssueDocument({
issueId,
key: "plan",
title: "Plan",
format: "markdown",
body: "# Agent replacement plan",
baseRevisionId: locked.document.latestRevisionId,
lockedDocumentStrategy: "create_new_document",
});
expect(fallback.created).toBe(true);
expect(fallback.document.key).toBe("plan-2");
expect(fallback.document.body).toBe("# Agent replacement plan");
expect("redirectedFromLockedDocument" in fallback ? fallback.redirectedFromLockedDocument : null)
.toEqual({ id: locked.document.id, key: "plan" });
const originalPlan = await svc.getIssueDocumentByKey(issueId, "plan");
expect(originalPlan).toEqual(expect.objectContaining({
body: "# Plan",
lockedAt: expect.any(Date),
}));
const newPlan = await svc.getIssueDocumentByKey(issueId, "plan-2");
expect(newPlan).toEqual(expect.objectContaining({
body: "# Agent replacement plan",
lockedAt: null,
}));
});
});