From 20ffa6b0a387b09338dd4ec2793fc7119e59383e Mon Sep 17 00:00:00 2001 From: Andrii Vasyliev Date: Sat, 5 Dec 2026 12:24:03 +0200 Subject: [PATCH] fix(prompt): reference the exact plan revision on resumed turns (#17769) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Each heartbeat run gives the agent task Markdown, and a task can have a revisioned plan document > - A resumed session gets a compact variant of that Markdown, because the session already received the assignment brief > - The compact variant already leaves out the issue description, but it still repeats the full plan body on every resumed wake > - A long plan therefore grows every resumed prompt, although the session already has the plan > - This pull request keeps the exact plan document and revision pointer in the compact variant and drops the body > - The benefit is smaller resumed prompts without a weaker plan contract: the agent reads that exact revision when it does not have it ## Linked Issues or Issue Description No public issue exists for this. I searched open and closed issues and pull requests for the task plan in resumed prompts and for changes to `server/src/services/heartbeat/task-markdown.ts` and `task-context.ts`. Related prompt-size work: #17584 (skip static notes on resumed ACPX sessions), #17342 and #16645 (bound the execution continuation). **What existing behavior does this improve?** `buildPaperclipTaskMarkdown` with `includeDescription: false` builds the compact task Markdown for resumed sessions. It still writes the full `Task plan document …` body in a fenced block on every resumed wake. **Subsystem affected** Heartbeat task context (`server/src/services/heartbeat/task-markdown.ts`, `server/src/services/heartbeat/task-context.ts`). **Current behavior** Every resumed wake repeats the full plan body, even when the plan did not change and the session already holds it. **Proposed behavior** The compact variants keep the line `Task plan document , revision ():` and the work-mode rule. In place of the body, they tell the agent to read that exact revision through `GET /api/issues/{id}/documents/plan` (or its `/revisions` list) when the session does not have it, and not to use a later draft or infer approval. The full variants do not change. **Reason and benefit** Resumed prompts stay smaller. A changed plan still shows a new revision id, so the agent can see that it must read the new revision. ## What Changed - `buildPaperclipTaskMarkdown` accepts `includePlanBody`. When it is `false`, the plan section keeps the document and revision pointer and replaces the fenced body with the read instruction. - `prepareHeartbeatTaskContext` passes `includePlanBody: false` only for `paperclipTaskMarkdownCompact` and `paperclipTaskMarkdownAssignmentCompact`. Fresh attempts and assignment-shaped wakes use the full variants and still get the body. - A quarantined low-trust plan seen by a higher-trust agent keeps its withheld-body notice in the compact variants instead of the read instruction, because the issue document routes return the stored body without the quarantine filter. - Add unit tests for the compact plan section in all work modes, for a changed revision and for rejected-plan rules. - Add a database-backed test that runs a real heartbeat with a plan document and checks all four task Markdown variants. Another one checks all four variants for a quarantined plan. ## Verification On the head rebased onto `master` `7e8901aa60` (the later rebase onto `7cd5558e41` did not change any file this PR touches): - `npx vitest run src/__tests__/heartbeat-context-summary.test.ts src/__tests__/heartbeat-task-context.test.ts` in `server`: 2 files, 70 tests passed (with embedded PostgreSQL). - Without the source change, the two new plan tests fail (checked before the rebase). Without the quarantine change, the quarantined-plan test fails. - `pnpm --filter @paperclipai/server typecheck` (all layers, including the test trees): no errors. `pnpm check:tokens` and `pnpm check:module-boundaries` pass. ## Risks - A resumed session that lost the plan from its context must call the API to read it. The prompt names the exact endpoint and revision. - Approval and work-mode rules do not change. The rejected-plan text stays in the compact variant. > 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`. ## Model Used AI-assisted with Claude Code and OpenAI Codex coding agents; exact model versions are not listed. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [ ] 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 (none needed: no documented behavior or setup 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Co-authored-by: a-vasyliev <1255946+a-vasyliev@users.noreply.github.com> --- .../heartbeat-context-summary.test.ts | 30 +++++ .../heartbeat-task-plan-context.test.ts | 108 ++++++++++++++++++ server/src/services/heartbeat/task-context.ts | 9 +- .../src/services/heartbeat/task-markdown.ts | 5 +- 4 files changed, 147 insertions(+), 5 deletions(-) create mode 100644 server/src/__tests__/heartbeat-task-plan-context.test.ts diff --git a/server/src/__tests__/heartbeat-context-summary.test.ts b/server/src/__tests__/heartbeat-context-summary.test.ts index f1e014e4ec3..ae32514fb70 100644 --- a/server/src/__tests__/heartbeat-context-summary.test.ts +++ b/server/src/__tests__/heartbeat-context-summary.test.ts @@ -162,6 +162,36 @@ describe("buildPaperclipTaskMarkdown", () => { taskPlan, })).not.toContain("ACCEPTANCE_PHRASE"); }); + it("replaces repeated plan text with exact revision evidence only in the compact variant", () => { + const taskPlan = { documentId: "document", revisionId: "revision", revisionNumber: 7, + body: "ACCEPTANCE_PHRASE and detailed requirements.\n".repeat(400) }; + for (const workMode of ["standard", "planning", "ask"]) { + const input = { issue: { id: "task", identifier: "TASK-1", title: "Work", workMode }, taskPlan }; + const full = buildPaperclipTaskMarkdown(input)!; + const compact = buildPaperclipTaskMarkdown({ ...input, includeDescription: false, includePlanBody: false })!; + expect(full).toContain(taskPlan.body.trim()); + expect(compact).not.toContain("ACCEPTANCE_PHRASE"); + expect(compact).toContain("revision 7 (revision)"); + expect(compact).toContain("/api/issues/task/documents/plan"); + expect(compact).toContain("If this exact revision is not already in the resumed session"); + expect(compact).toContain("Follow the current work mode and any required approvals"); + expect(compact.length).toBeLessThan(full.length / 3); + if (workMode === "planning") expect(compact).toContain("Make the plan only"); + if (workMode === "ask") expect(compact).toContain("Answer the question directly"); + const changed = buildPaperclipTaskMarkdown({ ...input, taskPlan: { ...taskPlan, revisionId: "new-revision", body: "Changed scope" }, includePlanBody: false }); + expect(changed).toContain("new-revision"); + expect(changed).not.toContain("revision 7 (revision)"); + } + }); + + it("preserves rejected-plan restrictions when plan text is compacted", () => { + const prompt = buildPaperclipTaskMarkdown({ issue: { id: "task", identifier: null, title: "Work", workMode: "planning" }, + taskPlan: { documentId: "doc", revisionId: "rev", revisionNumber: 1, body: "Do the work" }, + planReview: { status: "rejected", reason: "Revise the design first" }, includePlanBody: false }); + expect(prompt).toContain("The user rejected the plan"); + expect(prompt).toContain("This is not approval to implement"); + }); + it("hands an accepted chat plan to assigned project tasks using the approved revision", () => { const prompt = buildPaperclipTaskMarkdown({ issue: { id: "chat", identifier: null, title: "Agent chat", workMode: "planning", conversationAgentId: "agent", description: null }, diff --git a/server/src/__tests__/heartbeat-task-plan-context.test.ts b/server/src/__tests__/heartbeat-task-plan-context.test.ts new file mode 100644 index 00000000000..31bf704fddc --- /dev/null +++ b/server/src/__tests__/heartbeat-task-plan-context.test.ts @@ -0,0 +1,108 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agents, authUsers, companies, companyMemberships, createDb, documentRevisions, documents, heartbeatRuns, issueDocuments, issues } from "@paperclipai/db"; +import { registerServerAdapter, unregisterServerAdapter, type AdapterExecutionContext } from "../adapters/index.js"; +import { heartbeatService } from "../services/heartbeat.js"; +import { documentService } from "../services/documents.js"; +import { buildLowTrustSourceTrust, LOW_TRUST_QUARANTINED_BODY } from "../services/source-trust.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const describePostgres = support.supported ? describe : describe.skip; +if (!support.supported) console.warn(`Skipping heartbeat task plan context tests: ${support.reason}`); + +describePostgres("heartbeat task plan context on resumed turns", () => { + const adapterType = "task_context_test"; + const captured = new Map(); + const inspectPreparation = new Map void>(); + let temporary: Awaited>; + let db: ReturnType; + let heartbeat: ReturnType; + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("heartbeat-task-plan-context-"); + db = createDb(temporary.connectionString); + await db.insert(authUsers).values({ id: "context-user", name: "Context user", email: "context-user@example.test", + createdAt: new Date(), updatedAt: new Date() }); + heartbeat = heartbeatService(db); + registerServerAdapter({ + type: adapterType, + supportsLocalAgentJwt: false, + execute: async (input) => { + inspectPreparation.get(input.agent.id)?.(); + captured.set(input.runId, input); + return { exitCode: 0, signal: null, timedOut: false, sessionId: "context-session", resultJson: {} }; + }, + testEnvironment: async () => ({ adapterType, status: "pass", checks: [], testedAt: new Date().toISOString() }), + }); + }, 30_000); + + afterAll(async () => { + await heartbeat?.drainActiveRunExecutions(); + unregisterServerAdapter(adapterType); + await db?.$client.end({ timeout: 0 }); + await temporary?.cleanup(); + }); + + async function seed() { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Task context fixture", issuePrefix: `T${companyId.slice(0, 6)}` }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "context-user", + membershipRole: "member", status: "active" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Context reader", adapterType, status: "idle" }); + await db.insert(issues).values({ + id: issueId, companyId, title: "Task context fixture", description: "Assignment description canary", + status: "todo", assigneeAgentId: agentId, responsibleUserId: "context-user", issueNumber: 1, + }); + return { companyId, agentId, issueId }; + } + + async function execute(f: Awaited>, context: Record) { + const run = await heartbeat.wakeup(f.agentId, { + source: "on_demand", triggerDetail: "manual", reason: "issue_assigned", + payload: { issueId: f.issueId }, contextSnapshot: { issueId: f.issueId, ...context }, + }); + expect(run).not.toBeNull(); + await heartbeat.drainActiveRunExecutions(); + const finished = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run!.id)).then(rows => rows[0]); + expect(finished?.status, finished?.error ?? undefined).toBe("succeeded"); + expect(captured.has(run!.id)).toBe(true); + return captured.get(run!.id)!; + } + + it("sends the plan body on fresh attempts and only the exact revision pointer on resumed turns", async () => { + const f = await seed(); + const documentId = randomUUID(), revisionId = randomUUID(); + const body = "Plan body canary with acceptance criteria"; + await db.insert(documents).values({ id: documentId, companyId: f.companyId, latestBody: body, latestRevisionId: revisionId }); + await db.insert(documentRevisions).values({ id: revisionId, documentId, companyId: f.companyId, revisionNumber: 3, body }); + await db.insert(issueDocuments).values({ companyId: f.companyId, issueId: f.issueId, documentId, key: "plan" }); + const { context } = await execute(f, {}); + const pointer = `Task plan document ${documentId}, revision 3 (${revisionId}):`; + for (const key of ["paperclipTaskMarkdown", "paperclipTaskMarkdownAssignment"]) { + expect(context[key]).toContain(pointer); + expect(context[key]).toContain(body); + } + for (const key of ["paperclipTaskMarkdownCompact", "paperclipTaskMarkdownAssignmentCompact"]) { + expect(context[key]).toContain(pointer); + expect(context[key]).toContain(`/api/issues/${f.issueId}/documents/plan`); + expect(context[key]).not.toContain(body); + } + }); + + it("keeps the withheld-body notice instead of a read instruction for a quarantined plan on resumed turns", async () => { + const f = await seed(); + await documentService(db).upsertIssueDocument({ + issueId: f.issueId, key: "plan", format: "markdown", + body: "QUARANTINED plan canary", sourceTrust: buildLowTrustSourceTrust({ issueId: f.issueId }), + }); + const { context } = await execute(f, {}); + for (const key of ["paperclipTaskMarkdown", "paperclipTaskMarkdownAssignment", "paperclipTaskMarkdownCompact", "paperclipTaskMarkdownAssignmentCompact"]) { + expect(context[key]).toContain(LOW_TRUST_QUARANTINED_BODY); + expect(context[key]).not.toContain("QUARANTINED plan canary"); + expect(context[key]).not.toContain("If this exact revision is not already in the resumed session"); + } + }); + +}); diff --git a/server/src/services/heartbeat/task-context.ts b/server/src/services/heartbeat/task-context.ts index 5450122166c..2bbe8177bb8 100644 --- a/server/src/services/heartbeat/task-context.ts +++ b/server/src/services/heartbeat/task-context.ts @@ -12,7 +12,7 @@ import { buildExecutionContinuation } from "../execution-continuation.js"; import { getIssueContinuationSummaryDocument } from "../issue-continuation-summary.js"; import type { issueService } from "../issues.js"; import { createRunSecretRedactionRegistry } from "../run-secret-redaction.js"; -import { redactQuarantinedBodyForHigherTrust, sanitizeQuarantinedCommentForHigherTrust } from "../source-trust.js"; +import { isLowTrustQuarantined, redactQuarantinedBodyForHigherTrust, sanitizeQuarantinedCommentForHigherTrust } from "../source-trust.js"; import { getTaskPlanContext } from "../task-plan-context.js"; import { loadResponsibilityBarGuidance } from "../responsibility-bar-guidance.js"; import { loadAutomationConversationGuidance } from "../automation-conversation-guidance.js"; @@ -453,14 +453,15 @@ export async function prepareHeartbeatTaskContext(db: Db, input: HeartbeatTaskCo ? await loadStandingCheckGuidance(db, { companyId: agent.companyId, agentId: agent.id }) : null; // A wake with no task builds no task markdown; never let that read as "null". - const markdown = (options: { includeDescription?: boolean; includeWakeComments?: boolean }) => + const compactPlanBody = !exposeLowTrustRaw && isLowTrustQuarantined(taskPlan?.sourceTrust); + const markdown = (options: { includeDescription?: boolean; includeWakeComments?: boolean; includePlanBody?: boolean }) => assignmentPrefix + [buildPaperclipTaskMarkdown({ ...taskMarkdownInput, taskPlan, ...options }), standingChecks].filter(Boolean).join("\n\n") + chatCompletionInstruction(context); let taskMarkdown = markdown({}); let taskMarkdownAssignment = markdown({ includeWakeComments: false }); - const taskMarkdownCompact = markdown({ includeDescription: false }); - const taskMarkdownAssignmentCompact = markdown({ includeDescription: false, includeWakeComments: false }); + const taskMarkdownCompact = markdown({ includeDescription: false, includePlanBody: compactPlanBody }); + const taskMarkdownAssignmentCompact = markdown({ includeDescription: false, includePlanBody: compactPlanBody, includeWakeComments: false }); if (issueRef) { context.paperclipIssue = { id: issueRef.id, diff --git a/server/src/services/heartbeat/task-markdown.ts b/server/src/services/heartbeat/task-markdown.ts index 6349be2e111..12abe041a03 100644 --- a/server/src/services/heartbeat/task-markdown.ts +++ b/server/src/services/heartbeat/task-markdown.ts @@ -104,6 +104,7 @@ export function buildPaperclipTaskMarkdown(input: { // false builds the compact variant used for resume deltas, where the session // already received the description with the assignment. includeDescription?: boolean; + includePlanBody?: boolean; // Current wake events are rendered by the structured wake prompt on // adapter lanes. Keep the legacy default for standalone callers. includeWakeComments?: boolean; @@ -382,7 +383,9 @@ export function buildPaperclipTaskMarkdown(input: { "", `Task plan document ${input.taskPlan.documentId}, revision ${input.taskPlan.revisionNumber} (${input.taskPlan.revisionId}):`, "Use this plan as assignment context, including its outcome and acceptance criteria. Follow the current work mode and any required approvals.", - fenceTaskText(input.taskPlan.body.trim()), + ...(input.includePlanBody === false + ? [`If this exact revision is not already in the resumed session, read it before implementation: GET /api/issues/${encodeURIComponent(issue.id)}/documents/plan (or its /revisions list for a retained revision). Verify the document and revision; never substitute a later draft or infer approval.`] + : [fenceTaskText(input.taskPlan.body.trim())]), ); } }