Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): 编辑或回到线程第一轮时换空线程,不再报「无可用边界」(#4994) (#5014)
Lizi7d0ebfd059f8
diff --git a/apps/desktop/src/main/__tests__/fork.test.ts b/apps/desktop/src/main/__tests__/fork.test.tsindex 57092719db..7cc8b480e1 100644--- a/apps/desktop/src/main/__tests__/fork.test.ts+++ b/apps/desktop/src/main/__tests__/fork.test.ts@@ -2124,3 +2124,71 @@ describe('forkSessionAtMessage', () => {expect(txCalls).toHaveLength(0);});});++describe('isCodexNativeThreadStart (#4994)', () => {+ const user = (createdAt: number) => ({ role: 'user', content: '', agentMeta: null, createdAt });+ const agentSwitch = (createdAt: number, fromAgentKind: 'cc' | 'codex', fromSdkSessionId: string | null) => ({+ role: 'agent_switch',+ content: JSON.stringify({ fromAgentKind, toAgentKind: fromAgentKind === 'cc' ? 'codex' : 'cc', fromSdkSessionId }),+ agentMeta: null,+ createdAt,+ });+ const contextRebuild = (createdAt: number) => ({ role: 'context_rebuild', content: '{}', agentMeta: null, createdAt });++ it('treats an empty timeline as the thread start', async () => {+ const { isCodexNativeThreadStart } = await import('../maker-orchestration/fork');+ expect(isCodexNativeThreadStart([], 'thread-x')).toBe(true);+ });++ it('rejects when the current thread already has an earlier user turn', async () => {+ const { isCodexNativeThreadStart } = await import('../maker-orchestration/fork');+ expect(isCodexNativeThreadStart([user(1000)], 'thread-x')).toBe(false);+ });++ it('ignores turns of the engine the session switched away from', async () => {+ const { isCodexNativeThreadStart } = await import('../maker-orchestration/fork');+ expect(isCodexNativeThreadStart([user(1000), agentSwitch(2000, 'cc', 'claude-sdk')], 'thread-x')).toBe(true);+ });++ it('counts earlier turns of a resumed parked thread across switch boundaries', async () => {+ const { isCodexNativeThreadStart } = await import('../maker-orchestration/fork');+ expect(isCodexNativeThreadStart([+ user(1000),+ agentSwitch(2000, 'codex', 'thread-x'),+ user(3000),+ agentSwitch(4000, 'cc', 'claude-sdk'),+ ], 'thread-x')).toBe(false);+ });++ it('ignores turns before a context rebuild', async () => {+ const { isCodexNativeThreadStart } = await import('../maker-orchestration/fork');+ expect(isCodexNativeThreadStart([user(1000), contextRebuild(2000)], 'thread-x')).toBe(true);+ });++ it('does not let a pre-rebuild switch restore the current thread', async () => {+ const { isCodexNativeThreadStart } = await import('../maker-orchestration/fork');+ expect(isCodexNativeThreadStart([+ user(1000),+ agentSwitch(2000, 'codex', 'thread-x'),+ user(3000),+ agentSwitch(4000, 'cc', 'claude-sdk'),+ contextRebuild(5000),+ ], 'thread-x')).toBe(true);+ });++ it('withholds thread start when a switch boundary is unparseable', async () => {+ const { isCodexNativeThreadStart } = await import('../maker-orchestration/fork');+ expect(isCodexNativeThreadStart([+ user(1000),+ { role: 'agent_switch', content: '{not-json', agentMeta: null, createdAt: 2000 },+ ], 'thread-x')).toBe(false);+ });++ it('withholds thread start when a switch boundary has no fromSdkSessionId', async () => {+ const { isCodexNativeThreadStart } = await import('../maker-orchestration/fork');+ expect(isCodexNativeThreadStart([+ user(1000),+ agentSwitch(2000, 'cc', null),+ ], 'thread-x')).toBe(false);+ });+});diff --git a/apps/desktop/src/main/__tests__/rewind.test.ts b/apps/desktop/src/main/__tests__/rewind.test.tsindex 1a5430b9d1..fde4b2a8ad 100644--- a/apps/desktop/src/main/__tests__/rewind.test.ts+++ b/apps/desktop/src/main/__tests__/rewind.test.ts@@ -161,9 +161,10 @@ const txMock = vi.fn((name: string, args: unknown) => {txCalls.push({ name, args });return Promise.resolve({});});+const queryOneMock = vi.fn(async () => ({ cleared_at: null as number | null }));vi.mock('../localDb/client/current', () => ({- getDbClient: () => ({ drizzle: fakeDb, tx: txMock }),+ getDbClient: () => ({ drizzle: fakeDb, tx: txMock, queryOne: queryOneMock }),}));let commitRewindAtMessage: typeof import('../maker-orchestration/rewind').commitRewindAtMessage;@@ -177,6 +178,8 @@ beforeEach(async () => {selectQueue.length = 0;txCalls.length = 0;txMock.mockClear();+ queryOneMock.mockReset();+ queryOneMock.mockResolvedValue({ cleared_at: null });setLastAssistantTranscriptUuidMock.mockClear();previewRewindFilesMock.mockReset();commitRewindFilesMock.mockReset();@@ -251,6 +254,11 @@ async function waitFor(condition: () => boolean): Promise<void> {throw new Error('condition was not met');}+function enqueueCodexClearGeneration(clearedAt: number | null = null): void {+ // loadCodexRewindNativeBoundary 在原生边界查询前读 sessions.clearedAt。+ selectQueue.push([{ clearedAt }]);+}+function makeSessionRow(over: Partial<Record<string, unknown>> = {}) {return {id: 'sess-1',@@ -909,13 +917,15 @@ describe('commitRewindAtMessage', () => {makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 }),makeUserMessageRow({ clientId: 'later-user', createdAt: 5000 }),]); // Codex tail turns+ enqueueCodexClearGeneration();selectQueue.push([], // Codex 原生边界行(#4421):无锚点+ [], // 线程第一轮判定:时间线上 target 之前没有 user 行[makeSessionRow({ agentKind: 'codex' })]); // post-update selectconst result = await commitRewindAtMessage('sess-1', 'client-id');expect(commitRewindFilesMock).toHaveBeenCalledTimes(1);- expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 2 });+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 2, rewindsToNativeThreadStart: true });const txCall = txCalls.find((c) => c.name === 'rewind.commit');if (!txCall) throw new Error('缺少 rewind.commit tx 调用');expect(txCall.args).toMatchObject({@@ -932,6 +942,7 @@ describe('commitRewindAtMessage', () => {selectQueue.push([makeUserMessageRow({ agentMeta: null })]); // target userselectQueue.push([]); // agent_switch 边界守卫:无边界selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]); // Codex tail turns+ enqueueCodexClearGeneration();selectQueue.push([// desc 顺序:最近的在前。上一轮 assistant 带已完成 turn 的原生锚点。makeAssistantMessageRow({@@ -962,7 +973,9 @@ describe('commitRewindAtMessage', () => {selectQueue.push([makeUserMessageRow({ agentMeta: null })]);selectQueue.push([]);selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);+ enqueueCodexClearGeneration();selectQueue.push([]);+ selectQueue.push([]); // 线程第一轮判定selectQueue.push([makeSessionRow({ agentKind: 'codex' })]);await commitRewindAtMessage('sess-1', 'client-id');@@ -990,6 +1003,7 @@ describe('commitRewindAtMessage', () => {selectQueue.push([makeUserMessageRow({ agentMeta: null })]);selectQueue.push([]);selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);+ enqueueCodexClearGeneration();selectQueue.push([// 旧数据:assistant 无 nativeForkAnchor;error 行不算真实输出。{ role: 'error', content: '"boom"', agentMeta: null, createdAt: 2600 },@@ -1003,13 +1017,148 @@ describe('commitRewindAtMessage', () => {expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1, forkAtTimestampMs: 2500 });});- it('Codex: omits boundary fields when target is the first turn of the native thread (#4421)', async () => {+ it('Codex: marks the native thread start when target is the first turn of the native thread (#4994)', async () => {useFakeSession('codex');commitRewindFilesMock.mockResolvedValueOnce({ sdkSessionId: 'rollback-thread-id' });selectQueue.push([makeUserMessageRow({ agentMeta: null })]);selectQueue.push([]);selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);+ enqueueCodexClearGeneration();+ selectQueue.push([]); // target 之前没有任何行+ selectQueue.push([]); // 时间线上也没有属于当前线程的 user 行+ selectQueue.push([makeSessionRow({ agentKind: 'codex' })]);++ await commitRewindAtMessage('sess-1', 'client-id');++ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true });+ expect(txCalls.find((c) => c.name === 'rewind.commit')?.args).toMatchObject({+ expectedClearedAt: null,+ });+ });++ it('Codex: rechecks /clear generation before replacing the native thread (#4994)', async () => {+ useFakeSession('codex');+ selectQueue.push([makeUserMessageRow({ agentMeta: null })]);+ selectQueue.push([]);+ selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);+ enqueueCodexClearGeneration();selectQueue.push([]); // target 之前没有任何行+ selectQueue.push([]); // 时间线上也没有属于当前线程的 user 行+ queryOneMock.mockResolvedValueOnce({ cleared_at: 4000 });++ await expect(commitRewindAtMessage('sess-1', 'client-id')).rejects.toMatchObject({+ code: 'REWIND_UNSUPPORTED_HISTORY',+ });+ expect(commitRewindFilesMock).not.toHaveBeenCalled();+ expect(txCalls).toHaveLength(0);+ });++ const agentSwitchRow = (createdAt: number, fromAgentKind: 'cc' | 'codex', fromSdkSessionId: string) => ({+ role: 'agent_switch',+ content: JSON.stringify({ fromAgentKind, toAgentKind: fromAgentKind === 'cc' ? 'codex' : 'cc', fromSdkSessionId }),+ agentMeta: null,+ createdAt,+ });++ it('Codex: does not mark the thread start when an earlier turn has no recoverable boundary (#4994)', async () => {+ useFakeSession('codex');+ selectQueue.push([makeUserMessageRow({ agentMeta: null })]);+ selectQueue.push([]);+ selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);+ enqueueCodexClearGeneration();+ selectQueue.push([+ // 上一轮失败:只有 error 行,没有锚点也没有真实输出时间。+ { role: 'error', content: '"boom"', agentMeta: null, createdAt: 2600 },+ makeUserMessageRow({ rowid: 8, clientId: 'earlier-user', createdAt: 2000 }),+ ]);+ selectQueue.push([{ role: 'user', content: '', createdAt: 2000 }]); // 时间线:当前线程已有更早的 user+ selectQueue.push([makeSessionRow({ agentKind: 'codex' })]);++ await commitRewindAtMessage('sess-1', 'client-id');++ // 不能把前面的轮次当成不存在:交给 maker-core 按「无可用边界」明确失败,而不是换空线程。+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1 });+ });++ it('Codex: marks the thread start for the first turn after switching from another engine (#4994)', async () => {+ useFakeSession('codex');+ commitRewindFilesMock.mockResolvedValueOnce({ sdkSessionId: 'fresh-thread-id' });+ selectQueue.push([makeUserMessageRow({ agentMeta: null })]);+ selectQueue.push([]);+ selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);+ enqueueCodexClearGeneration();+ selectQueue.push([+ agentSwitchRow(2800, 'cc', 'claude-sdk'),+ makeAssistantMessageRow({ createdAt: 2500 }),+ makeUserMessageRow({ rowid: 8, clientId: 'claude-user', createdAt: 2000 }),+ ]);+ selectQueue.push([+ { role: 'user', content: '', createdAt: 2000 },+ agentSwitchRow(2800, 'cc', 'claude-sdk'),+ ]);+ selectQueue.push([makeSessionRow({ agentKind: 'codex' })]);++ await commitRewindAtMessage('sess-1', 'client-id');++ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', {+ tailTurnsToDrop: 1,+ rewindsToNativeThreadStart: true,+ });+ expect(txCalls.find((c) => c.name === 'rewind.commit')?.args).toMatchObject({+ sdkSessionId: 'fresh-thread-id',+ });+ });++ it('Codex: keeps earlier turns of a resumed parked thread out of the thread-start marker (#4994)', async () => {+ useFakeSession('codex');+ selectQueue.push([makeUserMessageRow({ agentMeta: null })]);+ selectQueue.push([]);+ selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);+ enqueueCodexClearGeneration();+ selectQueue.push([+ // 切回停泊的同一条 Codex 线程;旧数据没有锚点。+ agentSwitchRow(2800, 'cc', 'claude-sdk'),+ makeUserMessageRow({ rowid: 7, clientId: 'claude-user', createdAt: 2400 }),+ agentSwitchRow(2200, 'codex', 'codex-thread-old'),+ makeAssistantMessageRow({ createdAt: 2100, agentMeta: null }),+ makeUserMessageRow({ rowid: 5, clientId: 'codex-user', createdAt: 2000 }),+ ]);+ selectQueue.push([+ { role: 'user', content: '', createdAt: 2000 },+ agentSwitchRow(2200, 'codex', 'codex-thread-old'),+ { role: 'user', content: '', createdAt: 2400 },+ agentSwitchRow(2800, 'cc', 'claude-sdk'),+ ]);+ selectQueue.push([makeSessionRow({ agentKind: 'codex' })]);++ await commitRewindAtMessage('sess-1', 'client-id');++ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1 });+ });++ it('Codex: withholds the thread-start marker when a prior switch boundary is unparseable (#4994)', async () => {+ useFakeSession('codex');+ selectQueue.push([makeUserMessageRow({ agentMeta: null })]);+ selectQueue.push([]);+ selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);+ enqueueCodexClearGeneration();+ selectQueue.push([{ role: 'agent_switch', content: '{not-json', agentMeta: null, createdAt: 2800 }]);+ selectQueue.push([{ role: 'agent_switch', content: '{not-json', createdAt: 2800 }]);+ selectQueue.push([makeSessionRow({ agentKind: 'codex' })]);++ await commitRewindAtMessage('sess-1', 'client-id');++ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1 });+ });++ it('Codex: withholds the thread-start marker when a prior switch has no fromSdkSessionId (#4994)', async () => {+ useFakeSession('codex');+ selectQueue.push([makeUserMessageRow({ agentMeta: null })]);+ selectQueue.push([]);+ selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);+ enqueueCodexClearGeneration();+ selectQueue.push([agentSwitchRow(2800, 'cc', '')]);+ selectQueue.push([agentSwitchRow(2800, 'cc', '')]);selectQueue.push([makeSessionRow({ agentKind: 'codex' })]);await commitRewindAtMessage('sess-1', 'client-id');@@ -1143,7 +1292,10 @@ describe('commitRewindAtMessage', () => {detectCwdMock.mockResolvedValueOnce({ gitInstalled: true, isGitRepo: true, repoRoot: '/repo', isInsideWorktree: false });listSnapshotsMock.mockResolvedValueOnce([]);getHeadMock.mockRejectedValueOnce(new Error('unborn HEAD'));- selectQueue.push([makeUserMessageRow({ agentMeta: null })], [], [makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })], [], // Codex 原生边界行(#4421):无锚点+ selectQueue.push([makeUserMessageRow({ agentMeta: null })], [], [makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);+ enqueueCodexClearGeneration();+ selectQueue.push([], // Codex 原生边界行(#4421):无锚点+ [], // 线程第一轮判定:时间线上 target 之前没有 user 行[makeSessionRow({ agentKind: 'codex' })]);await commitRewindAtMessage('sess-1', 'client-id');@@ -1157,7 +1309,7 @@ describe('commitRewindAtMessage', () => {// conversation-only 不进 restore 执行器, 也不动任何文件相关 git 操作。expect(executeCodexFileRestorePlanWithThreadRollbackMock).not.toHaveBeenCalled();expect(writeWorktreeTreeForPathsMock).not.toHaveBeenCalled();- expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1 });+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true });});it('Codex commit: shadow 链被截断 → 降级 conversation-only(不做部分文件回退)', async () => {@@ -1180,7 +1332,10 @@ describe('commitRewindAtMessage', () => {],truncated: true,});- selectQueue.push([makeUserMessageRow({ agentMeta: null })], [], [makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })], [], // Codex 原生边界行(#4421):无锚点+ selectQueue.push([makeUserMessageRow({ agentMeta: null })], [], [makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);+ enqueueCodexClearGeneration();+ selectQueue.push([], // Codex 原生边界行(#4421):无锚点+ [], // 线程第一轮判定:时间线上 target 之前没有 user 行[makeSessionRow({ agentKind: 'codex' })]);await commitRewindAtMessage('sess-1', 'client-id');@@ -1248,6 +1403,8 @@ describe('commitRewindAtMessage', () => {selectQueue.push([makeUserMessageRow({ agentMeta: null })], [], [makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 }),]);+ enqueueCodexClearGeneration();+ selectQueue.push([], []); // 无锚点 + 线程第一轮判定await expect(commitRewindAtMessage('sess-1', 'client-id')).rejects.toThrow('thread rollback failed');@@ -1256,7 +1413,7 @@ describe('commitRewindAtMessage', () => {'sess-1',expect.objectContaining({ commitThreadRollback: expect.any(Function), onCompensationError: expect.any(Function) }),);- expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1 });+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true });});it('Codex commit: shadow file-restore 计划分发给 restore 执行器', async () => {@@ -1280,7 +1437,11 @@ describe('commitRewindAtMessage', () => {[makeUserMessageRow({ agentMeta: null })],[], // agent_switch 边界守卫:无边界[makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })],+ );+ enqueueCodexClearGeneration();+ selectQueue.push([], // Codex 原生边界行(#4421):无锚点+ [], // 线程第一轮判定:时间线上 target 之前没有 user 行[makeSessionRow({ agentKind: 'codex' })],);@@ -1300,7 +1461,7 @@ describe('commitRewindAtMessage', () => {expect.objectContaining({ commitThreadRollback: expect.any(Function), onCompensationError: expect.any(Function) }),);expect(executeCodexFileRewindPlanWithThreadRollbackMock).not.toHaveBeenCalled();- expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1 });+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true });const txCall = txCalls.find((c) => c.name === 'rewind.commit');if (!txCall) throw new Error('缺少 rewind.commit tx 调用');expect(txCall.args).toMatchObject({ sdkSessionId: 'restore-thread-id' });@@ -1328,7 +1489,11 @@ describe('commitRewindAtMessage', () => {[makeUserMessageRow({ agentMeta: null })],[],[makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })],+ );+ enqueueCodexClearGeneration();+ selectQueue.push([],+ [], // 线程第一轮判定:时间线上 target 之前没有 user 行[makeSessionRow({ agentKind: 'codex' })],);@@ -1337,7 +1502,7 @@ describe('commitRewindAtMessage', () => {expect(executeCodexFileRestorePlanWithThreadRollbackMock).not.toHaveBeenCalled();expect(executeCodexFileRewindPlanWithThreadRollbackMock).not.toHaveBeenCalled();expect(listShadowSavepointsMock).not.toHaveBeenCalled();- expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1 });+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true });});it('Codex commit: legacy file-rewind 计划仍分发给 revert 执行器', async () => {@@ -1350,7 +1515,11 @@ describe('commitRewindAtMessage', () => {[makeUserMessageRow({ agentMeta: null })],[], // agent_switch 边界守卫:无边界[makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })],+ );+ enqueueCodexClearGeneration();+ selectQueue.push([], // Codex 原生边界行(#4421):无锚点+ [], // 线程第一轮判定:时间线上 target 之前没有 user 行[makeSessionRow({ agentKind: 'codex' })],);@@ -1362,7 +1531,7 @@ describe('commitRewindAtMessage', () => {expect.objectContaining({ commitThreadRollback: expect.any(Function), onCompensationError: expect.any(Function) }),);expect(executeCodexFileRestorePlanWithThreadRollbackMock).not.toHaveBeenCalled();- expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1 });+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true });});it('Codex commit: restore 执行器内 thread rollback 失败 → 错误传播, DB 事务不执行', async () => {@@ -1387,11 +1556,13 @@ describe('commitRewindAtMessage', () => {[], // agent_switch 边界守卫:无边界[makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })],);+ enqueueCodexClearGeneration();+ selectQueue.push([], []); // 无锚点 + 线程第一轮判定await expect(commitRewindAtMessage('sess-1', 'client-id')).rejects.toThrow('thread rollback failed');expect(executeCodexFileRestorePlanWithThreadRollbackMock).toHaveBeenCalledTimes(1);- expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1 });+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true });expect(txCalls).toHaveLength(0);});diff --git a/apps/desktop/src/main/__tests__/rewindNativeBoundarySqlite.test.ts b/apps/desktop/src/main/__tests__/rewindNativeBoundarySqlite.test.tsnew file mode 100644index 0000000000..6a3c3e1214--- /dev/null+++ b/apps/desktop/src/main/__tests__/rewindNativeBoundarySqlite.test.ts@@ -0,0 +1,247 @@+/**+ * loadCodexRewindNativeBoundary 的真实 SQLite 回归 (#4994 review P2)。+ *+ * rewind.test.ts 按队列喂查询结果,不会执行 /clear 截断与 context_rebuild+ * rewind_at 豁免。这里用 drizzle + better-sqlite3 跑同一条 SQL,确认旧线程+ * 边界不会漏进第一轮判定。+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import Database from 'better-sqlite3';+import { drizzle } from 'drizzle-orm/better-sqlite3';+import { getTableConfig } from 'drizzle-orm/sqlite-core';++import type { DbClient } from '../localDb/client/DbClient';+import { clearCurrentDbClient, setCurrentDbClient } from '../localDb/client/current';+import { messages, sessions } from '../localDb/schema';++const commitRewindFilesMock = vi.fn();+const isTurnRunningMock = vi.fn(() => false);+const recomputePrRefsForSessionMock = vi.fn();+const executeCodexFileRewindPlanWithThreadRollbackMock = vi.fn();+const executeCodexFileRestorePlanWithThreadRollbackMock = vi.fn();+const detectCwdMock = vi.fn();++type FakeSession = {+ agentKind: 'codex';+ sdkSessionId: string;+ workDir: string;+ remoteHostId: string | null;+ isTurnRunning: () => boolean;+ commitRewindFiles: typeof commitRewindFilesMock;+};++const fakeSession: FakeSession = {+ agentKind: 'codex',+ sdkSessionId: 'codex-thread-live',+ workDir: '/work',+ remoteHostId: null,+ isTurnRunning: isTurnRunningMock,+ commitRewindFiles: commitRewindFilesMock,+};++vi.mock('../maker-host/index.js', () => ({+ getMaker: () => ({+ getSession: () => fakeSession,+ getSessionMeta: async () => ({ sdkSessionId: fakeSession.sdkSessionId }),+ }),+}));++vi.mock('../git-context/prRefsStore.js', () => ({+ recomputePrRefsForSession: recomputePrRefsForSessionMock,+}));++vi.mock('../git-snapshot/codexFileRewindExecutor', () => ({+ executeCodexFileRewindPlanWithThreadRollback: executeCodexFileRewindPlanWithThreadRollbackMock,+}));++vi.mock('../git-snapshot/codexFileRestoreExecutor', () => ({+ executeCodexFileRestorePlanWithThreadRollback: executeCodexFileRestorePlanWithThreadRollbackMock,+}));++vi.mock('../worktree/WorktreeManager.js', () => ({+ detectCwd: detectCwdMock,+}));++vi.mock('../messagePersistBroadcaster.js', () => ({+ setLastAssistantTranscriptUuid: vi.fn(),+}));++const txMock = vi.fn(async () => ({}));++let sqlite: Database.Database;+let client: DbClient;+let commitRewindAtMessage: typeof import('../maker-orchestration/rewind').commitRewindAtMessage;++function insertSession(over: { clearedAt?: number | null } = {}): void {+ client.drizzle+ .insert(sessions)+ .values({+ id: 'sess-1',+ title: 'demo',+ workingDir: '/work',+ model: 'gpt-5.4',+ agentKind: 'codex',+ sdkSessionId: 'codex-thread-live',+ createdAt: 1,+ updatedAt: 1,+ clearedAt: over.clearedAt ?? null,+ })+ .run();+}++function insertMessage(row: {+ id: string;+ role: 'user' | 'assistant' | 'context_rebuild' | 'agent_switch';+ createdAt: number;+ rewindAt?: number | null;+ content?: string;+ agentMeta?: string | null;+}): void {+ client.drizzle+ .insert(messages)+ .values({+ id: row.id,+ clientId: row.id,+ sessionId: 'sess-1',+ role: row.role,+ content: row.content ?? '"hi"',+ agentMeta: row.agentMeta ?? null,+ createdAt: row.createdAt,+ rewindAt: row.rewindAt ?? null,+ })+ .run();+}++const oldAnchorMeta = JSON.stringify({+ turnCompleted: true,+ nativeForkAnchor: {+ agentKind: 'codex',+ kind: 'turn',+ sdkSessionId: 'codex-thread-old',+ id: 'turn-old',+ },+});++beforeEach(async () => {+ sqlite = new Database(':memory:');+ for (const table of [sessions, messages]) {+ const { name, columns } = getTableConfig(table);+ sqlite.exec(+ `CREATE TABLE "${name}" (${columns.map((column) => `"${column.name}" ${column.getSQLType()}`).join(', ')})`,+ );+ }+ const db = drizzle(sqlite);+ client = {+ drizzle: db,+ tx: txMock,+ queryOne: async <T = unknown>(sql: string, params: unknown[] = []) =>+ sqlite.prepare(sql).get(...params) as T | undefined,+ } as unknown as DbClient;+ setCurrentDbClient(client, 'test-user');+ txMock.mockClear();+ txMock.mockResolvedValue({});+ commitRewindFilesMock.mockReset();+ commitRewindFilesMock.mockResolvedValue({ sdkSessionId: 'fresh-thread' });+ executeCodexFileRewindPlanWithThreadRollbackMock.mockReset();+ executeCodexFileRewindPlanWithThreadRollbackMock.mockImplementation(+ async (+ _plan: unknown,+ _sessionId: string,+ hooks: { commitThreadRollback: (execution: unknown) => Promise<unknown> },+ ) => ({+ fileRewind: null,+ threadRollback: await hooks.commitThreadRollback(null),+ }),+ );+ executeCodexFileRestorePlanWithThreadRollbackMock.mockReset();+ executeCodexFileRestorePlanWithThreadRollbackMock.mockImplementation(+ async (+ _plan: unknown,+ _sessionId: string,+ hooks: { commitThreadRollback: (execution: unknown) => Promise<unknown> },+ ) => ({+ fileRestore: null,+ threadRollback: await hooks.commitThreadRollback(null),+ }),+ );+ isTurnRunningMock.mockReturnValue(false);+ recomputePrRefsForSessionMock.mockResolvedValue(undefined);+ detectCwdMock.mockResolvedValue({+ gitInstalled: false,+ isGitRepo: false,+ isInsideWorktree: false,+ });+ if (!commitRewindAtMessage) {+ ({ commitRewindAtMessage } = await import('../maker-orchestration/rewind'));+ }+});++afterEach(() => {+ clearCurrentDbClient(client);+ sqlite.close();+});++describe('Codex rewind native boundary SQL (#4994)', () => {+ it('does not borrow a native turn from history before /clear', async () => {+ insertSession({ clearedAt: 2500 });+ insertMessage({ id: 'old-user', role: 'user', createdAt: 1000 });+ insertMessage({+ id: 'old-asst',+ role: 'assistant',+ createdAt: 2000,+ agentMeta: oldAnchorMeta,+ });+ insertMessage({ id: 'target', role: 'user', createdAt: 3000 });++ await commitRewindAtMessage('sess-1', 'target');++ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', {+ tailTurnsToDrop: 1,+ rewindsToNativeThreadStart: true,+ });+ });++ it('keeps a hidden context_rebuild marker as the native-thread cutoff', async () => {+ insertSession();+ insertMessage({ id: 'old-user', role: 'user', createdAt: 1000 });+ insertMessage({+ id: 'old-asst',+ role: 'assistant',+ createdAt: 2000,+ agentMeta: oldAnchorMeta,+ });+ insertMessage({+ id: 'rebuild',+ role: 'context_rebuild',+ createdAt: 2500,+ rewindAt: 2501,+ content: JSON.stringify({ reason: 'context-overflow' }),+ });+ insertMessage({ id: 'target', role: 'user', createdAt: 3000 });++ await commitRewindAtMessage('sess-1', 'target');++ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', {+ tailTurnsToDrop: 1,+ rewindsToNativeThreadStart: true,+ });+ });++ it('refuses a target at or before /clear instead of treating it as the native thread start', async () => {+ insertSession({ clearedAt: 2500 });+ insertMessage({ id: 'old-user', role: 'user', createdAt: 1000 });+ insertMessage({+ id: 'old-asst',+ role: 'assistant',+ createdAt: 2000,+ agentMeta: oldAnchorMeta,+ });+ insertMessage({ id: 'post-clear', role: 'user', createdAt: 3000 });++ await expect(commitRewindAtMessage('sess-1', 'old-user')).rejects.toMatchObject({+ code: 'REWIND_UNSUPPORTED_HISTORY',+ });+ expect(commitRewindFilesMock).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex 9e3a4152af..98bfc3e395 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -1661,6 +1661,10 @@ function rewindCommit(readyDb, args) {const requireLatestUser = payload.requireLatestUser === true;const nativeForkAnchorSessionMap = normalizeNativeForkAnchorSessionMap(payload.nativeForkAnchorSessionMap);const now = expectNumber(payload.now, 'now');+ const expectedClearedAt =+ payload.expectedClearedAt === undefined || payload.expectedClearedAt === null+ ? null+ : expectNumber(payload.expectedClearedAt, 'expectedClearedAt');const rows = readyDb.prepare('SELECT id, client_id, role, created_at, agent_meta, tool_use_id FROM messages WHERE session_id = ? AND rewind_at IS NULL',).all(sessionId);@@ -1697,6 +1701,23 @@ function rewindCommit(readyDb, args) {: null;const updateAgentMeta = readyDb.prepare('UPDATE messages SET agent_meta = ? WHERE id = ?');readyDb.transaction(() => {+ const session = readyDb.prepare('SELECT cleared_at FROM sessions WHERE id = ?').get(sessionId);+ if (!session) {+ throw Object.assign(new Error('Session missing: ' + sessionId), { code: 'NOT_FOUND' });+ }+ const currentClearedAt = session.cleared_at ?? null;+ if ((currentClearedAt ?? -1) !== (expectedClearedAt ?? -1)) {+ throw Object.assign(+ new Error('CLEAR_GENERATION_CHANGED: clear-boundary changed for ' + sessionId),+ { code: 'PRECONDITION_FAILED' },+ );+ }+ if (currentClearedAt !== null && targetCreatedAt <= currentClearedAt) {+ throw Object.assign(+ new Error('CLEAR_GENERATION_CHANGED: target is at or before /clear for ' + sessionId),+ { code: 'PRECONDITION_FAILED' },+ );+ }for (const id of idsToRewind) updateMessage.run(now, id);// Mirror worker/opHandlers/tx.ts: surviving rows that still anchor the old// Codex thread are remapped to the replacement thread in the same transaction.diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex b775b439c0..46714050f1 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -1211,6 +1211,34 @@ describe('db worker tx handlers', () => {},);+ it.each([false, true])(+ 'rewind.commit refuses to mutate when the /clear generation has changed (inline=%s)',+ async (useInlineWorker) => {+ await withClient(async (client) => {+ await seedSession(client, 's1');+ await client.exec(+ 'INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?)',+ ['m1', 'c1', 's1', 'user', 'before', 100, 'm2', 'c2', 's1', 'user', 'after-clear', 400],+ );+ await client.exec('UPDATE sessions SET cleared_at = ? WHERE id = ?', [250, 's1']);++ await expect(+ client.tx('rewind.commit', {+ sessionId: 's1',+ targetCreatedAt: 100,+ expectedClearedAt: null,+ now: 999,+ }),+ ).rejects.toThrow(/CLEAR_GENERATION_CHANGED|clear-boundary changed/i);++ await expect(client.query('SELECT id, rewind_at FROM messages ORDER BY id')).resolves.toEqual([+ { id: 'm1', rewind_at: null },+ { id: 'm2', rewind_at: null },+ ]);+ }, { useInlineWorker });+ },+ );+it('rewind.commit uses target message id to avoid same-timestamp over-delete', async () => {await withClient(async (client) => {await seedSession(client, 's1');diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 0aa3f42091..cbf467df13 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -122,6 +122,11 @@ export interface RewindCommitArgs {* fork.session 的同名字段),否则后续回退/fork 会把这些锚点当异线程丢弃。*/nativeForkAnchorSessionMap?: Array<[string, string]>;+ /**+ * 读历史时看到的 sessions.cleared_at。提交时必须仍相同,否则 /clear 竞态整单回滚。+ * 省略或 null 表示当时会话未被清空。+ */+ expectedClearedAt?: number | null;now: number;}diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex be87643969..741046b508 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -2313,6 +2313,10 @@ function rewindCommit(db: Database.Database, args: unknown): void {payload.nativeForkAnchorSessionMap,);const now = expectNumber(payload.now, 'now');+ const expectedClearedAt =+ payload.expectedClearedAt === undefined || payload.expectedClearedAt === null+ ? null+ : expectNumber(payload.expectedClearedAt, 'expectedClearedAt');const rows = db.prepare(`SELECT id, client_id, role, created_at, agent_meta, tool_use_id@@ -2368,6 +2372,25 @@ function rewindCommit(db: Database.Database, args: unknown): void {: null;const updateAgentMeta = db.prepare('UPDATE messages SET agent_meta = ? WHERE id = ?');const transaction = db.transaction(() => {+ const session = db+ .prepare('SELECT cleared_at FROM sessions WHERE id = ?')+ .get(sessionId) as { cleared_at: number | null } | undefined;+ if (!session) {+ throw Object.assign(new Error(`Session missing: ${sessionId}`), { code: 'NOT_FOUND' });+ }+ const currentClearedAt = session.cleared_at ?? null;+ if ((currentClearedAt ?? -1) !== (expectedClearedAt ?? -1)) {+ throw Object.assign(+ new Error(`CLEAR_GENERATION_CHANGED: clear-boundary changed for ${sessionId}`),+ { code: 'PRECONDITION_FAILED' },+ );+ }+ if (currentClearedAt !== null && targetCreatedAt <= currentClearedAt) {+ throw Object.assign(+ new Error(`CLEAR_GENERATION_CHANGED: target is at or before /clear for ${sessionId}`),+ { code: 'PRECONDITION_FAILED' },+ );+ }for (const id of idsToRewind) updateMessage.run(now, id);// 保留下来的消息若持有旧 thread 的原生 turn 锚点,随 thread 替换一起重映射// (与 fork.session 复制消息时的处理一致),软删与重映射同一事务。diff --git a/apps/desktop/src/main/maker-orchestration/fork.ts b/apps/desktop/src/main/maker-orchestration/fork.tsindex 8dccf62159..7149970cdc 100644--- a/apps/desktop/src/main/maker-orchestration/fork.ts+++ b/apps/desktop/src/main/maker-orchestration/fork.ts@@ -538,8 +538,8 @@ export function resolveCodexTurnAnchor(for (let i = rows.length - 1; i >= 0; i -= 1) {const row = rows[i];if (row.role === 'context_rebuild') {- timelineSdkSessionId = null;- continue;+ // 重建之后是新的原生线程;不能从更早片段借 turn 锚点。+ return undefined;}if (row.role === 'agent_switch') {timelineSdkSessionId = parseAgentSwitchBoundary(row.content)?.fromSdkSessionId ?? null;@@ -573,6 +573,38 @@ export function resolveCodexForkEventTimestamp(rows: CodexNativeBoundaryRow[]):return undefined;}+/**+ * rows 之内是否没有属于 sourceSdkSessionId 原生线程的 user 行,即目标是该线程的第一轮。+ * 归属判定与 resolveCodexTurnAnchor 一致:agent_switch 之前的片段属于其 fromSdkSessionId+ * (切回停泊线程时仍是同一条线程);最近的 context_rebuild 截断更早历史,重建前的+ * agent_switch 不能把归属设回当前线程。+ * 不可解析或没有 fromSdkSessionId 的 switch 视为归属不定,返回 false,调用方不得标记+ * rewindsToNativeThreadStart(与「判定不出就明确失败」的 fail-closed 契约一致)。+ * rows 必须完整覆盖当前时间线(/clear 之后的可见行 + context_rebuild 标记);窗口被截断时+ * 调用方不得据此判定。+ */+export function isCodexNativeThreadStart(+ rows: CodexNativeBoundaryRow[],+ sourceSdkSessionId: string,+): boolean {+ let timelineSdkSessionId: string | null = sourceSdkSessionId;+ for (let i = rows.length - 1; i >= 0; i -= 1) {+ const row = rows[i]!;+ if (row.role === 'context_rebuild') {+ // 重建之后是新的原生线程;更早的 agent_switch 不能把归属设回当前线程。+ break;+ }+ if (row.role === 'agent_switch') {+ const owner = parseAgentSwitchBoundary(row.content)?.fromSdkSessionId;+ if (!owner) return false;+ timelineSdkSessionId = owner;+ continue;+ }+ if (row.role === 'user' && timelineSdkSessionId === sourceSdkSessionId) return false;+ }+ return true;+}+async function countCodexTailTurns(sourceSessionId: string,sourceCurrentSdkSessionId: string | null,diff --git a/apps/desktop/src/main/maker-orchestration/rewind.ts b/apps/desktop/src/main/maker-orchestration/rewind.tsindex 5dd7f31e36..de601f7928 100644--- a/apps/desktop/src/main/maker-orchestration/rewind.ts+++ b/apps/desktop/src/main/maker-orchestration/rewind.ts@@ -4,11 +4,12 @@* Stage 2 C2 重构后:SDK 调用全部走 maker-core 的 Session.previewRewindFiles /* commitRewindFiles。本文件只剩业务编排:* - Claude: 反向找 prior assistant uuid (跳 subagent / 跳 rewinded)- * - Codex: 计算 target 之后要裁掉的完整 user turn 数,交给 thread/rollback+ * - Codex: 计算 target 之后要裁掉的完整 user turn 数与原生 turn 边界,交给+ * maker-core(thread/rollback;不可用时按边界 fork,第一轮换空线程)* - SQLite 事务 (messages.rewind_at + sessions reset tokens + bump userSendAt)** Claude 三件套 (resume + resumeSessionAt + forkSession) 重启逻辑封装在- * ClaudeCodeAgent 内部。Codex 的 thread/rollback 会立即更新 app-server 上下文。+ * ClaudeCodeAgent 内部。Codex 的回退会立即更新 app-server 上下文。** 关键 uuid 拆解 (与重构前一致):* - resumeSessionAt 锚点 = **prior assistant uuid** (SDK 类型注释:@@ -18,7 +19,7 @@* user uuid 缺失 (老消息) → preview 走 Empty, commit 跳过文件回滚交* forkSession=true 兜底 (功能不残)。* - Codex 没有 message uuid / file checkpoint,preview 永远是 Empty,commit 用- * tailTurnsToDrop 调 thread/rollback。+ * tailTurnsToDrop + 原生边界交给 maker-core。*/import { and, asc, desc, eq, gt, gte, isNull, lt, or, sql } from 'drizzle-orm';@@ -34,7 +35,7 @@ import type { RewindFilesResult } from '@cindy/maker-core';import { createLogger } from '../logger';import { setLastAssistantTranscriptUuid } from '../messagePersistBroadcaster.js';import { recomputePrRefsForSession } from '../git-context/prRefsStore.js';-import { resolveCodexForkEventTimestamp, resolveCodexTurnAnchor } from './fork';+import { isCodexNativeThreadStart, resolveCodexForkEventTimestamp, resolveCodexTurnAnchor } from './fork';import {buildCodexFileRewindPlan,CodexFileRewindPlanError,@@ -586,23 +587,78 @@ async function loadCodexFileRewindRepoContext(makerSession: { workDir: string; r* commit 后立即发一条消息把 rewind 应用掉。后续可持久化到 sessions 表新列。*//**- * Codex 原地回退的原生边界(#4421):target 之前的时间线里,最近一个已完成 turn 的- * 持久化 nativeForkAnchor(lastTurnId);没有锚点(旧数据/上一轮失败)时退到最近一条- * 真实模型/工具输出的时间戳,由 maker-core 经 thread/turns/list 解析。两者都没有- * 就什么都不传——只有分页线程才会用到,普通线程仍走 thread/rollback。判定逻辑与- * fork 共用,原生 turn 计数含失败/重试轮次,不能拿可见 user 消息数去数。+ * Codex 回退的原生边界(#4421 / #4994):thread/rollback 不可用(分页线程,或 0.156.0 起+ * 运行时已移除该方法)时 maker-core 按它 fork。target 之前的时间线里,最近一个已完成+ * turn 的持久化 nativeForkAnchor(lastTurnId);没有锚点(旧数据/上一轮失败)时退到最近+ * 一条真实模型/工具输出的时间戳,由 maker-core 经 thread/turns/list 解析。两者都没有且+ * target 是当前原生线程的第一轮时标记 rewindsToNativeThreadStart,由 maker-core 换成空+ * 线程;否则什么都不传。判定逻辑与 fork 共用,原生 turn 计数含失败/重试轮次,不能拿+ * 可见 user 消息数去数。*/+async function readSessionClearedAt(sessionId: string): Promise<number | null> {+ const [sessionRow] = await getDbClient()+ .drizzle+ .select({ clearedAt: sessions.clearedAt })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ return sessionRow?.clearedAt ?? null;+}++async function rereadSessionClearedAt(sessionId: string): Promise<number | null> {+ // SDK 副作用前的代次复核必须独立于 rewind.test.ts 的 drizzle select 队列。+ const row = await getDbClient().queryOne<{ cleared_at: number | null }>(+ 'SELECT cleared_at FROM sessions WHERE id = ?',+ [sessionId],+ );+ return row?.cleared_at ?? null;+}++function assertTargetVisibleAfterClear(targetCreatedAt: number, clearedAt: number | null): void {+ if (clearedAt !== null && targetCreatedAt <= clearedAt) {+ throw rewindError(+ 'REWIND_UNSUPPORTED_HISTORY',+ '目标消息在 /clear 边界之前,当前引擎的会话历史无法回滚到那里',+ );+ }+}++async function assertClearGenerationUnchanged(+ sessionId: string,+ expectedClearedAt: number | null,+ targetCreatedAt: number,+): Promise<void> {+ const clearedAt = await rereadSessionClearedAt(sessionId);+ if ((clearedAt ?? -1) !== (expectedClearedAt ?? -1)) {+ throw rewindError(+ 'REWIND_UNSUPPORTED_HISTORY',+ '会话在回退判定后被 /clear,当前引擎的会话历史无法回滚到原目标',+ );+ }+ assertTargetVisibleAfterClear(targetCreatedAt, clearedAt);+}+async function loadCodexRewindNativeBoundary(sessionId: string,ctx: Pick<RewindContext, 'targetCreatedAt' | 'targetRowid'>,liveSdkSessionId: string | undefined,-): Promise<{ sdkSessionId?: string; lastTurnId?: string; forkAtTimestampMs?: number }> {+): Promise<{+ sdkSessionId?: string;+ lastTurnId?: string;+ forkAtTimestampMs?: number;+ rewindsToNativeThreadStart?: true;+ expectedClearedAt: number | null;+}> {const currentSessionMeta = await getMaker().getSessionMeta(sessionId);const sdkSessionId =activeSdkSessionId(liveSdkSessionId) ??activeSdkSessionId(currentSessionMeta?.sdkSessionId ?? undefined);- if (!sdkSessionId) return {};+ if (!sdkSessionId) return { expectedClearedAt: null };const db = getDbClient().drizzle;+ const clearedAt = await readSessionClearedAt(sessionId);+ // /clear 之后旧 target 已不在当前原生线程。空时间线不能当成第一轮,否则会换空+ // 线程并把 clear 之后的新消息一并软删(#4994 review P1)。+ assertTargetVisibleAfterClear(ctx.targetCreatedAt, clearedAt);const beforeTarget =ctx.targetRowid === undefined? lt(messages.createdAt, ctx.targetCreatedAt)@@ -610,6 +666,13 @@ async function loadCodexRewindNativeBoundary(lt(messages.createdAt, ctx.targetCreatedAt),and(eq(messages.createdAt, ctx.targetCreatedAt), lt(messageRowid, ctx.targetRowid)),);+ // /clear 与 context_rebuild 之后是新的原生线程,之前的行不能拿来当锚点或时间戳。+ // context_rebuild 的写入契约是 rewind_at 固定非 NULL,需豁免可见性过滤才能看到边界。+ const inTimeline = and(+ eq(messages.sessionId, sessionId),+ sql`${messages.createdAt} > ${clearedAt ?? -1}`,+ beforeTarget,+ );// 只需回看到上一条 user / 引擎切换边界;取最近 200 行足够覆盖一轮的工具输出。const recent = await db.select({@@ -619,14 +682,40 @@ async function loadCodexRewindNativeBoundary(createdAt: messages.createdAt,}).from(messages)- .where(and(eq(messages.sessionId, sessionId), isNull(messages.rewindAt), beforeTarget))+ .where(and(inTimeline, or(isNull(messages.rewindAt), eq(messages.role, 'context_rebuild')))).orderBy(desc(messages.createdAt), desc(messageRowid)).limit(200);const rows = [...recent].reverse();const lastTurnId = resolveCodexTurnAnchor(rows, sdkSessionId);- if (lastTurnId) return { sdkSessionId, lastTurnId };+ if (lastTurnId) return { sdkSessionId, lastTurnId, expectedClearedAt: clearedAt };const forkAtTimestampMs = resolveCodexForkEventTimestamp(rows);- return forkAtTimestampMs !== undefined ? { sdkSessionId, forkAtTimestampMs } : { sdkSessionId };+ if (forkAtTimestampMs !== undefined) return { sdkSessionId, forkAtTimestampMs, expectedClearedAt: clearedAt };+ // 第一轮判定要看完整时间线:切回停泊线程时,更早的片段仍属于当前线程。只取 user 与+ // 边界行,user 正文不参与判定,不读出来。+ const timeline = await db+ .select({+ role: messages.role,+ content: sql<string>`CASE WHEN ${messages.role} = 'agent_switch' THEN ${messages.content} ELSE '' END`,+ createdAt: messages.createdAt,+ })+ .from(messages)+ .where(+ and(+ inTimeline,+ or(+ and(eq(messages.role, 'user'), isNull(messages.rewindAt)),+ and(eq(messages.role, 'agent_switch'), isNull(messages.rewindAt)),+ eq(messages.role, 'context_rebuild'),+ ),+ ),+ )+ .orderBy(asc(messages.createdAt), asc(messageRowid));+ return isCodexNativeThreadStart(+ timeline.map((row) => ({ ...row, agentMeta: null })),+ sdkSessionId,+ )+ ? { sdkSessionId, rewindsToNativeThreadStart: true, expectedClearedAt: clearedAt }+ : { sdkSessionId, expectedClearedAt: clearedAt };}export async function commitRewindAtMessage(@@ -647,13 +736,23 @@ export async function commitRewindAtMessage(// pendingRewindTo, 下次 send 仍走三件套 (forkSession=true CLI 端兜底回滚)。let rewindResult: Awaited<ReturnType<typeof makerSession.commitRewindFiles>> | undefined;let nativeForkAnchorSessionMap: Array<[string, string]> | undefined;+ let expectedClearedAt: number | null = null;if (ctx.agentKind === 'codex' || ctx.agentKind === 'pi') {- // Codex 分页线程拒绝 thread/rollback(#4421):把 target 之前的原生 turn 边界- // (持久化锚点或事件时间戳)一并交给 maker-core,遇拒绝时改走 thread/fork。- const { sdkSessionId: previousSdkSessionId, ...nativeBoundary } =+ // thread/rollback 不可用(分页线程 #4421、0.156.0 起已移除 #4994):把 target 之前的+ // 原生 turn 边界(持久化锚点、事件时间戳或线程第一轮标记)一并交给 maker-core,+ // 由它改走 thread/fork 或换空线程。+ const {+ sdkSessionId: previousSdkSessionId,+ expectedClearedAt: codexExpectedClearedAt,+ ...nativeBoundary+ } =ctx.agentKind === 'codex'? await loadCodexRewindNativeBoundary(sessionId, ctx, makerSession.sdkSessionId)- : {};+ : { expectedClearedAt: await rereadSessionClearedAt(sessionId) };+ expectedClearedAt = codexExpectedClearedAt ?? null;+ // /clear 可能在读完时间线之后、SDK 换空线程之前落库。副作用前再核一次代次,+ // 最终 rewind.commit 事务再 CAS 同一值(#4994 review P1)。+ await assertClearGenerationUnchanged(sessionId, expectedClearedAt, ctx.targetCreatedAt);const commitThreadRollback = () =>makerSession.commitRewindFiles('', '', { tailTurnsToDrop: ctx.tailTurnsToDrop, ...nativeBoundary });const logCompensationError = (compErr: unknown, rollbackCommit: string | null) => {@@ -696,18 +795,22 @@ export async function commitRewindAtMessage() {nativeForkAnchorSessionMap = [[previousSdkSessionId, rewindResult.sdkSessionId]];}- } else if (ctx.userUuid && opts?.allowFileRestore !== false) {- rewindResult = await makerSession.commitRewindFiles(ctx.userUuid, ctx.assistantUuid!);} else {- log.info(- opts?.allowFileRestore === false- ? `[rewind commit] sid=${sessionId.slice(0, 8)} allowFileRestore=false — skip SDK rewindFiles`- : `[rewind commit] sid=${sessionId.slice(0, 8)} userUuid missing — skip SDK rewindFiles, only set pendingRewindTo via empty userUuid path`,- );- // 走一遍仅为了让 maker-core 设 pendingRewindTo. 它内部 rewindFiles('') 会 SDK 报错,- // 我们 catch 了 warn + 继续 (close + 设标记仍执行)。这与老链路 "userUuid 缺时跳过- // 文件回滚但保留三件套重启" 行为一致。- rewindResult = await makerSession.commitRewindFiles('', ctx.assistantUuid!);+ expectedClearedAt = await rereadSessionClearedAt(sessionId);+ await assertClearGenerationUnchanged(sessionId, expectedClearedAt, ctx.targetCreatedAt);+ if (ctx.userUuid && opts?.allowFileRestore !== false) {+ rewindResult = await makerSession.commitRewindFiles(ctx.userUuid, ctx.assistantUuid!);+ } else {+ log.info(+ opts?.allowFileRestore === false+ ? `[rewind commit] sid=${sessionId.slice(0, 8)} allowFileRestore=false — skip SDK rewindFiles`+ : `[rewind commit] sid=${sessionId.slice(0, 8)} userUuid missing — skip SDK rewindFiles, only set pendingRewindTo via empty userUuid path`,+ );+ // 走一遍仅为了让 maker-core 设 pendingRewindTo. 它内部 rewindFiles('') 会 SDK 报错,+ // 我们 catch 了 warn + 继续 (close + 设标记仍执行)。这与老链路 "userUuid 缺时跳过+ // 文件回滚但保留三件套重启" 行为一致。+ rewindResult = await makerSession.commitRewindFiles('', ctx.assistantUuid!);+ }}// ── 段 2:SQLite 事务(软删消息 + 同步写回 replacement sdk_session_id)──@@ -728,6 +831,7 @@ export async function commitRewindAtMessage(preserveMessageUuid: ctx.preserveMessageUuid,sdkSessionId: rewindResult?.sdkSessionId,now,+ expectedClearedAt,...(opts?.requireLatestUser ? { requireLatestUser: true } : {}),...(nativeForkAnchorSessionMap ? { nativeForkAnchorSessionMap } : {}),});@@ -737,6 +841,15 @@ export async function commitRewindAtMessage(} catch (err) {// 原子守卫命中:软删未发生(并发落库的新消息被保住)。必须向上抛而不能// 沿用"warn + 继续"——继续会让编辑链路误以为 rewind 成功并触发重发。+ if (err instanceof Error && err.message.includes('CLEAR_GENERATION_CHANGED')) {+ log.error(+ `[rewind commit] sid=${sessionId.slice(0, 8)} /clear 代次在软删临界区内已变——事务未执行(文件回滚可能已发生)`,+ );+ throw rewindError(+ 'REWIND_UNSUPPORTED_HISTORY',+ '会话在回退判定后被 /clear,当前引擎的会话历史无法回滚到原目标',+ );+ }if (err instanceof Error && err.message.includes('REWIND_TARGET_NOT_LATEST')) {log.error(`[rewind commit] sid=${sessionId.slice(0, 8)} target 在软删临界区内被新 user 消息超越——事务未执行(文件回滚可能已发生)`,diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex b3599bc39b..ec9c67a180 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -133,9 +133,23 @@ vitest run src/agents/codex/app-server/external-auth.native.test.ts`,覆盖分关闭任务时也清理这些实例里的同 thread 保活状态;不能只查共享代理而漏掉实际承载连接。分支优先使用已保存的原生 turn 锚点。Codex 0.153.4 起,旧消息或失败轮没有锚点时,先用 `thread/turns/list(itemsView: notLoaded)` 查询终态边界,再 `thread/fork(lastTurnId)`,-不能对分页线程执行 rollback。界面软删重试不代表原生 turn 消失,有复制事件时间时据此+不能对分页线程执行 rollback;0.156.0 起运行时已移除 `thread/rollback`,编辑重发与回退+一律走同一边界 fork。界面软删重试不代表原生 turn 消失,有复制事件时间时据此定位,不按可见 user 行数猜边界;复制事件时间缺失、原生时间缺失或秒级精度无法确定顺序时明确失败,不截错-历史。查询与 fork 使用同一隔离控制面 host,关闭其写入进程后才发布子线程身份。+历史。回退目标是当前原生线程的第一轮时(目标之前没有属于该线程的 user 行:首条消息,或+`/clear`、上下文重建、切换引擎新开线程后的第一轮)没有可 fork 的边界,由宿主标记+`rewindsToNativeThreadStart`,Codex 按当前配置换一条空线程;归属沿用锚点的 agent_switch+链,切回停泊线程时更早的片段仍算当前线程,判定不出就明确失败,不能把「找不到边界」+当成第一轮。不可解析或没有 `fromSdkSessionId` 的 `agent_switch` 视为归属不定,同样+不得标记 `rewindsToNativeThreadStart`。最近的 `context_rebuild` 截断更早历史,不能让+重建前的 `agent_switch` 把归属设回当前线程。`targetCreatedAt <= sessions.clearedAt` 必须拒绝,+不能把 `/clear` 之前的目标当成当前线程第一轮。`INPUT_CLEAR_SESSION` 不进+`withSendToSessionLock`,因此判定时读到的 `clearedAt` 必须作为 `expectedClearedAt`+传入 `rewind.commit`,并在 SDK 换空线程之前再核一次;代次已变则整单失败,不得软删+`/clear` 之后的新消息。实现见 Desktop `maker-orchestration/rewind.ts` 与 maker-core+`agents/codex/index.ts` 的 `commitRewindFiles`,回归见 `rewind.test.ts`、`fork.test.ts`、+`rewindNativeBoundarySqlite.test.ts`、`tx.test.ts` 与 `index.test.ts`。+查询与 fork 使用同一隔离控制面 host,关闭其写入进程后才发布子线程身份。HTTP 回退遇到缺失 `Content-Type` 的成功响应时,只允许从明文 SSE 前缀(可带注释心跳)确认事件流并补齐响应头;显式非 SSE 类型、HTML/JSON、空响应与只有心跳的正文不能放行。正在运行的 turn、SSH 远端缺少本地交接能力、或已有恢复动作在途时必须 fail closed,不能diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 35bc51606f..9772d87d57 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -24969,6 +24969,220 @@ describe('CodexAgent rewind', () => {expect(isCodexRollbackUnavailableError(new Error('unknown variant `thread/fork`'))).toBe(false);});+ // #4994 follow-up:首条消息(或 /clear、重建、切换后的第一轮)之前没有 turn 可作 fork 边界。+ // 宿主确认是线程第一轮时换一条按当前配置新开的空线程,而不是报「无可用边界」。+ const freshThreadStartImpl = () => {+ let threadStarts = 0;+ return (method: string) => {+ if (method !== Method.ThreadStart) return undefined;+ threadStarts += 1;+ if (threadStarts === 1) return undefined;+ return { thread: { id: 'fresh-thread-id' }, model: 'gpt-5.4', modelProvider: 'openai', cwd: '/repo' };+ };+ };++ it('replaces the thread with a fresh one when rewinding to the native thread start on Codex 0.156.0 (#4994)', async () => {+ const agent = new CodexAgent(createDeps());+ const startImpl = freshThreadStartImpl();+ const host = installFakeHost(agent, (method) => {+ if (method === Method.ThreadRollback) {+ throw Object.assign(new Error(ROLLBACK_REMOVED_ERROR_TEXT), { code: -32600 });+ }+ return startImpl(method);+ }, { userAgent: 'mock-codex/0.156.0' });+ const handle = await agent.startSession({+ sessionId: 'session-rewind-thread-start',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const iterator = handle.events()[Symbol.asyncIterator]();+ const commitRewindFiles = handle.commitRewindFiles;+ if (!commitRewindFiles) throw new Error('expected commitRewindFiles');++ await expect(commitRewindFiles('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true }))+ .resolves.toEqual({ sdkSessionId: 'fresh-thread-id' });++ const methods = host.request.mock.calls.map(([method]) => method);+ expect(methods).not.toContain(Method.ThreadRollback);+ expect(methods).not.toContain(Method.ThreadFork);+ expect(methods).not.toContain(Method.ThreadTurnsList);+ expect(methods.filter((method) => method === Method.ThreadStart)).toHaveLength(2);+ expect(host.request).toHaveBeenLastCalledWith(Method.ThreadStart, expect.objectContaining({ cwd: '/repo' }));+ expect(host.subscribeThread).toHaveBeenLastCalledWith('fresh-thread-id', expect.any(Object));+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'session_id',+ data: 'fresh-thread-id',+ source: 'codex',+ });+ await handle.close();+ });++ it('holds MCP discovery identity around the fresh rewind thread/start (#4994)', async () => {+ const order: string[] = [];+ const deps = createDeps();+ deps.withCodexMcpDiscoveryContext = async (ctx, run) => {+ expect(ctx).toMatchObject({ sessionId: 'bot-parent', sessionInstanceId: 'bot-instance' });+ order.push('discovery');+ try { return await run(); } finally { order.push('released'); }+ };+ const agent = new CodexAgent(deps);+ const startImpl = freshThreadStartImpl();+ const host = installFakeHost(agent, (method) => {+ if (method === Method.ThreadRollback) {+ throw Object.assign(new Error(ROLLBACK_REMOVED_ERROR_TEXT), { code: -32600 });+ }+ return startImpl(method);+ }, { userAgent: 'mock-codex/0.156.0' });+ const original = host.request.getMockImplementation()!;+ host.request.mockImplementation(async (...args) => {+ if (args[0] === Method.ThreadStart) {+ expect(order.at(-1)).toBe('discovery');+ order.push('native');+ }+ return original(...args);+ });+ const handle = await agent.startSession({+ sessionId: 'bot-parent',+ sessionInstanceId: 'bot-instance',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ expect(order).toEqual(['discovery', 'native', 'released']);+ order.length = 0;+ const commitRewindFiles = handle.commitRewindFiles;+ if (!commitRewindFiles) throw new Error('expected commitRewindFiles');++ await expect(commitRewindFiles('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true }))+ .resolves.toEqual({ sdkSessionId: 'fresh-thread-id' });+ expect(order).toEqual(['discovery', 'native', 'released']);+ await handle.close();+ });++ it('does not reuse the previous thread rollout after a pathless first-turn replacement (#4994)', async () => {+ const codexHome = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-rewind-rollout-'));+ tempRoots.push(codexHome);+ const sessionsDir = path.join(codexHome, 'sessions', '2026', '09', '24');+ await fs.mkdir(sessionsDir, { recursive: true });+ const oldRollout = path.join(sessionsDir, 'rollout-2026-09-24T00-00-00-start-thread-id.jsonl');+ await fs.writeFile(oldRollout, `${JSON.stringify({ payload: { type: 'event_msg', message: 'old thread' } })}\n`);++ const agent = new CodexAgent(createDeps());+ (agent as unknown as { codexHome: string }).codexHome = codexHome;+ const startImpl = freshThreadStartImpl();+ installFakeHost(agent, (method) => {+ if (method === Method.ThreadStart) {+ const started = startImpl(method) as { thread: { id: string; path?: string } } | undefined;+ if (!started) {+ return { thread: { id: 'start-thread-id', path: oldRollout }, model: 'gpt-5.4', modelProvider: 'openai', cwd: '/repo' };+ }+ return started;+ }+ if (method === Method.ThreadRollback) {+ throw Object.assign(new Error(ROLLBACK_REMOVED_ERROR_TEXT), { code: -32600 });+ }+ return startImpl(method);+ }, { userAgent: 'mock-codex/0.156.0', codexHome });+ const handle = await agent.startSession({+ sessionId: 'session-rewind-clear-rollout',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const commitRewindFiles = handle.commitRewindFiles;+ if (!commitRewindFiles) throw new Error('expected commitRewindFiles');+ await expect(commitRewindFiles('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true }))+ .resolves.toEqual({ sdkSessionId: 'fresh-thread-id' });++ await expect(+ (agent as unknown as { findRolloutPath: (threadId: string, preferredPath?: string, homeOverride?: string) => Promise<string> })+ .findRolloutPath('fresh-thread-id', oldRollout, codexHome),+ ).rejects.toThrow('Codex rollout not found for thread fresh-thread-id');+ await handle.close();+ });++ it('replaces the thread when a paginated thread rejects rollback at the native thread start (#4421 / #4994)', async () => {+ const agent = new CodexAgent(createDeps());+ const startImpl = freshThreadStartImpl();+ const host = installFakeHost(agent, (method) => {+ if (method === Method.ThreadRollback) {+ throw Object.assign(new Error('paginated threads do not support thread/rollback'), { code: -32600 });+ }+ return startImpl(method);+ }, { userAgent: 'mock-codex/0.153.4' });+ const handle = await agent.startSession({+ sessionId: 'session-rewind-thread-start-paginated',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const commitRewindFiles = handle.commitRewindFiles;+ if (!commitRewindFiles) throw new Error('expected commitRewindFiles');++ await expect(commitRewindFiles('', '', { tailTurnsToDrop: 2, rewindsToNativeThreadStart: true }))+ .resolves.toEqual({ sdkSessionId: 'fresh-thread-id' });+ expect(host.request).toHaveBeenCalledWith(Method.ThreadRollback, { threadId: 'start-thread-id', numTurns: 2 });+ expect(host.request).not.toHaveBeenCalledWith(Method.ThreadFork, expect.anything());+ expect(host.subscribeThread).toHaveBeenLastCalledWith('fresh-thread-id', expect.any(Object));+ await handle.close();+ });++ it('keeps thread/rollback for the native thread start while the daemon still supports it (#4994)', async () => {+ const agent = new CodexAgent(createDeps());+ const startImpl = freshThreadStartImpl();+ const host = installFakeHost(agent, startImpl, { userAgent: 'mock-codex/0.153.4' });+ const handle = await agent.startSession({+ sessionId: 'session-rewind-thread-start-legacy',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const commitRewindFiles = handle.commitRewindFiles;+ if (!commitRewindFiles) throw new Error('expected commitRewindFiles');++ await expect(commitRewindFiles('', '', { tailTurnsToDrop: 1, rewindsToNativeThreadStart: true }))+ .resolves.toEqual({ sdkSessionId: 'rollback-thread-id' });+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadStart)).toHaveLength(1);+ await handle.close();+ });++ it('prefers a native boundary over the thread-start marker (#4994)', async () => {+ const agent = new CodexAgent(createDeps());+ const startImpl = freshThreadStartImpl();+ const host = installFakeHost(agent, startImpl, { userAgent: 'mock-codex/0.156.0' });+ const handle = await agent.startSession({+ sessionId: 'session-rewind-thread-start-with-anchor',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const commitRewindFiles = handle.commitRewindFiles;+ if (!commitRewindFiles) throw new Error('expected commitRewindFiles');++ await expect(commitRewindFiles('', '', {+ tailTurnsToDrop: 1,+ lastTurnId: 'persisted-boundary',+ rewindsToNativeThreadStart: true,+ })).resolves.toEqual({ sdkSessionId: 'fork-thread-id' });+ expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, expect.objectContaining({ lastTurnId: 'persisted-boundary' }));+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadStart)).toHaveLength(1);+ await handle.close();+ });++ it('never drops history without the thread-start marker when no boundary is known (#4994)', async () => {+ const agent = new CodexAgent(createDeps());+ const startImpl = freshThreadStartImpl();+ const host = installFakeHost(agent, startImpl, { userAgent: 'mock-codex/0.156.0' });+ const handle = await agent.startSession({+ sessionId: 'session-rewind-no-boundary',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const commitRewindFiles = handle.commitRewindFiles;+ if (!commitRewindFiles) throw new Error('expected commitRewindFiles');++ await expect(commitRewindFiles('', '', { tailTurnsToDrop: 1 }))+ .rejects.toThrow('Codex fork requires an unambiguous native anchor or event timestamp');+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadStart)).toHaveLength(1);+ expect(host.request).not.toHaveBeenCalledWith(Method.ThreadFork, expect.anything());+ await handle.close();+ });+it('re-registers proxy developer instructions for the replacement rollback thread', async () => {const registerCodexSystemPromptForThread = vi.fn();const agent = new CodexAgent(createDeps(diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex b8ee2699f5..25491a1f15 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -6514,7 +6514,13 @@ export class CodexAgent extends BaseAgent {let threadId!: string;let sessionRolloutPath: string | undefined;const recordNativeThreadLocation = async (thread: { id: string; [key: string]: unknown }): Promise<void> => {- if (typeof thread.path !== 'string') return;+ if (typeof thread.path !== 'string') {+ // thread/start on a brand-new thread often has no rollout yet. Drop the+ // previous thread's path so later findRolloutPath / plan fallback cannot+ // tail the replaced history (#4994).+ sessionRolloutPath = undefined;+ return;+ }sessionRolloutPath = thread.path;if (opts.remoteHostId || !sessionCodexHome) return;await this.deps.recordCodexThreadLocation?.(thread.id, sessionSqliteHome ?? sessionCodexHome, thread.path);@@ -6879,7 +6885,7 @@ export class CodexAgent extends BaseAgent {const resp = await requestProfileLifecycle<ThreadStartResponse>({action: 'replacement',signal,- request: () => host.request<ThreadStartResponse>(retainHistory ? Method.ThreadFork : Method.ThreadStart, {+ request: () => withMcpDiscoveryContext(() => host.request<ThreadStartResponse>(retainHistory ? Method.ThreadFork : Method.ThreadStart, {...(retainHistory ? { threadId: previousThreadId, excludeTurns: true } : {}),cwd: opts.workingDir,// Recovery belongs to the running send, whose catalog/window is already frozen.@@ -6889,7 +6895,7 @@ export class CodexAgent extends BaseAgent {...(mutableModel && mutableModel !== 'gpt-5' ? { model: mutableModel } : {}),...(mutableServiceTier !== undefined ? { serviceTier: mutableServiceTier } : {}),...(developerInstructions && !useProxyChannel ? { developerInstructions } : {}),- }),+ })),onLateResolve: async (lateResp) => {const lateThreadId = lateResp.thread.id;if (lateThreadId === previousThreadId) return;@@ -14158,6 +14164,29 @@ export class CodexAgent extends BaseAgent {const unavailableReason = rollbackUnavailableReason ?? 'thread/rollback unavailable';const rollbackMethodRemoved = unavailableReason.includes('unknown method')|| unavailableReason.includes('removed in Codex');+ if (+ rewindOpts?.rewindsToNativeThreadStart === true+ && !normalizeNativeForkTurnId(rewindOpts.lastTurnId)+ && rewindOpts.forkAtTimestampMs === undefined+ ) {+ // 目标是当前原生线程的第一轮(宿主按消息时间线确认):前面没有 turn 可作+ // fork 边界,裁掉全部 turn 等价于一条空线程。按当前配置新开线程并切过去,+ // 旧线程与 fork 路径一样保留不动(#4994)。+ log.info('commitRewindFiles ▶ rewinding to native thread start; replacing with a fresh thread', {+ threadId,+ tailTurnsToDrop,+ reason: unavailableReason,+ });+ await replaceThreadWithCurrentProfile();+ currentTurnId = null;+ isTurnInFlight = false;+ log.info('commitRewindFiles ◀ fresh thread replaced rewound thread', {+ previousThreadId,+ threadId,+ tailTurnsToDrop,+ });+ return sdkSessionId ? { sdkSessionId } : {};+ }if (!rollbackMethodRemoved && !supportsCodexNativeTurnFork(initResp.userAgent)) {throw new Error(`Codex app-server ${initResp.userAgent ?? 'unknown'}: ${unavailableReason} and predates native turn fork (0.145.0); rewind is unavailable for this thread`,@@ -14291,12 +14320,15 @@ export class CodexAgent extends BaseAgent {private async findRolloutPath(threadId: string, preferredPath?: string, homeOverride?: string): Promise<string> {if (preferredPath && !isRemoteLikePath(preferredPath)) {- try {- const stat = await fs.stat(preferredPath);- if (stat.isFile()) return preferredPath;- } catch {- // Fall through to the normal CODEX_HOME scan when preparation only- // returned a stale state-db pointer.+ const preferredName = path.basename(preferredPath);+ if (preferredName.startsWith('rollout-') && preferredName.endsWith(`${threadId}.jsonl`)) {+ try {+ const stat = await fs.stat(preferredPath);+ if (stat.isFile()) return preferredPath;+ } catch {+ // Fall through to the normal CODEX_HOME scan when preparation only+ // returned a stale state-db pointer.+ }}}const codexHome = homeOverride ?? this.codexHome;diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.tsindex 5ff2cbdf03..7cbf676ff5 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts@@ -944,6 +944,10 @@ describe('PI durable subagent run store', () => {const foreignLivePid = process.ppid;/** A pid that is certainly not running: 2^22 is above every OS pid_max. */const deadPid = 4_194_303;+ /** These cases pin ownership, not stale detection. A default `updatedAt: 20`+ * is already expired, so the sync identity probe (Windows: powershell, 5s)+ * would starve the 5s test budget. */+ const live = (): { updatedAt: number } => ({ updatedAt: Date.now() });async function homeWithRuns(): Promise<{ agentHome: string; root: string }> {const agentHome = await makeRoot();@@ -957,9 +961,11 @@ describe('PI durable subagent run store', () => {const foreign = '123e4567-e89b-42d3-a456-426614174061';await writeStatus(root, status(mine, {runtimeOwnerId: piSubagentRuntimeOwnerId(process.pid, 'scope-mine'),+ ...live(),}));await writeStatus(root, status(foreign, {runtimeOwnerId: piSubagentRuntimeOwnerId(foreignLivePid, 'scope-foreign'),+ ...live(),}));// Times out because our own run never goes terminal; what matters is who@@ -978,6 +984,7 @@ describe('PI durable subagent run store', () => {const orphan = '123e4567-e89b-42d3-a456-426614174062';await writeStatus(root, status(orphan, {runtimeOwnerId: piSubagentRuntimeOwnerId(deadPid, 'scope-crashed'),+ ...live(),}));await expect(stopAllPiSubagentRunsForExit(agentHome, 150, { hostPid: process.pid }))@@ -990,7 +997,7 @@ describe('PI durable subagent run store', () => {it('fails closed on a legacy owner id that carries no host prefix', async () => {const { agentHome, root } = await homeWithRuns();const legacy = '123e4567-e89b-42d3-a456-426614174063';- await writeStatus(root, status(legacy, { runtimeOwnerId: 'owner-a' }));+ await writeStatus(root, status(legacy, { runtimeOwnerId: 'owner-a', ...live() }));await expect(stopAllPiSubagentRunsForExit(agentHome, 150, { hostPid: process.pid })).resolves.toBe(false);@@ -1005,6 +1012,7 @@ describe('PI durable subagent run store', () => {const foreign = '123e4567-e89b-42d3-a456-426614174065';await writeStatus(root, status(foreign, {runtimeOwnerId: piSubagentRuntimeOwnerId(foreignLivePid, 'scope-foreign'),+ ...live(),}));// Only the foreign run exists: this host has nothing to stop and must not@@ -1016,6 +1024,7 @@ describe('PI durable subagent run store', () => {await writeStatus(root, status(mine, {runtimeOwnerId: piSubagentRuntimeOwnerId(process.pid, 'scope-mine'),+ ...live(),}));expect(hasActivePiSubagentRunsSync(agentHome, { hostPid: process.pid })).toBe(true);expect(requestStopAllPiSubagentRunsSync(agentHome, { hostPid: process.pid })).toBe(1);diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.tsindex 9d00ddf6e5..a89cb395cc 100644--- a/packages/maker-core/src/types/events.ts+++ b/packages/maker-core/src/types/events.ts@@ -468,9 +468,9 @@ export interface RewindCommitOptions {*/tailTurnsToDrop?: number;/**- * Codex 分页线程拒绝 thread/rollback(-32600 "paginated threads do not support- * thread/rollback")时的原生边界:回退目标之前最后一个已完成 turn 的原生- * turn id(持久化的 nativeForkAnchor)。有它就直接 thread/fork(lastTurnId)。+ * Codex thread/rollback 不可用(分页线程拒绝,或 0.156.0 起运行时已移除该方法)+ * 时的原生边界:回退目标之前最后一个已完成 turn 的原生 turn id(持久化的+ * nativeForkAnchor)。有它就直接 thread/fork(lastTurnId)。*/lastTurnId?: string;/**@@ -479,6 +479,13 @@ export interface RewindCommitOptions {* 的 forkAtTimestampMs 语义一致。*/forkAtTimestampMs?: number;+ /**+ * 宿主确认回退目标是当前原生线程的第一轮:目标之前没有属于该线程的 user 行+ * (首条消息,或 /clear、上下文重建、切换引擎新开线程后的第一轮)。此时没有可作+ * fork 边界的 turn,rollback 不可用时 Codex 改为按当前配置新开一条空线程替换。+ * 只在没有 lastTurnId / forkAtTimestampMs 时生效。+ */+ rewindsToNativeThreadStart?: boolean;}export interface RewindCommitResult {