Skip to content

Commit 3c3f843

Browse files
committed
fix(cursor): keep recovered checkpoints and close review holes
Do not invalidate the checkpoint just committed during forced-fresh recovery. Invalidate the inherited ref, including compaction leftovers. Pin checkpoint blobs atomically, collect nested subagent blob ids, and keep suffix replay off the system prompt. Refs #1527
1 parent 1ffee21 commit 3c3f843

8 files changed

Lines changed: 121 additions & 35 deletions

File tree

‎docs-site/src/content/docs/ko/reference/adapters.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,12 +142,13 @@ commentary로 유지하고 비공개 완료 툴을 한 번 검증합니다.
142142
- content-addressed blob으로 대화 상태를 재생하고 서버 툴 호출을 Codex에 다시 매핑합니다. protobuf
143143
`GetUsableModels` RPC로 실시간 Cursor 모델을 찾으며, run 요청이 wire에 commit되기 전까지만
144144
재시도합니다.
145-
도구 없이 정상 완료된 턴 뒤에는 Cursor가 돌려준 ConversationStateStructure를 프로세스 로컬
145+
- 도구 없이 정상 완료된 턴 뒤에는 Cursor가 돌려준 ConversationStateStructure를 프로세스 로컬
146146
store에 보관하고, 검증된 선형 이어말하기에서는 전체 root history를 다시 만들지 않고 그
147147
checkpoint를 재사용합니다. tool-result 턴은 마지막 정상 완료 턴의 checkpoint에 커버되지 않은
148-
suffix만 붙입니다. compaction, helper/shadow 격리, 계정/모델 불일치, 없는 ref, decode 실패는
149-
기존 full replay로 돌아갑니다. Cursor Connect는 권위 있는 cache_read_tokens를 주지 않으므로
150-
OpenCodex usage만 보고 cache hit라고 단정하지 않습니다.
148+
suffix만 붙입니다. compaction, helper/shadow 격리, 계정/모델 불일치, 없는 ref, decode 실패,
149+
forced-fresh 복구, invalid_argument 재시도는 기존 full replay로 돌아갑니다. Cursor Connect는
150+
권위 있는 cache_read_tokens를 주지 않으므로 OpenCodex usage만 보고 cache hit라고 단정하지
151+
않습니다.
151152
- `cursor/grok-4.5-fast`는 선택 가능한 모델로 유지하되, Cursor에는 정식 `grok-4.5` 모델을 보내고
152153
별도의 `effort`, `fast=true` 값은 `requested_model.parameters`에 담습니다.
153154
- Cursor 네이티브 로컬 파일시스템/shell/network 실행은 기본적으로 거부합니다. 명시적인

‎docs-site/src/content/docs/reference/adapters.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -195,13 +195,14 @@ advertised effort control on those models as proof of upstream-native reasoning
195195
- Replays conversation state through content-addressed blobs, maps server tool calls back to Codex,
196196
discovers live Cursor models through the protobuf `GetUsableModels` RPC, and retries only before a
197197
run request is committed to the wire.
198-
After a successful no-tool turn, the adapter keeps Cursor's returned ConversationStateStructure
198+
- After a successful no-tool turn, the adapter keeps Cursor's returned ConversationStateStructure
199199
in a process-local store and reuses that checkpoint on the next validated linear continuation
200200
instead of rebuilding the full root history. Tool-result turns reuse the last completed-turn
201201
checkpoint plus only the uncovered suffix when the covered message boundary is known.
202-
Compaction, helper/shadow isolation, account/model mismatch, missing refs, and decode failures
203-
fall back to the existing full replay. Cursor Connect still does not expose authoritative
204-
cache_read_tokens, so OpenCodex usage is not a cache-hit counter.
202+
Compaction, helper/shadow isolation, account/model mismatch, missing refs, decode failures,
203+
forced-fresh recovery, and invalid_argument retries fall back to the existing full replay. Cursor
204+
Connect still does not expose authoritative cache_read_tokens, so OpenCodex usage is not a
205+
cache-hit counter.
205206
- Exposes Cursor Router as `cursor/auto` plus explicit `cursor/auto-cost`,
206207
`cursor/auto-balance`, and `cursor/auto-intelligence` entries. Explicit levels are encoded in
207208
`requested_model.parameters` while the legacy `cursor/auto` entry retains the account/team default.

