Skip to content

Commit a8f007d

Browse files
committed
fix(cursor): fail closed on stale refs and prefix collisions
An explicit missing checkpointRef now expires instead of picking another snapshot. Ref-less Chat hops look up only a unique covered-prefix plus system digest. Identical first prompts no longer share a conversation. Expired snapshots are pruned by an unref timer, not the next request. Refs #1527
1 parent 3c3f843 commit a8f007d

6 files changed

Lines changed: 419 additions & 121 deletions

File tree

‎src/adapters/cursor.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,11 @@ import { isCursorBenignCancelError, isCursorInvalidArgumentError, safeCursorErro
77
import { cursorCheckpointModelAffinityId, isCursorExternalWireModel } from "./cursor/discovery";
88
import { createCursorKvStore, type CursorKvStore } from "./cursor/kv-store";
99
import { mapCursorServerMessage } from "./cursor/message-mapper";
10-
import { createCursorRequest } from "./cursor/request-builder";
10+
import {
11+
createCursorRequest,
12+
cursorCoveredPrefixDigest,
13+
cursorInstructionDigest,
14+
} from "./cursor/request-builder";
1115
import {
1216
createLiveCursorTransport,
1317
CursorMissingCredentialError,
@@ -133,12 +137,15 @@ export function createCursorAdapter(provider: OcxProviderConfig, deps: CursorAda
133137
|| lastTransport.captured.byteLength === 0
134138
) return;
135139
const previousRef = _parsed._providerContinuation?.cursor?.checkpointRef;
140+
const coveredMessageCount = _parsed.context.messages.length;
136141
const checkpointRef = commitCursorCheckpoint({
137142
conversationId: activeRequest.conversationId,
138143
identityScope: _parsed._cursorIdentityScope,
139144
modelId: cursorCheckpointModelAffinityId(activeRequest.modelId),
140145
checkpointBytes: lastTransport.captured,
141-
coveredMessageCount: _parsed.context.messages.length,
146+
coveredMessageCount,
147+
prefixDigest: cursorCoveredPrefixDigest(_parsed, coveredMessageCount),
148+
systemDigest: cursorInstructionDigest(_parsed),
142149
});
143150
if (!checkpointRef) return;
144151
if (previousRef && previousRef !== checkpointRef) invalidateCursorCheckpoint(previousRef);

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

Lines changed: 107 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ export type CursorCheckpointInvalidationReason =
2222
| "compaction"
2323
| "trailing_tool_result"
2424
| "force_fresh"
25-
| "upstream_invalid_argument";
25+
| "upstream_invalid_argument"
26+
| "lineage_mismatch";
2627

2728
export interface CursorCheckpointSnapshot {
2829
ref: string;
@@ -34,20 +35,77 @@ export interface CursorCheckpointSnapshot {
3435
lastAccessAt: number;
3536
blobLease?: CursorBlobRequestScopeToken;
3637
coveredMessageCount?: number;
38+
prefixDigest?: string;
39+
systemDigest?: string;
3740
}
3841

3942
interface CursorCheckpointStore {
4043
snapshots: Map<string, CursorCheckpointSnapshot>;
44+
prefixIndex: Map<string, Set<string>>;
4145
totalBytes: number;
4246
}
4347

4448
const store: CursorCheckpointStore = {
4549
snapshots: new Map(),
50+
prefixIndex: new Map(),
4651
totalBytes: 0,
4752
};
4853

54+
let nowFn = (): number => Date.now();
55+
let scheduleFn = (fn: () => void, ms: number): ReturnType<typeof setTimeout> => {
56+
const timer = setTimeout(fn, ms);
57+
timer.unref?.();
58+
return timer;
59+
};
60+
let clearScheduleFn = (timer: ReturnType<typeof setTimeout>): void => {
61+
clearTimeout(timer);
62+
};
63+
let pruneTimer: ReturnType<typeof setTimeout> | undefined;
64+
4965
function now(): number {
50-
return Date.now();
66+
return nowFn();
67+
}
68+
69+
export function installCursorCheckpointClockForTests(input: {
70+
now?: () => number;
71+
schedule?: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;
72+
clear?: (timer: ReturnType<typeof setTimeout>) => void;
73+
}): void {
74+
if (input.now) nowFn = input.now;
75+
if (input.schedule) scheduleFn = input.schedule;
76+
if (input.clear) clearScheduleFn = input.clear;
77+
}
78+
79+
export function resetCursorCheckpointClockForTests(): void {
80+
nowFn = () => Date.now();
81+
scheduleFn = (fn, ms) => {
82+
const timer = setTimeout(fn, ms);
83+
timer.unref?.();
84+
return timer;
85+
};
86+
clearScheduleFn = timer => {
87+
clearTimeout(timer);
88+
};
89+
stopPruneTimer();
90+
}
91+
92+
function stopPruneTimer(): void {
93+
if (pruneTimer !== undefined) clearScheduleFn(pruneTimer);
94+
pruneTimer = undefined;
95+
}
96+
97+
function schedulePrune(at = now()): void {
98+
stopPruneTimer();
99+
let nextExpiry = Number.POSITIVE_INFINITY;
100+
for (const snapshot of store.snapshots.values()) {
101+
nextExpiry = Math.min(nextExpiry, snapshot.lastAccessAt + CURSOR_CHECKPOINT_TTL_MS);
102+
}
103+
if (!Number.isFinite(nextExpiry)) return;
104+
pruneTimer = scheduleFn(() => {
105+
pruneTimer = undefined;
106+
prune();
107+
schedulePrune();
108+
}, Math.max(0, nextExpiry - at));
51109
}
52110

53111
function prune(at = now()): void {
@@ -59,12 +117,29 @@ function prune(at = now()): void {
59117
if (oldest === undefined) break;
60118
deleteSnapshot(oldest);
61119
}
120+
schedulePrune(at);
121+
}
122+
123+
function indexPrefix(digest: string | undefined, ref: string): void {
124+
if (!digest) return;
125+
const refs = store.prefixIndex.get(digest) ?? new Set<string>();
126+
refs.add(ref);
127+
store.prefixIndex.set(digest, refs);
128+
}
129+
130+
function unindexPrefix(digest: string | undefined, ref: string): void {
131+
if (!digest) return;
132+
const refs = store.prefixIndex.get(digest);
133+
if (!refs) return;
134+
refs.delete(ref);
135+
if (refs.size === 0) store.prefixIndex.delete(digest);
62136
}
63137

64138
function deleteSnapshot(ref: string): void {
65139
const existing = store.snapshots.get(ref);
66140
if (!existing) return;
67141
if (existing.blobLease) releaseCursorBlobRequestScope(existing.blobLease);
142+
unindexPrefix(existing.prefixDigest, ref);
68143
store.snapshots.delete(ref);
69144
store.totalBytes = Math.max(0, store.totalBytes - existing.checkpointBytes.byteLength);
70145
}
@@ -110,6 +185,8 @@ export function commitCursorCheckpoint(input: {
110185
modelId: string;
111186
checkpointBytes: Uint8Array;
112187
coveredMessageCount?: number;
188+
prefixDigest?: string;
189+
systemDigest?: string;
113190
}): string | undefined {
114191
if (!input.conversationId || !input.modelId || input.checkpointBytes.byteLength === 0) return undefined;
115192
if (input.checkpointBytes.byteLength > CURSOR_CHECKPOINT_MAX_TOTAL_BYTES) return undefined;
@@ -137,6 +214,8 @@ export function commitCursorCheckpoint(input: {
137214
createdAt,
138215
lastAccessAt: createdAt,
139216
...(input.coveredMessageCount !== undefined ? { coveredMessageCount: input.coveredMessageCount } : {}),
217+
...(input.prefixDigest ? { prefixDigest: input.prefixDigest } : {}),
218+
...(input.systemDigest ? { systemDigest: input.systemDigest } : {}),
140219
};
141220
const blobIds = collectCheckpointBlobIds(input.checkpointBytes);
142221
if (blobIds === undefined) return undefined;
@@ -151,10 +230,33 @@ export function commitCursorCheckpoint(input: {
151230
deleteSnapshot(ref);
152231
store.snapshots.set(ref, snapshot);
153232
store.totalBytes += snapshot.checkpointBytes.byteLength;
233+
indexPrefix(snapshot.prefixDigest, ref);
154234
prune(createdAt);
155235
return store.snapshots.has(ref) ? ref : undefined;
156236
}
157237

238+
export function getCursorCheckpointForPrefix(input: {
239+
prefixDigest: string;
240+
systemDigest: string;
241+
coveredMessageCount: number;
242+
identityScope?: string;
243+
modelId: string;
244+
}): CursorCheckpointSnapshot | undefined {
245+
prune();
246+
const refs = store.prefixIndex.get(input.prefixDigest);
247+
if (!refs || refs.size !== 1) return undefined;
248+
const [ref] = refs;
249+
if (!ref) return undefined;
250+
const snapshot = getCursorCheckpoint(ref);
251+
if (!snapshot) return undefined;
252+
const identityScope = input.identityScope?.trim() || "local";
253+
if (snapshot.systemDigest !== input.systemDigest) return undefined;
254+
if (snapshot.coveredMessageCount !== input.coveredMessageCount) return undefined;
255+
if (snapshot.identityScope !== identityScope) return undefined;
256+
if (snapshot.modelId !== input.modelId) return undefined;
257+
return snapshot;
258+
}
259+
158260
export function getLatestCursorCheckpoint(
159261
match: (snapshot: CursorCheckpointSnapshot) => boolean,
160262
): CursorCheckpointSnapshot | undefined {
@@ -188,9 +290,12 @@ export function invalidateCursorCheckpoint(ref: string | undefined): void {
188290
}
189291

190292
export function clearCursorCheckpointsForTests(): void {
293+
stopPruneTimer();
191294
for (const ref of [...store.snapshots.keys()]) deleteSnapshot(ref);
192295
store.snapshots.clear();
296+
store.prefixIndex.clear();
193297
store.totalBytes = 0;
298+
resetCursorCheckpointClockForTests();
194299
}
195300

196301
export function cursorCheckpointStoreMetricsForTests(): { count: number; totalBytes: number } {

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

Lines changed: 72 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import {
2727
import { lookupCursorThreadConversation } from "./thread-continuity";
2828
import {
2929
getCursorCheckpoint,
30-
getLatestCursorCheckpoint,
30+
getCursorCheckpointForPrefix,
3131
type CursorCheckpointInvalidationReason,
3232
type CursorCheckpointSnapshot,
3333
} from "./checkpoint-store";
@@ -291,42 +291,80 @@ export function resolveCursorConversationId(
291291
options: CreateCursorRequestOptions = {},
292292
): string {
293293
if (options.forceFreshConversation === true) return generatedCursorConversationId();
294-
// Helper/shadow turns must not append into the parent's Cursor conversation, even when
295-
// previous_response_id restored the parent's remembered id. They still keep their own
296-
// cache, keyed off this turn's first user/developer text.
297-
if (parsed._cursorIsolateConversation === true) {
298-
const isolatedSeed = cursorHistorySeed(parsed);
299-
if (isolatedSeed) {
300-
return cursorConversationIdFromClientThread(`isolate:${isolatedSeed}`, parsed._cursorIdentityScope);
301-
}
302-
return generatedCursorConversationId();
303-
}
294+
if (parsed._cursorIsolateConversation === true) return generatedCursorConversationId();
304295
if (parsed._cursorConversationId) return parsed._cursorConversationId;
305296
const threadId = parsed._clientThreadId?.trim();
306297
if (threadId) {
307298
const recovered = lookupCursorThreadConversation(threadId, parsed._cursorIdentityScope);
308299
if (recovered) return recovered;
309300
return cursorConversationIdFromClientThread(`thread:${threadId}`, parsed._cursorIdentityScope);
310301
}
311-
const historySeed = cursorHistorySeed(parsed);
312-
if (historySeed) return cursorConversationIdFromClientThread(`history:${historySeed}`, parsed._cursorIdentityScope);
313302
return generatedCursorConversationId();
314303
}
315304

316-
function cursorHistorySeed(parsed: OcxParsedRequest): string | undefined {
305+
export function cursorInstructionDigest(parsed: OcxParsedRequest): string {
306+
const hash = createHash("sha256").update("ocx:cursor:sys:");
307+
for (const line of parsed.context.systemPrompt ?? []) {
308+
hash.update(line).update("\n");
309+
}
317310
for (const message of parsed.context.messages) {
318-
if (message.role !== "user" && message.role !== "developer") continue;
319-
const text = contentToText(message.content).trim();
320-
if (text) return text;
311+
if (message.role !== "developer") continue;
312+
hash.update(contentToText(message.content)).update("\n");
321313
}
322-
return undefined;
314+
return hash.digest("hex");
315+
}
316+
317+
export function cursorCoveredPrefixDigest(parsed: OcxParsedRequest, coveredMessageCount: number): string {
318+
const hash = createHash("sha256").update("ocx:cursor:prefix:");
319+
hash.update(cursorInstructionDigest(parsed)).update("\0");
320+
for (const message of parsed.context.messages.slice(0, coveredMessageCount)) {
321+
hash.update(message.role).update("\0");
322+
hash.update(contentToText(message.content)).update("\n");
323+
}
324+
return hash.digest("hex");
323325
}
324326

325327
export interface CreateCursorRequestOptions {
326328
/** Force a brand-new Cursor conversation id even when remembered state exists. */
327329
forceFreshConversation?: boolean;
328330
}
329331

332+
function lookupPrefixSnapshot(
333+
parsed: OcxParsedRequest,
334+
request: CursorRunRequest,
335+
identityScope: string,
336+
): CursorCheckpointSnapshot | undefined {
337+
const systemDigest = cursorInstructionDigest(parsed);
338+
const modelId = cursorCheckpointModelAffinityId(request.modelId);
339+
for (let covered = parsed.context.messages.length; covered >= 1; covered--) {
340+
const snapshot = getCursorCheckpointForPrefix({
341+
prefixDigest: cursorCoveredPrefixDigest(parsed, covered),
342+
systemDigest,
343+
coveredMessageCount: covered,
344+
identityScope,
345+
modelId,
346+
});
347+
if (snapshot) return snapshot;
348+
}
349+
return undefined;
350+
}
351+
352+
function lineageMismatch(
353+
parsed: OcxParsedRequest,
354+
snapshot: CursorCheckpointSnapshot,
355+
): CursorCheckpointInvalidationReason | undefined {
356+
const covered = snapshot.coveredMessageCount;
357+
if (covered === undefined || covered < 0 || covered > parsed.context.messages.length) {
358+
return "lineage_mismatch";
359+
}
360+
if (!snapshot.prefixDigest || !snapshot.systemDigest) return "lineage_mismatch";
361+
if (snapshot.systemDigest !== cursorInstructionDigest(parsed)) return "lineage_mismatch";
362+
if (snapshot.prefixDigest !== cursorCoveredPrefixDigest(parsed, covered)) return "lineage_mismatch";
363+
const lastRole = parsed.context.messages.at(-1)?.role;
364+
if (lastRole === "toolResult" && covered >= parsed.context.messages.length) return "trailing_tool_result";
365+
return undefined;
366+
}
367+
330368
function resolveCursorCheckpoint(
331369
parsed: OcxParsedRequest,
332370
request: CursorRunRequest,
@@ -338,28 +376,26 @@ function resolveCursorCheckpoint(
338376
const cursorState = parsed._providerContinuation?.cursor;
339377
const ref = isolated ? undefined : cursorState?.checkpointRef;
340378
const identityScope = parsed._cursorIdentityScope?.trim() || "local";
341-
const modelAffinity = cursorCheckpointModelAffinityId(request.modelId);
342-
let snapshot = getCursorCheckpoint(ref);
343-
if (!snapshot) {
344-
snapshot = getLatestCursorCheckpoint(candidate =>
345-
candidate.conversationId === request.conversationId
346-
&& candidate.identityScope === identityScope
347-
&& cursorCheckpointModelAffinityId(candidate.modelId) === modelAffinity
348-
);
379+
let snapshot: CursorCheckpointSnapshot | undefined;
380+
if (ref) {
381+
snapshot = getCursorCheckpoint(ref);
382+
if (!snapshot) return { reason: "expired" };
383+
} else {
384+
snapshot = lookupPrefixSnapshot(parsed, request, identityScope);
385+
if (!snapshot) return { reason: "missing_ref" };
386+
}
387+
if (!isolated && snapshot.conversationId !== request.conversationId && ref) {
388+
return { reason: "conversation_changed" };
349389
}
350-
if (!snapshot) return { reason: ref ? "expired" : "missing_ref" };
351-
if (snapshot.conversationId !== request.conversationId) return { reason: "conversation_changed" };
352390
if (snapshot.identityScope !== identityScope) return { reason: "identity_changed" };
353-
if (cursorCheckpointModelAffinityId(snapshot.modelId) !== modelAffinity) return { reason: "model_changed" };
354-
const lastRole = parsed.context.messages.at(-1)?.role;
355-
if (lastRole === "toolResult") {
356-
if (snapshot.coveredMessageCount === undefined) return { reason: "trailing_tool_result" };
357-
if (snapshot.coveredMessageCount < 0 || snapshot.coveredMessageCount >= parsed.context.messages.length) {
358-
return { reason: "trailing_tool_result" };
359-
}
360-
} else if (cursorState?.checkpointUsable === false) {
391+
if (cursorCheckpointModelAffinityId(snapshot.modelId) !== cursorCheckpointModelAffinityId(request.modelId)) {
392+
return { reason: "model_changed" };
393+
}
394+
if (parsed.context.messages.at(-1)?.role !== "toolResult" && cursorState?.checkpointUsable === false) {
361395
return { reason: "trailing_tool_result" };
362396
}
397+
const lineage = lineageMismatch(parsed, snapshot);
398+
if (lineage) return { reason: lineage };
363399
return { snapshot };
364400
}
365401

‎structure/04_transports-and-sidecars.md‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -519,10 +519,9 @@ pre-compaction checkpoint is not persisted for later carry-forward.
519519
After a successful no-tool turn, the Cursor adapter keeps the returned ConversationStateStructure in
520520
a process-local store and reuses that snapshot on the next validated linear continuation instead of
521521
rebuilding rootPromptMessagesJson and conversationTurns. Tool-result turns reuse the last completed
522-
checkpoint plus only the uncovered suffix. Chat Completions hops that omit previous_response_id and
523-
thread headers pin to the first user/developer text and reuse the live snapshot for that
524-
conversation. Isolated helper/shadow turns keep their own checkpoint and never join the parent
525-
conversation. Compaction, account or model mismatch, missing refs, decode failures, and
522+
checkpoint plus only the uncovered suffix. Chat Completions hops that omit previous_response_id and thread headers reuse a snapshot only when
523+
the covered message prefix and system/developer digest match exactly one stored snapshot. Isolated
524+
helper/shadow turns never join the parent conversation. An explicit missing checkpointRef full-replays. Compaction, account or model mismatch, missing refs, decode failures, and
526525
invalid_argument recovery keep the existing full-replay path. previous_response_id may select a
527526
branch's opaque checkpointRef; it is never a Cursor conversation ownership key. Cursor Connect still
528527
does not expose authoritative cache_read_tokens.

0 commit comments

Comments
 (0)