fix: handle revert edge cases

This commit is contained in:
Rishin Georgy Anil authored and Julius Marminge committed 2026-07-20 17:45:27 +02:00
1 parent 2240378dda
commit 21e11b0d65
8 files changed
+459 -168

No files matched your search

@@ -162,10 +162,14 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => {
0,
);
const createdPath = NodePath.join(tmp, "created.txt");
const postCheckpointIgnorePath = NodePath.join(tmp, ".gitignore");
const ignoredCreatedPath = NodePath.join(tmp, "state.cache");
yield* git(tmp, ["init"]);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: baselineRef });
yield* writeTextFile(createdPath, "created after baseline\n");
yield* writeTextFile(postCheckpointIgnorePath, "*.cache\n");
yield* writeTextFile(ignoredCreatedPath, "ignored after baseline\n");
expect(
yield* checkpointStore.restoreCheckpoint({
@@ -174,6 +178,36 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => {
}),
).toBe(true);
expect(yield* fileSystem.exists(createdPath)).toBe(false);
expect(yield* fileSystem.exists(postCheckpointIgnorePath)).toBe(false);
expect(yield* fileSystem.exists(ignoredCreatedPath)).toBe(false);
}),
);
it.effect("preserves files ignored by the restored checkpoint", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir("checkpoint-store-unborn-ignored-test-");
const fileSystem = yield* FileSystem.FileSystem;
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const baselineRef = checkpointRefForThreadTurn(
ThreadId.make("thread-unborn-ignored-checkpoint-store"),
0,
);
const ignorePath = NodePath.join(tmp, ".gitignore");
const ignoredPath = NodePath.join(tmp, "local.cache");
yield* git(tmp, ["init"]);
yield* writeTextFile(ignorePath, "*.cache\n");
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: baselineRef });
yield* writeTextFile(ignoredPath, "local-only data\n");
expect(
yield* checkpointStore.restoreCheckpoint({
cwd: tmp,
checkpointRef: baselineRef,
}),
).toBe(true);
expect(yield* fileSystem.readFileString(ignorePath)).toBe("*.cache\n");
expect(yield* fileSystem.readFileString(ignoredPath)).toBe("local-only data\n");
}),
);
@@ -788,6 +788,28 @@ it.layer(
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-revert-files-user-keep"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:00:00.100Z",
commandId: CommandId.make("cmd-revert-files-user-keep"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-files-user-keep"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-user-keep"),
role: "user",
text: "Keep this turn",
turnId: null,
streaming: false,
createdAt: "2026-01-01T00:00:00.100Z",
updatedAt: "2026-01-01T00:00:00.100Z",
},
});
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.make("evt-revert-files-3"),
@@ -836,8 +858,8 @@ it.layer(
],
turnId: TurnId.make("turn-keep"),
streaming: false,
createdAt: now,
updatedAt: now,
createdAt: "2026-01-01T00:00:00.200Z",
updatedAt: "2026-01-01T00:00:00.200Z",
},
});
@@ -863,6 +885,28 @@ it.layer(
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-revert-files-user-remove"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:00:00.300Z",
commandId: CommandId.make("cmd-revert-files-user-remove"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-files-user-remove"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-user-remove"),
role: "user",
text: "Revert here",
turnId: null,
streaming: false,
createdAt: "2026-01-01T00:00:00.300Z",
updatedAt: "2026-01-01T00:00:00.300Z",
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-revert-files-6"),
@@ -889,8 +933,8 @@ it.layer(
],
turnId: TurnId.make("turn-remove"),
streaming: false,
createdAt: now,
updatedAt: now,
createdAt: "2026-01-01T00:00:00.400Z",
updatedAt: "2026-01-01T00:00:00.400Z",
},
});
@@ -2250,6 +2294,28 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-revert-user-keep"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-revert"),
occurredAt: "2026-02-26T12:00:02.050Z",
commandId: CommandId.make("cmd-revert-user-keep"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-revert-user-keep"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-revert"),
messageId: MessageId.make("user-keep"),
role: "user",
text: "start",
turnId: null,
streaming: false,
createdAt: "2026-02-26T12:00:02.050Z",
updatedAt: "2026-02-26T12:00:02.050Z",
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-revert-4"),
@@ -2289,7 +2355,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert/turn/2"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("assistant-remove"),
assistantMessageId: null,
completedAt: "2026-02-26T12:00:03.000Z",
},
});
@@ -2309,7 +2375,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
messageId: MessageId.make("user-remove"),
role: "user",
text: "removed",
turnId: TurnId.make("turn-2"),
turnId: null,
streaming: false,
createdAt: "2026-02-26T12:00:03.050Z",
updatedAt: "2026-02-26T12:00:03.050Z",
@@ -2331,7 +2397,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
messageId: MessageId.make("assistant-remove"),
role: "assistant",
text: "removed",
turnId: TurnId.make("turn-2"),
turnId: TurnId.make("turn-1"),
streaming: false,
createdAt: "2026-02-26T12:00:03.100Z",
updatedAt: "2026-02-26T12:00:03.100Z",
@@ -2368,6 +2434,11 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
ORDER BY created_at ASC, message_id ASC
`;
assert.deepEqual(messageRows, [
{
messageId: "user-keep",
turnId: null,
role: "user",
},
{
messageId: "assistant-keep",
turnId: "turn-1",
@@ -2375,7 +2446,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
},
{
messageId: "user-remove",
turnId: "turn-2",
turnId: null,
role: "user",
},
]);
@@ -207,41 +207,21 @@ function retainProjectionMessagesAfterRevert(
messages: ReadonlyArray<ProjectionThreadMessage>,
turnCount: number,
): ReadonlyArray<ProjectionThreadMessage> {
const compareMessages = (left: ProjectionThreadMessage, right: ProjectionThreadMessage): number =>
left.createdAt.localeCompare(right.createdAt) || left.messageId.localeCompare(right.messageId);
const retainedMessageIds = new Set(
messages
.filter((message) => message.role === "user")
.toSorted(compareMessages)
.slice(0, turnCount + 1)
.map((message) => message.messageId),
);
const assistantTurnIndexes = new Map<string, number>();
let nextAssistantTurnIndex = 0;
for (const message of messages
.filter((entry) => entry.role === "assistant")
.toSorted(compareMessages)) {
if (message.turnId === null) {
if (nextAssistantTurnIndex < turnCount) {
retainedMessageIds.add(message.messageId);
}
nextAssistantTurnIndex += 1;
continue;
let userMessageIndex = 0;
let reachedTargetUser = false;
return messages.filter((message) => {
if (message.role === "system") {
return true;
}
let assistantTurnIndex = assistantTurnIndexes.get(message.turnId);
if (assistantTurnIndex === undefined) {
assistantTurnIndex = nextAssistantTurnIndex;
assistantTurnIndexes.set(message.turnId, assistantTurnIndex);
nextAssistantTurnIndex += 1;
if (reachedTargetUser) {
return false;
}
if (assistantTurnIndex < turnCount) {
retainedMessageIds.add(message.messageId);
if (message.role === "user") {
reachedTargetUser = userMessageIndex === turnCount;
userMessageIndex += 1;
}
}
return messages.filter(
(message) => message.role === "system" || retainedMessageIds.has(message.messageId),
);
return true;
});
}
function retainProjectionTurnsAfterRevert(
+73 -12
View File
@@ -682,7 +682,7 @@ describe("orchestration projector", () => {
expect(thread?.latestTurn).toBeNull();
});
it("retains the selected user prompt even when it is tied to the reverted turn", async () => {
it("removes assistant output produced after the selected steering message", async () => {
const createdAt = "2026-02-26T12:00:00.000Z";
const model = createEmptyReadModel(createdAt);
@@ -717,6 +717,24 @@ describe("orchestration projector", () => {
const events: ReadonlyArray<OrchestrationEvent> = [
makeEvent({
sequence: 2,
type: "thread.message-sent",
aggregateKind: "thread",
aggregateId: "thread-revert",
occurredAt: "2026-02-26T12:00:00.500Z",
commandId: "cmd-user-keep",
payload: {
threadId: "thread-revert",
messageId: "user-keep",
role: "user",
text: "start",
turnId: null,
streaming: false,
createdAt: "2026-02-26T12:00:00.500Z",
updatedAt: "2026-02-26T12:00:00.500Z",
},
}),
makeEvent({
sequence: 3,
type: "thread.turn-diff-completed",
aggregateKind: "thread",
aggregateId: "thread-revert",
@@ -724,17 +742,17 @@ describe("orchestration projector", () => {
commandId: "cmd-turn-1",
payload: {
threadId: "thread-revert",
turnId: "turn-1",
turnId: "checkpoint-only-turn",
checkpointTurnCount: 1,
checkpointRef: "refs/t3/checkpoints/thread-revert/turn/1",
status: "ready",
files: [],
assistantMessageId: "assistant-keep",
assistantMessageId: null,
completedAt: "2026-02-26T12:00:01.000Z",
},
}),
makeEvent({
sequence: 3,
sequence: 4,
type: "thread.message-sent",
aggregateKind: "thread",
aggregateId: "thread-revert",
@@ -752,7 +770,47 @@ describe("orchestration projector", () => {
},
}),
makeEvent({
sequence: 4,
sequence: 5,
type: "thread.activity-appended",
aggregateKind: "thread",
aggregateId: "thread-revert",
occurredAt: "2026-02-26T12:00:01.200Z",
commandId: "cmd-checkpoint-only-activity",
payload: {
threadId: "thread-revert",
activity: {
id: "checkpoint-only-activity",
tone: "tool",
kind: "command",
summary: "Retained activity",
payload: {},
turnId: "checkpoint-only-turn",
createdAt: "2026-02-26T12:00:01.200Z",
},
},
}),
makeEvent({
sequence: 6,
type: "thread.proposed-plan-upserted",
aggregateKind: "thread",
aggregateId: "thread-revert",
occurredAt: "2026-02-26T12:00:01.300Z",
commandId: "cmd-checkpoint-only-plan",
payload: {
threadId: "thread-revert",
proposedPlan: {
id: "checkpoint-only-plan",
turnId: "checkpoint-only-turn",
planMarkdown: "## Retained plan",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-02-26T12:00:01.300Z",
updatedAt: "2026-02-26T12:00:01.300Z",
},
},
}),
makeEvent({
sequence: 7,
type: "thread.turn-diff-completed",
aggregateKind: "thread",
aggregateId: "thread-revert",
@@ -765,12 +823,12 @@ describe("orchestration projector", () => {
checkpointRef: "refs/t3/checkpoints/thread-revert/turn/2",
status: "ready",
files: [],
assistantMessageId: "assistant-remove",
assistantMessageId: null,
completedAt: "2026-02-26T12:00:02.000Z",
},
}),
makeEvent({
sequence: 5,
sequence: 8,
type: "thread.message-sent",
aggregateKind: "thread",
aggregateId: "thread-revert",
@@ -781,14 +839,14 @@ describe("orchestration projector", () => {
messageId: "user-remove",
role: "user",
text: "removed",
turnId: "turn-2",
turnId: null,
streaming: false,
createdAt: "2026-02-26T12:00:02.050Z",
updatedAt: "2026-02-26T12:00:02.050Z",
},
}),
makeEvent({
sequence: 6,
sequence: 9,
type: "thread.message-sent",
aggregateKind: "thread",
aggregateId: "thread-revert",
@@ -799,14 +857,14 @@ describe("orchestration projector", () => {
messageId: "assistant-remove",
role: "assistant",
text: "removed",
turnId: "turn-2",
turnId: "turn-1",
streaming: false,
createdAt: "2026-02-26T12:00:02.100Z",
updatedAt: "2026-02-26T12:00:02.100Z",
},
}),
makeEvent({
sequence: 7,
sequence: 10,
type: "thread.reverted",
aggregateKind: "thread",
aggregateId: "thread-revert",
@@ -833,9 +891,12 @@ describe("orchestration projector", () => {
turnId: message.turnId,
})),
).toEqual([
{ id: "user-keep", role: "user", turnId: null },
{ id: "assistant-keep", role: "assistant", turnId: "turn-1" },
{ id: "user-remove", role: "user", turnId: "turn-2" },
{ id: "user-remove", role: "user", turnId: null },
]);
expect(thread?.activities.map((activity) => activity.id)).toEqual(["checkpoint-only-activity"]);
expect(thread?.proposedPlans.map((plan) => plan.id)).toEqual(["checkpoint-only-plan"]);
});
it("caps message and checkpoint retention for long-lived threads", async () => {
+16 -35
View File
@@ -84,41 +84,21 @@ function retainThreadMessagesAfterRevert(
messages: ReadonlyArray<OrchestrationMessage>,
turnCount: number,
): ReadonlyArray<OrchestrationMessage> {
const compareMessages = (left: OrchestrationMessage, right: OrchestrationMessage): number =>
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
const retainedMessageIds = new Set(
messages
.filter((message) => message.role === "user")
.toSorted(compareMessages)
.slice(0, turnCount + 1)
.map((message) => message.id),
);
const assistantTurnIndexes = new Map<string, number>();
let nextAssistantTurnIndex = 0;
for (const message of messages
.filter((entry) => entry.role === "assistant")
.toSorted(compareMessages)) {
if (message.turnId === null) {
if (nextAssistantTurnIndex < turnCount) {
retainedMessageIds.add(message.id);
}
nextAssistantTurnIndex += 1;
continue;
let userMessageIndex = 0;
let reachedTargetUser = false;
return messages.filter((message) => {
if (message.role === "system") {
return true;
}
let assistantTurnIndex = assistantTurnIndexes.get(message.turnId);
if (assistantTurnIndex === undefined) {
assistantTurnIndex = nextAssistantTurnIndex;
assistantTurnIndexes.set(message.turnId, assistantTurnIndex);
nextAssistantTurnIndex += 1;
if (reachedTargetUser) {
return false;
}
if (assistantTurnIndex < turnCount) {
retainedMessageIds.add(message.id);
if (message.role === "user") {
reachedTargetUser = userMessageIndex === turnCount;
userMessageIndex += 1;
}
}
return messages.filter(
(message) => message.role === "system" || retainedMessageIds.has(message.id),
);
return true;
});
}
function retainThreadActivitiesAfterRevert(
@@ -605,9 +585,10 @@ export function projectEvent(
thread.messages,
payload.turnCount,
).slice(-MAX_THREAD_MESSAGES);
const retainedTurnIds = new Set(
messages.flatMap((message) => (message.turnId === null ? [] : [message.turnId])),
);
const retainedTurnIds = new Set([
...checkpoints.map((checkpoint) => checkpoint.turnId),
...messages.flatMap((message) => (message.turnId === null ? [] : [message.turnId])),
]);
const proposedPlans = retainThreadProposedPlansAfterRevert(
thread.proposedPlans,
retainedTurnIds,
+68 -42
View File
@@ -748,51 +748,77 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
}
const headExists = yield* hasHeadCommit(input.cwd);
let snapshotHasEntries = true;
if (!headExists) {
// In an unborn repository every restored path is still untracked from
// Git's perspective. Clean first so we remove post-checkpoint files
// without immediately deleting the files restored from the snapshot.
yield* execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const snapshotEntries = yield* execute({
operation,
cwd: input.cwd,
args: ["ls-tree", "-r", "--name-only", commitOid],
});
snapshotHasEntries = snapshotEntries.stdout.trim().length > 0;
}
if (headExists || snapshotHasEntries) {
yield* execute({
operation,
cwd: input.cwd,
args: [
"restore",
"--source",
commitOid,
"--worktree",
...(headExists ? ["--staged"] : []),
"--",
".",
],
});
}
if (headExists) {
yield* execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
yield* execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
const tempIndexPath = path.join(
gitCommonDir,
`t3-checkpoint-restore-index-${NodeCrypto.randomUUID()}`,
);
const restoreEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
};
const cleanupTempIndex = fileSystem
.remove(tempIndexPath, { force: true })
.pipe(Effect.ignore);
yield* Effect.gen(function* () {
// The real index is empty in an unborn repository. Clean before
// restoring so untracked paths cannot block the checkout.
yield* execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const snapshotEntries = yield* execute({
operation,
cwd: input.cwd,
args: ["ls-tree", "-r", "--name-only", commitOid],
});
if (snapshotEntries.stdout.trim().length > 0) {
yield* execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--", "."],
});
}
// Load the checkpoint tree into a temporary index before the final
// clean. Snapshot files are then protected as tracked, while paths
// ignored only by post-checkpoint rules are removed safely without -x.
yield* execute({
operation,
cwd: input.cwd,
args: ["read-tree", commitOid],
env: restoreEnv,
});
yield* execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
env: restoreEnv,
});
}).pipe(Effect.ensuring(cleanupTempIndex));
return true;
}
yield* execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
yield* execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
return true;
}),
@@ -763,6 +763,72 @@ describe("applyThreadDetailEvent", () => {
}
});
it("removes assistant output produced after the selected steering message", () => {
const steeringThread: OrchestrationThread = {
...baseThread,
messages: [
{
id: MessageId.make("steering-user-initial"),
role: "user",
text: "Start the task",
turnId: null,
streaming: false,
createdAt: "2026-04-01T01:00:00.000Z",
updatedAt: "2026-04-01T01:00:00.000Z",
},
{
id: MessageId.make("steering-assistant-before"),
role: "assistant",
text: "Working on it",
turnId: TurnId.make("steering-turn"),
streaming: false,
createdAt: "2026-04-01T02:00:00.000Z",
updatedAt: "2026-04-01T02:00:00.000Z",
},
{
id: MessageId.make("steering-user-target"),
role: "user",
text: "Actually, change direction",
turnId: null,
streaming: false,
createdAt: "2026-04-01T03:00:00.000Z",
updatedAt: "2026-04-01T03:00:00.000Z",
},
{
id: MessageId.make("steering-assistant-after"),
role: "assistant",
text: "Changed direction",
turnId: TurnId.make("steering-turn"),
streaming: false,
createdAt: "2026-04-01T04:00:00.000Z",
updatedAt: "2026-04-01T04:00:00.000Z",
},
],
};
const result = applyThreadDetailEvent(steeringThread, {
...baseEventFields,
sequence: 14,
occurredAt: "2026-04-01T05:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.reverted",
payload: {
threadId: ThreadId.make("thread-1"),
turnCount: 1,
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.messages.map((message) => message.id)).toEqual([
MessageId.make("steering-user-initial"),
MessageId.make("steering-assistant-before"),
MessageId.make("steering-user-target"),
]);
}
});
it("removes every message after the selected user prompt when checkpoints exist", () => {
const threadWithData: OrchestrationThread = {
...baseThread,
@@ -871,6 +937,15 @@ describe("applyThreadDetailEvent", () => {
},
{
id: MessageId.make("msg-3"),
role: "user",
text: "Second",
turnId: null,
streaming: false,
createdAt: "2026-04-01T02:30:00.000Z",
updatedAt: "2026-04-01T02:30:00.000Z",
},
{
id: MessageId.make("msg-4"),
role: "assistant",
text: "Response 2",
turnId: TurnId.make("turn-2"),
@@ -895,7 +970,7 @@ describe("applyThreadDetailEvent", () => {
checkpointRef: CheckpointRef.make("ref-2"),
status: "ready",
files: [],
assistantMessageId: MessageId.make("msg-3"),
assistantMessageId: MessageId.make("msg-4"),
completedAt: "2026-04-01T03:00:00.000Z",
},
],
@@ -919,11 +994,94 @@ describe("applyThreadDetailEvent", () => {
// turn-2 checkpoint is filtered out (turnCount 2 > revert target 1)
expect(result.thread.checkpoints).toHaveLength(1);
expect(result.thread.checkpoints[0]?.turnId).toBe("turn-1");
// msg-3 (turn-2) is filtered, msg-1 (no turn) and msg-2 (turn-1) remain
expect(result.thread.messages).toHaveLength(2);
// The selected second user prompt remains, but its turn-2 response is removed.
expect(result.thread.messages).toHaveLength(3);
expect(result.thread.latestTurn?.turnId).toBe("turn-1");
}
});
it("retains checkpoint turn entities when no assistant message exists", () => {
const retainedTurnId = TurnId.make("checkpoint-only-turn");
const checkpointOnlyThread: OrchestrationThread = {
...baseThread,
messages: [
{
id: MessageId.make("checkpoint-only-user"),
role: "user",
text: "Start",
turnId: null,
streaming: false,
createdAt: "2026-04-01T01:00:00.000Z",
updatedAt: "2026-04-01T01:00:00.000Z",
},
{
id: MessageId.make("checkpoint-only-next-user"),
role: "user",
text: "Try again",
turnId: null,
streaming: false,
createdAt: "2026-04-01T02:00:00.000Z",
updatedAt: "2026-04-01T02:00:00.000Z",
},
],
checkpoints: [
{
turnId: retainedTurnId,
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.make("checkpoint-only-ref"),
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-04-01T01:30:00.000Z",
},
],
proposedPlans: [
{
id: "checkpoint-only-plan",
turnId: retainedTurnId,
planMarkdown: "## Retained plan",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-04-01T01:10:00.000Z",
updatedAt: "2026-04-01T01:10:00.000Z",
},
],
activities: [
{
id: EventId.make("checkpoint-only-activity"),
tone: "tool",
kind: "command",
summary: "Retained activity",
payload: {},
turnId: retainedTurnId,
createdAt: "2026-04-01T01:20:00.000Z",
},
],
};
const result = applyThreadDetailEvent(checkpointOnlyThread, {
...baseEventFields,
sequence: 14,
occurredAt: "2026-04-01T03:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.reverted",
payload: {
threadId: ThreadId.make("thread-1"),
turnCount: 1,
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.proposedPlans.map((plan) => plan.id)).toEqual([
"checkpoint-only-plan",
]);
expect(result.thread.activities.map((activity) => activity.id)).toEqual([
EventId.make("checkpoint-only-activity"),
]);
}
});
});
describe("no-op events", () => {
@@ -418,9 +418,10 @@ export function applyThreadDetailEvent(
);
const messages = retainMessagesAfterRevert(thread.messages, event.payload.turnCount);
const retainedTurnIds = new Set(
messages.flatMap((message) => (message.turnId === null ? [] : [message.turnId])),
);
const retainedTurnIds = new Set([
...Arr.map(checkpoints, (checkpoint) => checkpoint.turnId),
...messages.flatMap((message) => (message.turnId === null ? [] : [message.turnId])),
]);
const proposedPlans = pipe(
thread.proposedPlans,
Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)),
@@ -535,40 +536,19 @@ function retainMessagesAfterRevert(
messages: ReadonlyArray<OrchestrationMessage>,
turnCount: number,
): OrchestrationMessage[] {
const compareMessages = (left: OrchestrationMessage, right: OrchestrationMessage): number =>
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
const retainedMessageIds = new Set(
messages
.filter((message) => message.role === "user")
.toSorted(compareMessages)
.slice(0, turnCount + 1)
.map((message) => message.id),
);
const assistantTurnIndexes = new Map<string, number>();
let nextAssistantTurnIndex = 0;
for (const message of messages
.filter((entry) => entry.role === "assistant")
.toSorted(compareMessages)) {
if (message.turnId === null) {
if (nextAssistantTurnIndex < turnCount) {
retainedMessageIds.add(message.id);
}
nextAssistantTurnIndex += 1;
continue;
let userMessageIndex = 0;
let reachedTargetUser = false;
return Arr.filter(messages, (message) => {
if (message.role === "system") {
return true;
}
let assistantTurnIndex = assistantTurnIndexes.get(message.turnId);
if (assistantTurnIndex === undefined) {
assistantTurnIndex = nextAssistantTurnIndex;
assistantTurnIndexes.set(message.turnId, assistantTurnIndex);
nextAssistantTurnIndex += 1;
if (reachedTargetUser) {
return false;
}
if (assistantTurnIndex < turnCount) {
retainedMessageIds.add(message.id);
if (message.role === "user") {
reachedTargetUser = userMessageIndex === turnCount;
userMessageIndex += 1;
}
}
return Arr.filter(
messages,
(message) => message.role === "system" || retainedMessageIds.has(message.id),
);
return true;
});
}