‎src/adapters/cursor.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ export function createCursorAdapter(provider: OcxProviderConfig, deps: CursorAda
103103
/* Missing credential is handled by the live transport path below. */
104104
}
105105
}
106+
const inheritedCheckpointRef = _parsed._providerContinuation?.cursor?.checkpointRef;
106107
const previousConversationId = _parsed._cursorConversationId;
107108
let request = createCursorRequest(_parsed);
108109
// The builder may derive a stable provider id from the client thread when Responses state
@@ -252,9 +253,8 @@ export function createCursorAdapter(provider: OcxProviderConfig, deps: CursorAda
252253
if (
253254
request.checkpointInvalidationReason
254255
&& request.checkpointInvalidationReason !== "missing_ref"
255-
&& request.checkpointInvalidationReason !== "compaction"
256256
) {
257-
invalidateCursorCheckpoint(_parsed._providerContinuation?.cursor?.checkpointRef);
257+
invalidateCursorCheckpoint(inheritedCheckpointRef);
258258
debugProviderDiagnostic("cursor", "checkpoint-invalidated", {
259259
reason: request.checkpointInvalidationReason,
260260
});

‎src/adapters/cursor/checkpoint-store.ts‎

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { createHash } from "node:crypto";
22
import { fromBinary } from "@bufbuild/protobuf";
3-
import { ConversationStateStructureSchema } from "./gen/agent_pb";
3+
import { ConversationStateStructureSchema, type ConversationStateStructure } from "./gen/agent_pb";
44
import {
55
createCursorBlobCheckpointLease,
66
pinCursorBlobIdsForCheckpoint,
@@ -69,24 +69,31 @@ function deleteSnapshot(ref: string): void {
6969
store.totalBytes = Math.max(0, store.totalBytes - existing.checkpointBytes.byteLength);
7070
}
7171

72+
function collectStateBlobIds(state: ConversationStateStructure, ids: Uint8Array[]): void {
73+
ids.push(
74+
...state.rootPromptMessagesJson,
75+
...state.turns,
76+
...state.turnsOld,
77+
...state.todos,
78+
...state.summaryArchives,
79+
);
80+
if (state.summary) ids.push(state.summary);
81+
if (state.summaryArchive) ids.push(state.summaryArchive);
82+
if (state.plan) ids.push(state.plan);
83+
for (const value of Object.values(state.fileStates)) ids.push(value);
84+
for (const value of Object.values(state.fileStatesV2)) {
85+
if (value.content) ids.push(value.content);
86+
if (value.initialContent) ids.push(value.initialContent);
87+
}
88+
for (const nested of Object.values(state.subagentStates)) {
89+
if (nested.conversationState) collectStateBlobIds(nested.conversationState, ids);
90+
}
91+
}
92+
7293
function collectCheckpointBlobIds(checkpointBytes: Uint8Array): Uint8Array[] | undefined {
7394
try {
74-
const state = fromBinary(ConversationStateStructureSchema, checkpointBytes);
75-
const ids: Uint8Array[] = [
76-
...state.rootPromptMessagesJson,
77-
...state.turns,
78-
...state.turnsOld,
79-
...state.todos,
80-
...state.summaryArchives,
81-
];
82-
if (state.summary) ids.push(state.summary);
83-
if (state.summaryArchive) ids.push(state.summaryArchive);
84-
if (state.plan) ids.push(state.plan);
85-
for (const value of Object.values(state.fileStates)) ids.push(value);
86-
for (const value of Object.values(state.fileStatesV2)) {
87-
if (value.content) ids.push(value.content);
88-
if (value.initialContent) ids.push(value.initialContent);
89-
}
95+
const ids: Uint8Array[] = [];
96+
collectStateBlobIds(fromBinary(ConversationStateStructureSchema, checkpointBytes), ids);
9097
return ids.filter(id => id.byteLength > 0);
9198
} catch {
9299
return undefined;

‎src/adapters/cursor/native-exec.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -419,16 +419,23 @@ export function pinCursorBlobIdsForCheckpoint(
419419
): boolean {
420420
const state = blobRequestScopes.get(lease);
421421
if (!state || state.sealed) return false;
422+
const added: Array<{ entry: { requestPins: Set<CursorBlobRequestScopeToken> }; key: string }> = [];
422423
for (const blobId of blobIds) {
423424
if (blobId.byteLength === 0) continue;
424425
const k = key(blobId);
425426
const entry = blobs.get(k);
426-
if (!entry) return false;
427-
if (isExpired(entry, Date.now()) && entry.requestPins.size === 0 && entry.provenance !== "remote-setBlobArgs") {
427+
if (!entry || (isExpired(entry, Date.now()) && entry.requestPins.size === 0 && entry.provenance !== "remote-setBlobArgs")) {
428+
for (const pinned of added) {
429+
pinned.entry.requestPins.delete(lease);
430+
state.keys.delete(pinned.key);
431+
}
428432
return false;
429433
}
430-
entry.requestPins.add(lease);
431-
state.keys.add(k);
434+
if (!entry.requestPins.has(lease)) {
435+
entry.requestPins.add(lease);
436+
state.keys.add(k);
437+
added.push({ entry, key: k });
438+
}
432439
}
433440
reconcileBlobClassAccountingAndEnforce();
434441
return true;

‎src/adapters/cursor/protobuf-request.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
ConversationActionSchema,
2626
ConversationStepSchema,
2727
ConversationStateStructureSchema,
28+
type ConversationStateStructure,
2829
ConversationTurnStructureSchema,
2930
McpArgsSchema,
3031
McpSuccessSchema,
@@ -800,7 +801,7 @@ function buildPreparedCursorRunRequest(
800801
});
801802
let continuationMode: "full-replay" | "checkpoint" = "full-replay";
802803
let checkpointInvalidationReason = request.checkpointInvalidationReason;
803-
let conversationState;
804+
let conversationState: ConversationStateStructure | undefined;
804805
let rootPromptMessagesState: ReturnType<typeof rootPromptMessages> | undefined;
805806
if (request.checkpointBytes && request.checkpointBytes.byteLength > 0) {
806807
try {
@@ -816,6 +817,7 @@ function buildPreparedCursorRunRequest(
816817
) {
817818
const suffixRequest: CursorRunRequest = {
818819
...request,
820+
system: [],
819821
rawMessages: request.rawMessages.slice(suffixStart),
820822
};
821823
const suffixRoots = rootPromptMessages(suffixRequest, requestScope);

‎tests/cursor-adapter.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,66 @@ describe("Cursor adapter live transport", () => {
334334
expect(events.filter(event => event.type === "error")).toHaveLength(0);
335335
});
336336

337+
test("forced-fresh recovery keeps the new checkpoint instead of deleting it", async () => {
338+
clearCursorCheckpointsForTests();
339+
const parentBytes = toBinary(ConversationStateStructureSchema, create(ConversationStateStructureSchema, {
340+
pendingToolCalls: ["parent-stale"],
341+
}));
342+
const parentRef = commitCursorCheckpoint({
343+
conversationId: "cursor_stale",
344+
identityScope: "acct-fresh",
345+
modelId: "gpt-5.6-sol",
346+
checkpointBytes: parentBytes,
347+
});
348+
expect(parentRef).toBeDefined();
349+
const recoveredBytes = toBinary(ConversationStateStructureSchema, create(ConversationStateStructureSchema, {
350+
pendingToolCalls: ["recovered"],
351+
}));
352+
let attempts = 0;
353+
const adapter = createCursorAdapter({
354+
...provider,
355+
apiKey: "cursor-token",
356+
}, {
357+
createTransport: () => ({
358+
async *run() {
359+
attempts += 1;
360+
if (attempts === 1) {
361+
throw Object.assign(
362+
new Error("Cursor invalid request: Cursor Connect error invalid_argument: Error"),
363+
{ code: "invalid_argument" },
364+
);
365+
}
366+
yield { type: "done" } satisfies CursorServerMessage;
367+
},
368+
writeClient() {},
369+
capturedConversationCheckpoint() {
370+
return attempts === 1 ? undefined : recoveredBytes;
371+
},
372+
}),
373+
});
374+
const body: OcxParsedRequest = {
375+
modelId: "cursor/gpt-5.6-sol",
376+
context: { messages: [{ role: "user", content: "retry me", timestamp: 1 }] },
377+
stream: false,
378+
options: {},
379+
_cursorConversationId: "cursor_stale",
380+
_cursorIdentityScope: "acct-fresh",
381+
_providerContinuation: {
382+
cursor: { conversationId: "cursor_stale", checkpointUsable: true, checkpointRef: parentRef },
383+
},
384+
};
385+
const events: AdapterEvent[] = [];
386+
await adapter.runTurn?.(body, { headers: new Headers() }, event => events.push(event));
387+
expect(attempts).toBe(2);
388+
expect(getCursorCheckpoint(parentRef)).toBeUndefined();
389+
const done = events.find(event => event.type === "done");
390+
const newRef = done && done.type === "done" ? done.providerState?.cursor?.checkpointRef : undefined;
391+
expect(newRef).toBeDefined();
392+
expect(newRef).not.toBe(parentRef);
393+
expect(getCursorCheckpoint(newRef)?.conversationId).toBe(body._cursorConversationId);
394+
clearCursorCheckpointsForTests();
395+
});
396+
337397
test("does not replay invalid_argument after a local side effect", async () => {
338398
let attempts = 0;
339399
const adapter = createCursorAdapter({

‎tests/cursor-blob.test.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1439,8 +1439,14 @@ describe("Cursor checkpoint request construction", () => {
14391439
checkpointBytes: new Uint8Array([1, 2, 3, 4]),
14401440
});
14411441
const roots = decodeRootMessages(prepared.bytes);
1442-
expect(roots.length).toBeGreaterThan(0);
1443-
expect(JSON.stringify(roots)).toContain("You are helpful.");
1442+
const fullReplay = decodeRootMessages(prepareCursorRunRequest({
1443+
modelId: "grok-4.6",
1444+
conversationId: "cursor_ckpt",
1445+
system: ["You are helpful."],
1446+
messages: [{ role: "user", content: "hello" }],
1447+
rawMessages: [{ role: "user", content: "hello", timestamp: 1 }],
1448+
}).bytes);
1449+
expect(roots).toEqual(fullReplay);
14441450
});
14451451

14461452
test("checkpoint suffix replay appends only uncovered history", () => {
@@ -1540,7 +1546,9 @@ describe("Cursor checkpoint request construction", () => {
15401546
});
15411547
expect(ref).toBeDefined();
15421548
releaseCursorBlobRequestScope(requestScope);
1543-
expectBlobHit(blobId, data, requestScope);
1549+
const hydrateScope = createCursorBlobRequestScope();
1550+
expectBlobHit(blobId, data, hydrateScope);
1551+
releaseCursorBlobRequestScope(hydrateScope);
15441552
expect(cursorBlobRetainedStoreSnapshot().pinnedBytes).toBeGreaterThan(0);
15451553
expect(evictOldestCursorBlobForBudget()).toBe(0);
15461554
invalidateCursorCheckpoint(ref);

0 commit comments

Comments
 (0)