From a2984a0a9d42a35e3fed8b291f8b0f9d1480cae8 Mon Sep 17 00:00:00 2001 From: Dotta Date: Wed, 30 Sep 2026 02:15:04 -0500 Subject: [PATCH] Preserve historical Cursor plan proof query bounds Retain the original Cursor6 event filter when verifying an exact committed wait. Progress rows remain part of Cursor7 lifecycle proof without consuming the historical query budget. Co-Authored-By: Paperclip --- .../heartbeat-process-recovery.test.ts | 31 ++++++++++++++++--- .../native-runtime/native-cursor-plan-wait.ts | 14 +++++++-- 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.ts index 7dc87f02e08..70aa2a42d18 100644 --- a/server/src/__tests__/heartbeat-process-recovery.test.ts +++ b/server/src/__tests__/heartbeat-process-recovery.test.ts @@ -13733,7 +13733,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { }); afterEach(() => { mockExecutePaperclipNativeSession.mockImplementation(nativeImplementation!); }); - async function seedAcceptedCursorPlanWait(semanticFinish = false) { + async function seedAcceptedCursorPlanWait(semanticFinish = false, sourceSequenceOffset = 0) { const f = await seedStrandedIssueFixture({ status: "in_progress", runStatus: "succeeded", livenessState: "advanced" }); const contractId = randomUUID(), instance = randomUUID(), interactionId = randomUUID(); const contract = { revision: "1", objective: "Review the plan before further work", criteria: [{ id: "objective", requirement: "Explicit completion required" }] }; @@ -13770,7 +13770,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { { eventType: "tool.execution.completed", payload: { schema: "paperclip.tool.execution.v1", executionId: "native-plan-tool", transport: "builtin", operation: "execute", status: "completed", readOnly: false, namespace: null, name: "Create Plan", target: null, inputUpdated: false, output: null, outputBytes: 0, outputTruncated: false, outputDigest: null, progress: null, exitCode: null, durationMs: null } }, { eventType: "turn.completed", payload: { status: "completed", error: null } }, ]; - for (const [index, event] of events.entries()) await port.appendEvent({ schema: "paperclip.prp.event.v1", sourceEventId: `${instance}:${index + 1}`, sourceSeq: index + 1, + for (const [index, event] of events.entries()) await port.appendEvent({ schema: "paperclip.prp.event.v1", sourceEventId: `${instance}:${sourceSequenceOffset + index + 1}`, sourceSeq: sourceSequenceOffset + index + 1, sourceInstanceId: instance, sourceKind: "runner", runId: f.runId, normalizedSessionId: f.runId, turnId: "turn", schemaVersion: 1, priority: 0, emittedAt: new Date().toISOString(), ...event } as paperclipRunner.PrpEvent); const proof = await readNativeCursorPlanWait(db, f); @@ -13820,8 +13820,9 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { expect(mockAdapterExecute).not.toHaveBeenCalled(); expect(mockExecutePaperclipNativeSession).not.toHaveBeenCalled(); }); - it("retains an exact historical Cursor6 committed wait without allowing new unbound admission", async () => { - const f = await seedAcceptedCursorPlanWait(); + it("retains an exact historical Cursor6 committed wait across more than 1000 ignored progress rows without allowing new unbound admission", async () => { + const progressCount = 1002; + const f = await seedAcceptedCursorPlanWait(false, progressCount); await finalizeNativeRun({ db, runId: f.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); const profile = structuredClone(run!.runnerProfileJson!) as any; @@ -13841,6 +13842,28 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { await db.update(statusDecisions).set({ decisionJson: { ...decision!.decisionJson, cursorPlanWait: legacy } }).where(eq(statusDecisions.id, decision!.id)); expect(await readNativeCursorPlanWait(db, f)).toBeNull(); expect(await hasCommittedNativeCursorPlanWait(db, f)).toBe(true); + // Fill the reserved source prefix with genuine durable progress rows. Shift + // only DB ordering keys; the original PRP facts and committed receipt stay + // byte-identical. Cursor6 never queried these rows, even above its budget. + await db.update(heartbeatRunEvents).set({ seq: sql`${heartbeatRunEvents.seq} + ${progressCount}` }).where(eq(heartbeatRunEvents.runId, f.runId)); + const progress = Array.from({ length: progressCount }, (_, index) => { + const seq = index + 1; + const prpEvent = { ...event("runtime_request.created"), sourceEventId: `${run!.runnerInstanceId}:${seq}`, sourceSeq: seq, eventType: "tool.execution.progressed", + payload: { schema: "paperclip.tool.execution.v1", executionId: "earlier-tool", transport: "builtin", operation: "read", status: "running" } }; + return { companyId: f.companyId, runId: f.runId, agentId: f.agentId, seq, eventType: prpEvent.eventType, payload: { prpEvent }, sourceInstanceId: run!.runnerInstanceId, + sourceEventId: prpEvent.sourceEventId, sourceSeq: seq, sourcePayloadSha256: nativeSha256(prpEvent), protocolSchemaVersion: 1 }; + }); + await db.insert(heartbeatRunEvents).values(progress); + expect(await hasCommittedNativeCursorPlanWait(db, f)).toBe(true); + const [unchangedDecision] = await db.select().from(statusDecisions).where(eq(statusDecisions.id, decision!.id)); + expect(unchangedDecision!.decisionJson!.cursorPlanWait).toEqual(legacy); + // Completed rows belonged to the old query. A later completion must still + // invalidate the normal-terminal boundary rather than being filtered away. + const completion = { ...event("turn.completed"), sourceEventId: `${run!.runnerInstanceId}:99999`, sourceSeq: 99999, eventType: "tool.execution.completed", payload: { ...progress[0]!.payload.prpEvent.payload, status: "completed" } }; + const [extra] = await db.insert(heartbeatRunEvents).values({ ...progress[0]!, seq: 99999, eventType: completion.eventType, payload: { prpEvent: completion }, sourceEventId: completion.sourceEventId, sourceSeq: 99999, sourcePayloadSha256: nativeSha256(completion) }).returning(); + expect(await hasCommittedNativeCursorPlanWait(db, f)).toBe(false); + await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.id, extra!.id)); + expect(await hasCommittedNativeCursorPlanWait(db, f)).toBe(true); profile.nativeExecutionInput.provider.profile.commandDigest = "tampered-history"; await db.update(heartbeatRuns).set({ runnerProfileJson: profile }).where(eq(heartbeatRuns.id, f.runId)); expect(await hasCommittedNativeCursorPlanWait(db, f)).toBe(false); diff --git a/server/src/services/native-runtime/native-cursor-plan-wait.ts b/server/src/services/native-runtime/native-cursor-plan-wait.ts index 7046e1a5d8c..3c58ed4d445 100644 --- a/server/src/services/native-runtime/native-cursor-plan-wait.ts +++ b/server/src/services/native-runtime/native-cursor-plan-wait.ts @@ -16,7 +16,10 @@ type Binding = { companyId: string; issueId: string; runId: string; agentId: str const record = (v: unknown): Record => v && typeof v === "object" && !Array.isArray(v) ? v as Record : {}; const same = (a: unknown, b: unknown) => nativeSha256(a) === nativeSha256(b); const PREFIX = "cursor-plan-wait:"; -const EVENT_TYPES = ["runtime_request.created", "runtime_request.resolved", "runtime_request.cancelled", "runtime_request.expired", "turn.started", "turn.completed", "turn.failed", "turn.cancelled", "tool.execution.started", "tool.execution.progressed", "tool.execution.completed"]; +// Preserve the exact Cursor6 proof query: progress rows were never part of its +// 1,000-row budget. Completed tools were included and must stay included. +const LEGACY_EVENT_TYPES = ["runtime_request.created", "runtime_request.resolved", "runtime_request.cancelled", "runtime_request.expired", "turn.started", "turn.completed", "turn.failed", "turn.cancelled", "tool.execution.started", "tool.execution.completed"]; +const EVENT_TYPES = [...LEGACY_EVENT_TYPES, "tool.execution.progressed"]; const SUMMARY = "Plan accepted. This task is waiting for your next message. This run used Plan mode; no implementation or task completion is claimed."; export interface NativeCursorPlanWaitSource extends Binding { @@ -45,6 +48,10 @@ export interface CursorPlanWaitFacts { interactions: Array<{ interaction: typeof issueThreadInteractions.$inferSelect; delivery: typeof issueQuestionResponseDeliveries.$inferSelect }>; } +function isHistoricalUnboundWait(source?: NativeCursorPlanWaitSource): boolean { + return source !== undefined && source.toolExecutionId === undefined && source.toolLifecycleSha256 === undefined; +} + /** Only committed native request/answer/normal-terminal facts can create this passive wait. */ export function nativeCursorPlanWaitFromFacts(facts: CursorPlanWaitFacts) { return cursorPlanWaitFromFacts(facts); @@ -100,7 +107,7 @@ function cursorPlanWaitFromFacts(facts: CursorPlanWaitFacts, committedSource?: N const resolved = turn.find(e => e.eventType === "runtime_request.resolved" && record(e.payload).requestId === request.requestId)!; const resolution = record(resolved.payload); if (resolved.sourceSeq >= terminal.sourceSeq || resolution.action !== "submit" || resolution.turnId !== terminal.turnId) return null; - const historicalUnboundWait = committedSource !== undefined && committedSource.toolExecutionId === undefined && committedSource.toolLifecycleSha256 === undefined; + const historicalUnboundWait = isHistoricalUnboundWait(committedSource); let toolBinding: { toolExecutionId: string; toolLifecycleSha256: string } | undefined; if (historicalUnboundWait) { if (profile.agentProfileVersion !== 6 || profile.commandDigest !== "sha256:377dcea64a727ce799cc112458d4b40ba4bc6574cd6c6f7233b6efd5917a6c4b") return null; @@ -174,7 +181,8 @@ async function readCursorPlanWaitProof(db: Db, binding: Binding, locked: boolean .where(and(eq(heartbeatRuns.id, binding.runId), eq(heartbeatRuns.companyId, binding.companyId), eq(heartbeatRuns.agentId, binding.agentId), eq(heartbeatRuns.nativeIssueId, binding.issueId))).limit(1); const [row] = await (locked ? q.for("share", { noWait: true }) : q); if (!row || record(record(row.run.runnerProfileJson).nativeExecutionInput).provider?.agent !== "cursor" || record(record(row.run.runnerProfileJson).nativeExecutionInput).provider?.cursorMode !== "plan") return null; - const eqs = db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.companyId, binding.companyId), eq(heartbeatRunEvents.runId, binding.runId), inArray(heartbeatRunEvents.eventType, EVENT_TYPES))).orderBy(asc(heartbeatRunEvents.seq)).limit(1001); + const eventTypes = isHistoricalUnboundWait(committedSource) ? LEGACY_EVENT_TYPES : EVENT_TYPES; + const eqs = db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.companyId, binding.companyId), eq(heartbeatRunEvents.runId, binding.runId), inArray(heartbeatRunEvents.eventType, eventTypes))).orderBy(asc(heartbeatRunEvents.seq)).limit(1001); const events = await (locked ? eqs.for("share", { noWait: true }) : eqs); const iq = db.select({ interaction: issueThreadInteractions, delivery: issueQuestionResponseDeliveries }).from(issueThreadInteractions) .innerJoin(issueQuestionResponseDeliveries, eq(issueQuestionResponseDeliveries.interactionId, issueThreadInteractions.id))