Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(codex): recover unpersisted threads when switching models (#4754)

Chris Zhangafef92916fbf
diff --git a/apps/desktop/src/main/maker-host/__tests__/codex-thread-locations.test.ts b/apps/desktop/src/main/maker-host/__tests__/codex-thread-locations.test.ts
index 0353a1d86d..ee69c147cc 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codex-thread-locations.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codex-thread-locations.test.ts
@@ -23,10 +23,10 @@ describe('native thread locations across accounts', () => {
await fs.mkdir(path.dirname(rollout), { recursive: true });
await fs.writeFile(rollout, 'history');
await locations.record('thread-a', rollout);
- expect(await locations.readStorage('thread-a')).toEqual({ historyHome: home, sqliteHome: home });
+ expect(await locations.readStorage('thread-a')).toEqual({ historyHome: home, sqliteHome: home, rolloutPath: rollout });
await locations.record('thread-a', rollout, home);
const reopened = new CodexThreadLocations(path.join(root, 'owner', 'locations'));
- expect(await reopened.readStorage('thread-a')).toEqual({ historyHome: home, sqliteHome: home });
+ expect(await reopened.readStorage('thread-a')).toEqual({ historyHome: home, sqliteHome: home, rolloutPath: rollout });
expect(await reopened.readStorage('unknown')).toBeUndefined();
expect(await fs.readFile(rollout, 'utf8')).toBe('history');
});
@@ -37,16 +37,55 @@ describe('native thread locations across accounts', () => {
await fs.mkdir(path.dirname(rollout), { recursive: true });
await fs.writeFile(rollout, 'old native history\n');
const prepare = vi.fn().mockResolvedValue(rollout);
- expect(await locations.readStorage('old-thread', { home, prepare })).toEqual({ historyHome: home, sqliteHome: home });
+ expect(await locations.readStorage('old-thread', { home, prepare })).toEqual({ historyHome: home, sqliteHome: home, rolloutPath: rollout });
expect(prepare).toHaveBeenCalledWith('old-thread');
expect(await locations.read('old-thread')).toBe(rollout);
- expect(await locations.readStorage('old-thread', { home, prepare })).toEqual({ historyHome: home, sqliteHome: home });
+ expect(await locations.readStorage('old-thread', { home, prepare })).toEqual({ historyHome: home, sqliteHome: home, rolloutPath: rollout });
expect(prepare).toHaveBeenCalledTimes(1);
expect(await fs.readFile(rollout, 'utf8')).toBe('old native history\n');
await fs.rm(rollout);
- await expect(locations.readStorage('old-thread', { home, prepare })).rejects.toThrow();
+ expect(await locations.readStorage('old-thread', { home, prepare })).toEqual({ historyHome: home, sqliteHome: home, rolloutPath: rollout });
+ await expect(locations.read('old-thread')).rejects.toThrow();
expect(prepare).toHaveBeenCalledTimes(1);
});
+ it('keeps an unmaterialized thread in its original homes across repeated model switches', async () => {
+ const { root, locations } = await fixture();
+ const historyHome = path.join(root, 'original-history');
+ const sqliteHome = path.join(root, 'original-state');
+ const rollout = path.join(historyHome, 'sessions', 'future.jsonl');
+ await locations.record('unused-thread', rollout, sqliteHome);
+ const prepare = vi.fn(async () => path.join(root, 'older-copy.jsonl'));
+ const before = await fs.readFile(path.join(root, 'owner', 'locations', 'unused-thread.json'), 'utf8');
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const reopened = new CodexThreadLocations(path.join(root, 'owner', 'locations'));
+ expect(await reopened.readStorage('unused-thread', { home: root, prepare })).toEqual({
+ historyHome, sqliteHome, rolloutPath: rollout,
+ });
+ expect(await reopened.prepareResume('unused-thread', prepare)).toBeUndefined();
+ }
+ expect(prepare).not.toHaveBeenCalled();
+ expect(await fs.readFile(path.join(root, 'owner', 'locations', 'unused-thread.json'), 'utf8')).toBe(before);
+ await fs.mkdir(path.dirname(rollout), { recursive: true });
+ await fs.writeFile(rollout, 'native history');
+ expect(await locations.prepareResume('unused-thread', prepare)).toBe(rollout);
+ expect(await fs.readFile(rollout, 'utf8')).toBe('native history');
+ });
+
+ it('does not treat invalid or unreadable history as an unused thread', async () => {
+ const { root, locations } = await fixture();
+ const rollout = path.join(root, 'sessions', 'rollout.jsonl');
+ const prepare = vi.fn(async () => undefined);
+ await locations.record('thread', rollout);
+ await fs.mkdir(rollout, { recursive: true });
+ await expect(locations.prepareResume('thread', prepare)).rejects.toThrow('history is unavailable');
+ const denied = Object.assign(new Error('access denied'), { code: 'EACCES' });
+ const stat = vi.spyOn(fs, 'lstat').mockRejectedValueOnce(denied);
+ try {
+ await expect(locations.prepareResume('thread', prepare)).rejects.toBe(denied);
+ } finally { stat.mockRestore(); }
+ expect(prepare).not.toHaveBeenCalled();
+ });
+
it('does not invent a storage home when legacy preparation finds no history', async () => {
const { root, locations } = await fixture();
const prepare = vi.fn().mockResolvedValue(undefined);
@@ -72,7 +111,7 @@ describe('native thread locations across accounts', () => {
await fs.mkdir(path.dirname(rollout), { recursive: true });
await fs.writeFile(rollout, JSON.stringify({ type: 'session_meta', payload: { id: 'archived' } }));
await locations.record('archived', rollout, sqliteHome);
- expect(await locations.readStorage('archived')).toEqual({ historyHome, sqliteHome });
+ expect(await locations.readStorage('archived')).toEqual({ historyHome, sqliteHome, rolloutPath: rollout });
});
it('never falls back to an older rollout after the canonical path disappears', async () => {
const { root, locations } = await fixture();
diff --git a/apps/desktop/src/main/maker-host/codex-thread-locations.ts b/apps/desktop/src/main/maker-host/codex-thread-locations.ts
index c3e4e85691..478bacf677 100644
--- a/apps/desktop/src/main/maker-host/codex-thread-locations.ts
+++ b/apps/desktop/src/main/maker-host/codex-thread-locations.ts
@@ -2,6 +2,12 @@ import fs from 'node:fs/promises';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
+interface ThreadLocation {
+ threadId: string;
+ path: string;
+ sqliteHome?: string;
+}
+
/** A native thread has one durable rollout, regardless of the account resuming it. */
export class CodexThreadLocations {
constructor(private readonly directory: string) {}
@@ -11,7 +17,7 @@ export class CodexThreadLocations {
return path.join(this.directory, `${threadId}.json`);
}
- async read(threadId: string): Promise<string | undefined> {
+ private async readLocation(threadId: string): Promise<ThreadLocation | undefined> {
let raw: string;
try {
raw = await fs.readFile(this.file(threadId), 'utf8');
@@ -23,37 +29,66 @@ export class CodexThreadLocations {
if (
value.threadId !== threadId ||
typeof value.path !== 'string' ||
- !path.isAbsolute(value.path)
+ !path.isAbsolute(value.path) ||
+ (value.sqliteHome !== undefined &&
+ (typeof value.sqliteHome !== 'string' || !path.isAbsolute(value.sqliteHome)))
) {
throw new Error('Invalid Codex thread location');
}
- // A missing canonical file must not silently select an older copy.
- const stat = await fs.lstat(value.path);
- if (!stat.isFile()) throw new Error('Codex thread history is unavailable');
+ return value;
+ }
+
+ private async rolloutExists(rollout: string): Promise<boolean> {
+ try {
+ const stat = await fs.lstat(rollout);
+ if (!stat.isFile()) throw new Error('Codex thread history is unavailable');
+ return true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
+ throw error;
+ }
+ }
+
+ async read(threadId: string): Promise<string | undefined> {
+ const value = await this.readLocation(threadId);
+ if (!value) return;
+ if (!await this.rolloutExists(value.path)) throw new Error('Codex thread history is unavailable');
return value.path;
}
+ /** Missing indexed paths are resolved by native resume in their original home.
+ * Never search legacy homes or silently substitute an older rollout for them. */
+ async prepareResume(
+ threadId: string,
+ prepareLegacy: (threadId: string) => Promise<string | undefined>,
+ ): Promise<string | undefined> {
+ const value = await this.readLocation(threadId);
+ if (!value) return prepareLegacy(threadId);
+ return await this.rolloutExists(value.path) ? value.path : undefined;
+ }
+
async readStorage(
threadId: string,
legacy?: { home: string; prepare: (threadId: string) => Promise<string | undefined> },
- ): Promise<{ historyHome: string; sqliteHome: string } | undefined> {
- const rollout = await this.read(threadId);
- if (!rollout) {
+ ): Promise<{ historyHome: string; sqliteHome: string; rolloutPath?: string } | undefined> {
+ const value = await this.readLocation(threadId);
+ if (!value) {
// Pre-multi-account threads have no location record. Resolve their native
// storage before an account-specific host starts, without moving history.
const legacyRollout = await legacy?.prepare(threadId);
if (!legacy || !legacyRollout) return;
await this.record(threadId, legacyRollout, legacy.home);
- return { historyHome: historyHomeForRollout(legacyRollout), sqliteHome: legacy.home };
- }
- const value = JSON.parse(await fs.readFile(this.file(threadId), 'utf8'));
- if (value.sqliteHome !== undefined) {
- if (typeof value.sqliteHome !== 'string' || !path.isAbsolute(value.sqliteHome)) throw new Error('Invalid Codex history storage');
- return { historyHome: historyHomeForRollout(rollout), sqliteHome: value.sqliteHome };
+ return { historyHome: historyHomeForRollout(legacyRollout), sqliteHome: legacy.home, rolloutPath: legacyRollout };
}
- // Compatibility with locations written before native database ownership was recorded.
- const historyHome = historyHomeForRollout(rollout);
- return { historyHome, sqliteHome: historyHome };
+ const historyHome = historyHomeForRollout(value.path);
+ // thread/start returns a future path before the first turn materializes it.
+ // Keep storage ownership even then, so native resume can distinguish an unused
+ // thread from unreadable history without looking in the newly selected account.
+ return {
+ historyHome,
+ sqliteHome: value.sqliteHome ?? historyHome,
+ rolloutPath: value.path,
+ };
}
async record(threadId: string, rolloutPath: string, sqliteHome?: string): Promise<void> {
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index f17a84e2db..c7a8f8fd75 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -1931,7 +1931,7 @@ export function getMaker(): Maker {
prepareCodexResumeSession: async (threadId) => {
if (!getActiveAppSession().dataOwnerId) return prepareExternalCodexSessionForResume(threadId);
const locations = new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations'));
- return await locations.read(threadId) ?? await prepareExternalCodexSessionForResume(threadId);
+ return locations.prepareResume(threadId, prepareExternalCodexSessionForResume);
},
resolveCodexThreadStorage: async (threadId) => {
if (!getActiveAppSession().dataOwnerId) return;
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 82607ae9da..c4e5e5a105 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -378,6 +378,14 @@ Session 任务遵守同一套机制与呈现契约:
- Bot 表全部只增量;旧代码打开含 Bot 表的库时按既有 migration compatibility 守卫失败关闭,
不得强行降级。
+Codex 切模型重建时,线程索引里的路径不等于文件已经落盘。缺文件时仍保留原历史根与
+数据库根,先用原生 `thread/read` 核实有无已存线程,再走 `thread/resume`;只有原生明确
+没有线程元数据且无法找到 rollout,才在同一伙伴主任务内重建未开始的线程。
+原生 `no rollout` 错误本身不能证明线程未开始:已有历史文件丢失时也会返回它。
+已有线程元数据、读取异常或迟到落盘不得触发空白重建;不得换用旧副本,也不得重放已接受的输入。
+实现见 `codex-thread-locations.ts` 与 Codex adapter;原生契约回归见
+`packages/maker-core/src/agents/codex/app-server/external-auth.native.test.ts`。
+
## 8. 验收最低集
- 单模型旧 Profile 可无损读成一项链;新 Profile 可保存并恢复 1–5 项顺序。
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 573b99ed6f..41b2a83ba3 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -1297,7 +1297,7 @@ export interface AgentDeps {
*/
prepareCodexResumeSession?: (threadId: string, context?: { codexHome: string; providerId?: string }) => Promise<string | void>;
recordCodexThreadLocation?: (threadId: string, codexHome: string, rolloutPath?: string) => Promise<void>;
- resolveCodexThreadStorage?: (threadId: string) => Promise<{ historyHome: string; sqliteHome: string } | undefined>;
+ resolveCodexThreadStorage?: (threadId: string) => Promise<{ historyHome: string; sqliteHome: string; rolloutPath?: string } | undefined>;
/** Freeze the owner/account scope before async host startup; never expose tokens to the renderer. */
createCodexAuthTokenReader?: (providerId?: string) => () => Promise<import('./codex/app-server/external-auth.js').CodexChatgptTokens>;
diff --git a/packages/maker-core/src/agents/codex/app-server/external-auth.native.test.ts b/packages/maker-core/src/agents/codex/app-server/external-auth.native.test.ts
index 385b7b32f2..f1f525bc20 100644
--- a/packages/maker-core/src/agents/codex/app-server/external-auth.native.test.ts
+++ b/packages/maker-core/src/agents/codex/app-server/external-auth.native.test.ts
@@ -158,6 +158,52 @@ describe.skipIf(!binaryPath)('real Codex history/account isolation contract', ()
await f.assertOriginals();
}, 60_000);
+ it('classifies an unmaterialized thread after closing its original host', async () => {
+ const f = await fixture();
+ const original = f.host(f.historyHome);
+ const started = await original.request<{ thread: { id: string; path: string } }>('thread/start', {
+ cwd: f.root, model: 'gpt-6-astra', approvalPolicy: 'never', sandbox: 'read-only',
+ }, { timeoutMs: 15_000 });
+ expect(started.thread.path).toBeTruthy();
+ await expect(fs.lstat(started.thread.path)).rejects.toMatchObject({ code: 'ENOENT' });
+ await original.retire();
+ const replacement = f.host(f.historyHome);
+ await expect(replacement.request('thread/read', { threadId: started.thread.id, includeTurns: false })).rejects.toMatchObject({
+ code: -32600, data: undefined,
+ message: `codex app-server thread/read error -32600: thread not loaded: ${started.thread.id}`,
+ });
+ await expect(replacement.request('thread/resume', {
+ threadId: started.thread.id, cwd: f.root, model: 'gpt-6-astra',
+ }, { timeoutMs: 15_000 })).rejects.toMatchObject({
+ code: -32600,
+ message: `codex app-server thread/resume error -32600: no rollout found for thread id ${started.thread.id}`,
+ data: undefined,
+ });
+ await f.assertOriginals();
+ }, 30_000);
+
+ it('retains metadata for a lost persisted rollout despite the same no-rollout resume error', async () => {
+ const f = await fixture();
+ const original = f.host(f.historyHome);
+ await f.resume(original);
+ await original.retire();
+ const canonical = await fs.realpath(f.child.file);
+ await fs.rename(f.child.file, `${f.child.file}.preserved`);
+ const replacement = f.host(f.historyHome);
+ await expect(replacement.request('thread/read', { threadId: f.child.id, includeTurns: false })).resolves.toMatchObject({
+ thread: { id: f.child.id, path: canonical },
+ });
+ try {
+ await expect(replacement.request('thread/resume', {
+ threadId: f.child.id, cwd: f.root, model: 'gpt-6-astra',
+ }, { timeoutMs: 15_000 })).rejects.toMatchObject({
+ message: `codex app-server thread/resume error -32600: no rollout found for thread id ${f.child.id}`,
+ });
+ } finally {
+ await fs.rename(`${f.child.file}.preserved`, f.child.file);
+ }
+ }, 30_000);
+
it('keeps native forks in the original history domain', async () => {
const f = await fixture();
const host = f.host(f.historyHome, 'account-b');
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 8442284fc1..b455f81ef4 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -23498,6 +23498,150 @@ describe('CodexAgent resume preparation', () => {
await handle.close();
});
+ it('recovers repeated model switches before the first turn without replacing the teammate identity', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-unused-switch-'));
+ const recorded = new Map<string, string>();
+ const agent = new CodexAgent(createDeps({}, {
+ resolveCodexThreadStorage: async id => ({ historyHome: root, sqliteHome: root, rolloutPath: recorded.get(id) }),
+ prepareCodexResumeSession: async () => undefined,
+ recordCodexThreadLocation: async (id, _home, rollout) => { if (rollout) recorded.set(id, rollout); },
+ }));
+ let seq = 0;
+ const host = installFakeHost(agent, (method, params) => {
+ if (method === 'thread/read') throw Object.assign(new Error(
+ `codex app-server thread/read error -32600: thread not loaded: ${(params as { threadId: string }).threadId}`,
+ ), { code: -32600, data: undefined });
+ if (method === Method.TurnStart) return { turn: { id: 'first-user-turn' } };
+ if (method === Method.ThreadResume) throw exactNoRolloutError((params as { threadId: string }).threadId);
+ if (method === Method.ThreadStart) {
+ const id = `123e4567-e89b-12d3-a456-${String(++seq).padStart(12, '0')}`;
+ return { thread: { id, path: path.join(root, 'sessions', `${id}.jsonl`) }, model: (params as { model: string }).model };
+ }
+ return undefined;
+ }, { codexHome: root, userAgent: 'mock-codex/0.153.4', localCompactionProviderId: 'cindy_summary' });
+ let handle: AgentSessionHandle | undefined;
+ try {
+ for (const model of ['gpt-5.6-sol', 'gpt-5.6-luna', 'gpt-6-astra']) {
+ const previous = handle?.id;
+ await handle?.close();
+ handle = await agent.startSession({ sessionId: 'same-canonical-teammate', resumeSessionId: previous,
+ model, workingDir: root, botProfilePrompt: 'STABLE TEAMMATE SOUL', botRuntimeProfile: {
+ botId: 'same-bot', profileVersion: 1,
+ skillPolicy: { mode: 'allowlist', configured: [], catalog: [] },
+ mcpPolicy: { mode: 'allowlist', configured: [], catalog: [] },
+ toolsetPolicy: { mode: 'allowlist', configured: [], catalog: [] },
+ } });
+ }
+ expect(recorded.size).toBe(3);
+ const starts = host.request.mock.calls.filter(([method]) => method === Method.ThreadStart);
+ expect(starts.map(([, params]) => (params as { model: string }).model)).toEqual(['gpt-5.6-sol', 'gpt-5.6-luna', 'gpt-6-astra']);
+ for (const [, params] of starts) expect(params).toMatchObject({ cwd: root, developerInstructions: expect.stringContaining('STABLE TEAMMATE SOUL') });
+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadResume)).toHaveLength(2);
+ // Verify missing native metadata in the original home before each resume fallback.
+ expect(host.request.mock.calls.filter(([method]) => method === 'thread/read')).toHaveLength(2);
+ expect(host.request.mock.calls.filter(([method]) => method === Method.TurnStart)).toHaveLength(0);
+ await handle!.send({ type: 'user', content: 'First user message' }, { throwOnStartFailure: true });
+ expect(host.request.mock.calls.filter(([method]) => method === Method.TurnStart)).toHaveLength(1);
+ expect(host.request.mock.calls.find(([method]) => method === Method.TurnStart)?.[1]).toMatchObject({ threadId: handle!.id, model: 'gpt-6-astra' });
+ } finally {
+ await handle?.close();
+ await agent.dispose();
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it('recovers an unindexed unused thread when the summary metadata lookup reports it unloaded', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, method => {
+ if (method === 'thread/read') throw Object.assign(new Error(
+ `codex app-server thread/read error -32600: thread not loaded: ${resumeSessionId}`,
+ ), { code: -32600, data: undefined });
+ if (method === Method.ThreadResume) throw exactNoRolloutError();
+ return undefined;
+ }, { localCompactionProviderId: 'cindy_summary' });
+ const handle = await agent.startSession({ sessionId: 'unindexed-unused', resumeSessionId,
+ model: 'gpt-6-astra', workingDir: '/repo' });
+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadStart)).toHaveLength(1);
+ await handle.close();
+ await agent.dispose();
+ });
+
+ it('resumes a still-loaded indexed thread without a file or losing its summary provider', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-loaded-index-'));
+ const rolloutPath = path.join(root, 'sessions', 'future.jsonl');
+ const agent = new CodexAgent(createDeps({}, {
+ resolveCodexThreadStorage: async () => ({ historyHome: root, sqliteHome: root, rolloutPath }),
+ prepareCodexResumeSession: async () => undefined,
+ }));
+ const thread = { id: resumeSessionId, path: rolloutPath, modelProvider: 'cindy_summary' };
+ const host = installFakeHost(agent, (method, params) => {
+ if (method === 'thread/read') return { thread };
+ if (method === Method.ThreadResume) return { thread, modelProvider: (params as { modelProvider: string }).modelProvider };
+ return undefined;
+ }, { codexHome: root, localCompactionProviderId: 'cindy_summary' });
+ try {
+ const handle = await agent.startSession({ sessionId: 'loaded-canonical', resumeSessionId, model: 'gpt-6-astra', workingDir: root });
+ expect(handle.id).toBe(resumeSessionId);
+ expect(host.request.mock.calls.find(([method]) => method === Method.ThreadResume)?.[1]).toMatchObject({ modelProvider: 'cindy_summary' });
+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadStart)).toHaveLength(0);
+ await handle.close();
+ } finally {
+ await agent.dispose();
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it('keeps missing indexed history out of the fork path', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-missing-fork-'));
+ const agent = new CodexAgent(createDeps({}, {
+ resolveCodexThreadStorage: async () => ({ historyHome: root, sqliteHome: root,
+ rolloutPath: path.join(root, 'sessions', 'missing.jsonl') }),
+ prepareCodexResumeSession: async () => undefined,
+ }));
+ const host = installFakeHost(agent);
+ try {
+ await expect(agent.forkSdkSession({ sourceSdkSessionId: resumeSessionId, workingDir: root })).rejects.toThrow();
+ expect(host.getHost).not.toHaveBeenCalled();
+ expect(host.request).not.toHaveBeenCalled();
+ } finally {
+ await agent.dispose();
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it.each(['native-history', 'read-timeout', 'unreadable', 'older-copy', 'late-file'] as const)('does not discard indexed history on %s', async failure => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-indexed-recovery-'));
+ const rolloutPath = path.join(root, 'sessions', 'canonical.jsonl');
+ const agent = new CodexAgent(createDeps({}, {
+ resolveCodexThreadStorage: async () => ({ historyHome: root, sqliteHome: root, rolloutPath }),
+ prepareCodexResumeSession: async () => undefined,
+ }));
+ const host = installFakeHost(agent, async method => {
+ if (method === 'thread/read') {
+ if (failure === 'native-history') return { thread: { id: resumeSessionId, path: rolloutPath } };
+ if (failure === 'read-timeout') throw new Error('metadata read timed out');
+ throw Object.assign(new Error(`codex app-server thread/read error -32600: thread not loaded: ${resumeSessionId}`), { code: -32600, data: undefined });
+ }
+ if (method !== Method.ThreadResume) return undefined;
+ if (failure === 'older-copy') return { thread: { id: resumeSessionId, path: path.join(root, 'older.jsonl') } };
+ if (failure === 'native-history') throw exactNoRolloutError();
+ if (failure === 'unreadable') throw new Error('failed to read existing rollout');
+ await fs.mkdir(path.dirname(rolloutPath), { recursive: true });
+ await fs.writeFile(rolloutPath, 'late native history');
+ throw exactNoRolloutError();
+ }, { codexHome: root });
+ try {
+ await expect(agent.startSession({ sessionId: 'preserve-canonical', resumeSessionId,
+ model: 'gpt-6-astra', workingDir: root })).rejects.toThrow();
+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadStart)).toHaveLength(0);
+ expect(host.request.mock.calls.filter(([method]) => method === Method.TurnStart)).toHaveLength(0);
+ if (failure === 'late-file') expect(await fs.readFile(rolloutPath, 'utf8')).toBe('late native history');
+ } finally {
+ await agent.dispose();
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+
it('does not call thread/resume when the host identifies an unsafe rollout', async () => {
const prepareCodexResumeSession = vi.fn(async () => {
throw new CodexResumePreparationBlockedError('rollout may still have a live writer');
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 5ab1714582..873693e108 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -1115,18 +1115,25 @@ function isExpectedTurnIdMismatchError(error: unknown): boolean {
}
/**
- * Only the app-server's canonical missing-rollout response permits replacing
- * a thread. Keep this fail-closed: a wrapped message, a different JSON-RPC
- * code, or populated error data may describe a different resume failure.
+ * Match the app-server's canonical missing-rollout response. This alone does
+ * not prove a thread was unused; indexed history also needs a metadata check.
+ * Wrapped messages, other JSON-RPC codes, or populated data are not equivalent.
*/
export function isExactNoRolloutThreadResumeError(error: unknown, threadId: string): boolean {
+ return isExactThreadLookupError(error,
+ `codex app-server thread/resume error -32600: no rollout found for thread id ${threadId}`);
+}
+
+function isExactUnloadedThreadReadError(error: unknown, threadId: string): boolean {
+ return isExactThreadLookupError(error,
+ `codex app-server thread/read error -32600: thread not loaded: ${threadId}`);
+}
+
+function isExactThreadLookupError(error: unknown, message: string): boolean {
if (typeof error !== 'object' || error === null) return false;
const candidate = error as { code?: unknown; data?: unknown; message?: unknown };
- if (candidate.code !== -32600 || !Object.hasOwn(error, 'data') || candidate.data !== undefined) {
- return false;
- }
- return candidate.message ===
- `codex app-server thread/resume error -32600: no rollout found for thread id ${threadId}`;
+ return candidate.code === -32600 && Object.hasOwn(error, 'data') && candidate.data === undefined
+ && candidate.message === message;
}
// 插话 (steer) 时 turn/steer RPC 的 ack 有界等待上限。AppServerClient.request
@@ -6282,7 +6289,7 @@ export class CodexAgent extends BaseAgent {
? await this.deps.prepareCodexResumeSession(opts.resumeSessionId, { codexHome: sessionCodexHome, providerId: accountProviderId })
: await this.deps.prepareCodexResumeSession(opts.resumeSessionId);
} catch (e) {
- if (accountSessionHost || e instanceof CodexResumePreparationBlockedError) {
+ if (accountSessionHost || sessionStorage?.rolloutPath || e instanceof CodexResumePreparationBlockedError) {
releaseHostBindingLeaseIfNeeded();
throw e;
}
@@ -6292,12 +6299,39 @@ export class CodexAgent extends BaseAgent {
});
}
}
+ // Native resume reports "no rollout" for both unused threads and deleted
+ // history. Metadata survives a missing file, so check the original native
+ // index before permitting the existing unused-thread fallback.
+ const indexedRolloutMissing = !!sessionStorage?.rolloutPath && !preparedResumePath;
+ let indexedThreadAbsent = false;
+ let indexedModelProvider: string | undefined;
+ if (indexedRolloutMissing && opts.resumeSessionId) {
+ try {
+ const { thread } = await host.request<{ thread: { id: string; path?: string; modelProvider?: string } }>(
+ 'thread/read', { threadId: opts.resumeSessionId, includeTurns: false }, {
+ timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS,
+ },
+ );
+ if (thread.id !== opts.resumeSessionId) {
+ throw new CodexResumePreparationBlockedError('Codex native metadata does not match indexed history');
+ }
+ indexedModelProvider = thread.modelProvider;
+ } catch (error) {
+ if (!isExactUnloadedThreadReadError(error, opts.resumeSessionId)) {
+ releaseHostBindingLeaseIfNeeded();
+ throw error;
+ }
+ indexedThreadAbsent = true;
+ }
+ }
const localSummaryProvider = opts.remoteHostId ? null : host.getLocalCompactionProviderId?.();
if (localSummaryProvider && opts.resumeSessionId && isLikelyValidThreadId(opts.resumeSessionId)) {
// Native modelProvider is durable thread metadata. Read it before overriding
// resume defaults so recovery survives closing/reopening this same task.
try {
- const savedProvider = preparedResumePath
+ const savedProvider = indexedRolloutMissing
+ ? indexedModelProvider
+ : preparedResumePath
? await readCodexRolloutModelProvider(preparedResumePath, opts.resumeSessionId)
: (await host.request<{ thread: { modelProvider?: string } }>(
'thread/read', { threadId: opts.resumeSessionId, includeTurns: false },
@@ -6307,7 +6341,7 @@ export class CodexAgent extends BaseAgent {
} catch (error) {
// Let the existing resume path recover an unused thread without a rollout.
// Other read failures must not silently reset a saved summary identity.
- if (preparedResumePath || !isExactNoRolloutThreadResumeError(error, opts.resumeSessionId)) {
+ if (preparedResumePath || !isExactUnloadedThreadReadError(error, opts.resumeSessionId)) {
releaseHostBindingLeaseIfNeeded();
throw error;
}
@@ -6575,7 +6609,20 @@ export class CodexAgent extends BaseAgent {
// 我们能拿到的最佳目录线索(与下方 wire 规范化不同,后者不更新它)。
mutableCatalogModel = resp.model;
}
- if (preparedResumePath && resp.thread.id !== opts.resumeSessionId) throw new Error('Codex resumed an unexpected thread');
+ if ((preparedResumePath || sessionStorage?.rolloutPath) && resp.thread.id !== opts.resumeSessionId) {
+ throw new Error('Codex resumed an unexpected thread');
+ }
+ // A missing indexed path is not permission to select an older copy by ID.
+ // If it materialized during startup, only that same canonical file may resume.
+ if (indexedRolloutMissing && sessionStorage?.rolloutPath) {
+ if (typeof resp.thread.path !== 'string') throw new Error('Codex resumed without a history location');
+ if (path.resolve(resp.thread.path) !== path.resolve(sessionStorage.rolloutPath)) {
+ const [actual, expected] = await Promise.all([
+ fs.realpath(resp.thread.path), fs.realpath(sessionStorage.rolloutPath),
+ ]);
+ if (actual !== expected) throw new Error('Codex resumed an unexpected history location');
+ }
+ }
threadId = resp.thread.id;
await recordNativeThreadLocation(resp.thread);
codexThreadModelProviderId = resp.modelProvider?.trim() || undefined;
@@ -6625,12 +6672,22 @@ export class CodexAgent extends BaseAgent {
});
} catch (e) {
let freshThreadStarted = false;
- if (!preparedResumePath && isExactNoRolloutThreadResumeError(e, opts.resumeSessionId)) {
- // Codex gives an exact, provider-owned proof that this thread has
- // never crossed a turn boundary. Only this error may switch the
- // continuation from resume to a fresh thread/start.
+ if (!preparedResumePath && (!indexedRolloutMissing || indexedThreadAbsent)
+ && isExactNoRolloutThreadResumeError(e, opts.resumeSessionId)) {
+ // For indexed threads, both native metadata and rollout must be absent.
+ // A no-rollout error alone also occurs after persisted history is lost.
log.info('thread/resume reported no rollout; starting a fresh thread');
try {
+ if (sessionStorage?.rolloutPath) {
+ const materialized = await fs.lstat(sessionStorage.rolloutPath).then(
+ () => true,
+ (error: NodeJS.ErrnoException) => {
+ if (error.code === 'ENOENT') return false;
+ throw error;
+ },
+ );
+ if (materialized) throw new CodexResumePreparationBlockedError('Codex history materialized during resume');
+ }
await startFreshThread();
freshThreadStarted = true;
} catch (freshStartError) {
@@ -14274,6 +14331,11 @@ export class CodexAgent extends BaseAgent {
note: 'Codex 精确 fork: 独立一次性 host 上 thread/fork 后按需 thread/rollback 新 thread 尾部 turn',
});
try {
+ const forkStorage = await this.deps.resolveCodexThreadStorage?.(opts.sourceSdkSessionId);
+ // Fork requires actual history; it must never use resume's unused-thread recovery.
+ if (forkStorage?.rolloutPath && !(await fs.lstat(forkStorage.rolloutPath)).isFile()) {
+ throw new CodexResumePreparationBlockedError('Codex fork history is unavailable');
+ }
// Source history inspection must not depend on the credentials we are leaving.
let preparedSourcePath = opts.stripEncryptedReasoning
? await this.deps.prepareCodexResumeSession?.(opts.sourceSdkSessionId)
@@ -14285,7 +14347,6 @@ export class CodexAgent extends BaseAgent {
}
// ID-only turn queries must use the source thread's index even when the
// account supplying credentials has changed. Keep the child in that index.
- const forkStorage = await this.deps.resolveCodexThreadStorage?.(opts.sourceSdkSessionId);
const forkSqliteHome = forkStorage?.sqliteHome;
stage = 'host-create';
const leased = await this.acquireHostOperation(async () => {