Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion docs/harnesses/cursor/cursor-cli-experimental.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,19 @@ references. This is an undocumented native format, not a supported Cursor API.
The snapshot body comes from native ACP `session/load` and is reused only while the
native history root is unchanged. It is accepted only
when session, workspace, turn count, order and exact prompt text match native
history. A successful live turn must introduce exactly one native user-turn ID.
history. A successful live turn must introduce exactly one non-notification native
user-turn ID whose text matches the submitted prompt, while preserving the existing
history prefix. Both the terminal identity and an available checkpoint use that ID.
A checkpoint is offered only when Fork is supported and the prompt is the last
native record or the next record has a verified native rewind root, matching replay
projection and Fork validation. Missing rewind roots do not invalidate the Turn's
successful outcome or native identity.
In the observed Cursor CLI `2026.10.22-27dcf5f` store, background task completion
records carry field 15 (`simulated_message_metadata`). Records with this field are
treated as Cursor-generated notifications for live prompt identity verification;
they remain in the native history for replay and Fork boundaries. This field is not
a dedicated notification flag, and other native versions or simulated message types
are not established by this compatibility rule.
Missing/ambiguous history is an error; generated UUIDs, array positions and text
hashes are never used as native turn keys. The adapter keeps no shadow transcript.

Expand Down
22 changes: 16 additions & 6 deletions packages/adapters/cursor-cli/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -814,24 +814,34 @@ export class CursorSession implements HarnessSession {
if (administrative && JSON.stringify(before) === JSON.stringify(after)) {
// This native command returns a local message without persisting a user Turn.
} else {
// Cursor appends its own user records when a background task finishes; those are not
// the echo of this prompt and must not make the prompt's identity ambiguous.
const prompted = added.filter((turn) => !turn.notification);
const own = prompted[0];
if (
added.length !== 1 ||
after.length !== before.length + 1 ||
!own ||
prompted.length !== 1 ||
after.length !== before.length + added.length ||
before.some((turn, index) => after[index]?.id !== turn.id) ||
added[0]?.text !== command.input.map((part) => part.text).join("\n")
own.text !== command.input.map((part) => part.text).join("\n")
)
throw new Error("Cursor terminal has no unique, verified native turn identity");
nativeTurnRef = nativeTurnRefSchema.parse({
harnessId: "cursor-cli",
nativeSessionId: this.transport.sessionId,
nativeTurnKey: added[0].id,
nativeTurnKey: own.id,
formatVersion: 1,
});
this.#fresh = false;
if (outcome.status === "succeeded" && cursorForkAvailable())
const ownIndex = after.findIndex((turn) => turn.id === own.id);
if (
outcome.status === "succeeded" &&
cursorForkAvailable() &&
(ownIndex === after.length - 1 || after[ownIndex + 1]?.rewindRoot)
)
outcome = {
...outcome,
checkpoint: cursorCheckpoint(this.transport.sessionId, added[0].id),
checkpoint: cursorCheckpoint(this.transport.sessionId, own.id),
};
}
} catch (error) {
Expand Down
4 changes: 4 additions & 0 deletions packages/adapters/cursor-cli/src/native-history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ export interface CursorNativeTurn {
text: string;
/** Native conversation root immediately before this user turn, when available. */
rewindRoot?: string;
/** Cursor wrote this user record itself to report a finished background task (field 15),
* not as the echo of a prompt the Host submitted. */
notification?: true;
}

export function cursorConfigDirectory(environment: NodeJS.ProcessEnv): string {
Expand Down Expand Up @@ -140,6 +143,7 @@ export function readCursorNativeHistory(
id,
text: one(user, 1).toString("utf8"),
...(rewindRoot ? { rewindRoot } : {}),
...(user.get(15)?.length ? { notification: true as const } : {}),
});
}
}
Expand Down
81 changes: 80 additions & 1 deletion packages/adapters/cursor-cli/test/cursor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ import { CursorTransport, type CursorCallbacks } from "../src/transport.js";
import { cursorModelRef, cursorCatalog, cursorNativeModel } from "../src/models.js";
import { CursorInteractions } from "../src/interactions.js";
import { cursorSnapshot } from "../src/projection.js";
import * as forkSupport from "../src/fork-support.js";

const native = vi.hoisted(() => ({ turns: [] as Array<{ id: string; text: string }> }));
const native = vi.hoisted(() => ({
turns: [] as Array<{ id: string; text: string; notification?: true; rewindRoot?: string }>,
}));
vi.mock("../src/native-history.js", () => ({
readCursorNativeTurns: () => structuredClone(native.turns),
readCursorNativeHistory: () => ({
Expand Down Expand Up @@ -287,6 +290,82 @@ describe("Cursor turn lifecycle", () => {
}),
);
});
it.each([true, false])(
"keeps prompt identity with notifications (rewind anchor=%s)",
async (hasRewindRoot) => {
vi.spyOn(forkSupport, "cursorForkAvailable").mockReturnValue(true);
const f = session();
const notification = (id: string) =>
native.turns.push({
id: randomUUID(),
text: `<system_notification>\n<task>\ntask_id: ${id}\n</task>\n</system_notification>`,
notification: true,
...(hasRewindRoot ? { rewindRoot: "a".repeat(64) } : {}),
});
notification("before");
f.transport.action = async (text, callbacks) => {
callbacks.update({
sessionId: info.sessionId,
update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "ok" } },
});
native.turns.push({ id: randomUUID(), text });
notification("one");
notification("two");
return { stopReason: "end_turn" };
};
await f.session.execute(start);
await vi.waitFor(() =>
expect(f.output.some((x) => x.kind === "event" && x.event.type === "turn.completed")).toBe(
true,
),
);
await f.session.close();
await f.done;
const terminal = f.output.filter(
(x) => x.kind === "event" && x.event.type === "turn.completed",
);
expect(terminal[0]).toMatchObject({
event: {
outcome: { status: "succeeded" },
nativeTurnRef: { nativeTurnKey: native.turns[1]?.id },
},
});
if (hasRewindRoot) {
expect(terminal[0]).toHaveProperty("event.outcome.checkpoint", {
harnessId: "cursor-cli",
nativeSessionId: info.sessionId,
checkpointId: native.turns[1]?.id,
locator: { kind: "cursor-turn" },
formatVersion: 1,
});
} else {
expect(terminal[0]).not.toHaveProperty("event.outcome.checkpoint");
}
},
);
it("still fails when only background task notifications were added", async () => {
const f = session();
f.transport.action = async () => {
native.turns.push({ id: randomUUID(), text: "<system_notification/>", notification: true });
return { stopReason: "end_turn" };
};
await f.session.execute(start);
await vi.waitFor(() =>
expect(f.output.some((x) => x.kind === "event" && x.event.type === "turn.completed")).toBe(
true,
),
);
await f.session.close();
await f.done;
expect(f.output).toContainEqual(
expect.objectContaining({
event: expect.objectContaining({
type: "turn.completed",
outcome: expect.objectContaining({ status: "failed" }),
}),
}),
);
});
it("rejects a concurrent turn and closes pending approval on cancel", async () => {
const f = session();
f.transport.action = async (text, callbacks) => {
Expand Down
31 changes: 28 additions & 3 deletions packages/adapters/cursor-cli/test/native-history.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ function field(id: number, value: Buffer | string) {
const data = Buffer.isBuffer(value) ? value : Buffer.from(value);
return Buffer.concat([varint(id * 8 + 2), varint(data.length), data]);
}
function fixture(texts = ["first", "second"]) {
function fixture(texts = ["first", "second"], notifications: number[] = []) {
const home = mkdtempSync(path.join(os.tmpdir(), "codexhost-cursor-history-"));
temporary.push(home);
const sessionId = randomUUID();
Expand All @@ -38,13 +38,31 @@ function fixture(texts = ["first", "second"]) {
db.prepare("INSERT OR IGNORE INTO blobs VALUES(?,?)").run(id.toString("hex"), data);
return id;
};
const turns = texts.map((text) => ({ id: randomUUID(), text }));
const turns = texts.map((text, index) => ({
id: randomUUID(),
text,
...(notifications.includes(index) ? { notification: true as const } : {}),
}));
const root = put(
Buffer.concat(
turns.map((turn) =>
field(
8,
put(field(1, field(1, put(Buffer.concat([field(1, turn.text), field(2, turn.id)]))))),
put(
field(
1,
field(
1,
put(
Buffer.concat([
field(1, turn.text),
field(2, turn.id),
...(turn.notification ? [field(15, field(1, "background task"))] : []),
]),
),
),
),
),
),
),
),
Expand Down Expand Up @@ -81,6 +99,13 @@ describe("Cursor read-only native identity", () => {
);
expect(readCursorNativeTurns(f.sessionId, requested, { HOME: f.home })).toEqual(f.turns);
});
it("marks user records Cursor wrote for finished background tasks", () => {
const f = fixture(["prompt", "<system_notification>task finished</system_notification>"], [1]);
const turns = readCursorNativeTurns(f.sessionId, f.home, { HOME: f.home });
expect(turns).toEqual(f.turns);
expect(turns[0]).not.toHaveProperty("notification");
expect(turns[1]).toMatchObject({ notification: true });
});
it("allows a new empty history without inventing IDs", () => {
const f = fixture([]);
expect(readCursorNativeTurns(f.sessionId, f.home, { HOME: f.home })).toEqual([]);
Expand Down
Loading