Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): restore imported paginated histories and ancestor chains
DavidShen75c0478e4d8a
diff --git a/apps/desktop/src/main/__tests__/codexLocalSessions.native.test.ts b/apps/desktop/src/main/__tests__/codexLocalSessions.native.test.tsnew file mode 100644index 0000000000..deb3d08cbc--- /dev/null+++ b/apps/desktop/src/main/__tests__/codexLocalSessions.native.test.ts@@ -0,0 +1,163 @@+/**+ * #7436 native contract: production adoption/index repair -> real thread/resume+ * -> turn/start with imported history. Unit fixtures cannot enforce Codex's+ * filename/ordinal contract. Opt-in runtime tier, isolated homes + loopback model:+ * CINDY_CODEX_TEST_BINARY=<bundled binary> vitest run <this file>.+ * Separate from unit tests because this starts real processes and a local server.+ * Windows 0.159.2: 7.94s including collection, 4.61s for all five native cases.+ */+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { randomUUID } from 'node:crypto';+import { createServer } from 'node:http';+import Database from 'better-sqlite3';+import { expect, it, vi } from 'vitest';+import { AppServerHost } from '../../../../../packages/maker-core/src/agents/codex/app-server/host';+import { createStdioTransport } from '../../../../../packages/maker-core/src/agents/codex/app-server/stdioTransport';+import type { Logger } from '../../../../../packages/maker-core/src/interfaces/logger';+import { prepareExternalCodexSessionForResume, prepareCodexRolloutForResume } from '../maker-host/codex-local-sessions';+import { CodexThreadLocations } from '../maker-host/codex-thread-locations';++const fixture = vi.hoisted(() => ({ userData: '' }));+vi.mock('electron', () => ({ app: { getPath: () => fixture.userData } }));+vi.mock('../logger.js', () => ({ createLogger: () => ({ debug() {}, info() {}, warn() {} }) }));++const binary = process.env.CINDY_CODEX_TEST_BINARY;+const logger: Logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child: () => logger };++it.skipIf(!binary).each(['import', 'indexed', 'indexed-reverted', 'lineage', 'indexed-lineage'] as const)(+ 'resumes paginated history and completes the next native turn: %s', async mode => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-paginated-native-'));+ fixture.userData = path.join(root, 'cindy');+ const targetHome = path.join(fixture.userData, 'codex-home');+ const sourceHome = path.join(root, 'source');+ const hosts: AppServerHost[] = [];+ const oldHome = process.env.CODEX_HOME;+ const oldAppData = process.env.APPDATA;+ process.env.CODEX_HOME = sourceHome;+ process.env.APPDATA = path.join(root, 'appdata');+ const homedir = vi.spyOn(os, 'homedir').mockReturnValue(root);+ const requests: string[] = [];+ const server = createServer(async (req, res) => {+ if (req.method !== 'POST') { res.end('{"models":[]}'); return; }+ let body = ''; for await (const chunk of req) body += chunk;+ requests.push(body);+ res.writeHead(200, { 'content-type': 'text/event-stream' });+ res.end(`data: ${JSON.stringify({ type: 'response.completed', response: {+ id: 'resp_fixture', object: 'response', status: 'completed', model: 'gpt-5.4', output: [],+ usage: { input_tokens: 10, output_tokens: 1, total_tokens: 11 },+ } })}\n\n`);+ });+ try {+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ const baseUrl = `http://127.0.0.1:${(server.address() as { port: number }).port}`;+ function host(home: string) {+ fs.mkdirSync(home, { recursive: true });+ const instance = new AppServerHost({ logger, clientInfo: { name: 'cindy-import-test', version: '1' },+ createTransport: () => createStdioTransport({ binaryPath: binary!, cwd: root,+ env: { PATH: process.env.PATH ?? '', HOME: root, USERPROFILE: root, CODEX_HOME: home,+ ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}) },+ extraArgs: ['--disable', 'plugins', '--disable', 'remote_plugin',+ '-c', 'cli_auth_credentials_store="ephemeral"', '-c', 'model_provider="probe"',+ '-c', 'model_providers.probe.name="Probe"', '-c', `model_providers.probe.base_url=${JSON.stringify(baseUrl)}`,+ '-c', 'model_providers.probe.wire_api="responses"', '-c', 'model_providers.probe.requires_openai_auth=false',+ '-c', 'model_providers.probe.supports_websockets=false',+ '-c', 'model_providers.probe.request_max_retries=0', '-c', 'model_providers.probe.stream_max_retries=0'],+ }),+ });+ hosts.push(instance);+ return instance;+ }+ const id = randomUUID();+ const hasLineage = mode.includes('lineage');+ const ancestors: Array<{ file: string; contents: string; marker: string }> = [];+ let base: { thread_id: string; end_ordinal_exclusive: number; end_byte_offset: number } | undefined;+ // Two generations, including an archived independent rollout ID and an+ // earlier page of this same thread. Root-only fixtures missed #7436 lineage.+ if (hasLineage) {+ for (const archived of [false, true]) {+ const parentThread = archived ? randomUUID() : id;+ const rolloutId = archived ? randomUUID() : parentThread;+ const parentName = `rollout-2026-10-13T10-13-41-${parentThread}${archived ? `_${rolloutId}` : ''}.jsonl`;+ const file = path.join(sourceHome, archived ? 'archived_sessions' : 'sessions', '2026', '10', '13', parentName);+ const parentMarker = `ancestor-history-${rolloutId}`;+ const ordinal = base?.end_ordinal_exclusive ?? 0;+ const contents = [+ { ordinal, type: 'session_meta', payload: { id: parentThread, timestamp: '2026-10-13T10:13:41Z', cwd: root,+ originator: 'cindy-import-test', cli_version: '0.159.2', source: 'cli', history_mode: 'paginated',+ model_provider: 'probe', ...(base ? { history_base: base } : {}) } },+ { ordinal: ordinal + 1, type: 'response_item', payload: { type: 'message', role: 'user',+ content: [{ type: 'input_text', text: parentMarker }] } },+ ].map(item => JSON.stringify({ timestamp: '2026-10-13T10:13:41Z', ...item })).join('\n') + '\n';+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, contents);+ ancestors.push({ file, contents, marker: parentMarker });+ base = { thread_id: rolloutId, end_ordinal_exclusive: ordinal + 2, end_byte_offset: Buffer.byteLength(contents) };+ }+ }+ const filename = `rollout-2026-10-14T10-13-41-${id}${mode === 'indexed-reverted' || hasLineage ? `_${randomUUID()}` : ''}.jsonl`;+ const sourcePath = path.join(sourceHome, 'sessions', '2026', '10', '14', filename);+ fs.mkdirSync(path.dirname(sourcePath), { recursive: true });+ const marker = `imported-history-${id}`;+ fs.writeFileSync(sourcePath, [+ { ordinal: base?.end_ordinal_exclusive ?? 0, type: 'session_meta', payload: { id, timestamp: '2026-10-14T10:13:41Z', cwd: root,+ originator: 'cindy-import-test', cli_version: '0.159.2', source: 'cli', history_mode: 'paginated', model_provider: 'probe',+ ...(base ? { history_base: base } : {}) } },+ { ordinal: (base?.end_ordinal_exclusive ?? 0) + 1, type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: marker }] } },+ ].map(item => JSON.stringify({ timestamp: '2026-10-14T10:13:41Z', ...item })).join('\n') + '\n');+ const resume = { threadId: id, cwd: root, model: 'gpt-5.4', modelProvider: 'probe', approvalPolicy: 'never', sandbox: 'read-only' };+ const sourceHost = host(sourceHome);+ await sourceHost.request('thread/resume', { ...resume, path: sourcePath });+ await sourceHost.retire('source fixture complete');+ const original = fs.readFileSync(sourcePath, 'utf8');+ const target = host(targetHome);+ await target.ensureStarted();+ // Initialize the native schema without sending a model request.+ await target.request('thread/start', { cwd: root, model: 'gpt-5.4', modelProvider: 'probe', ephemeral: true });+ let prepared = await prepareExternalCodexSessionForResume(id);+ expect(path.basename(prepared!)).toBe(filename);+ if (mode.startsWith('indexed')) {+ // Simulate an already-imported child from the old version, without ancestors.+ for (const ancestor of ancestors) fs.rmSync(path.join(targetHome, path.relative(sourceHome, ancestor.file)), { force: true });+ // Windows' old extended-path fallback flattened the selected file here.+ const broken = path.join(targetHome, 'sessions', `rollout-cindy-adopted-3-${filename}`);+ // Recreate an old release's sole selected path and index.+ fs.renameSync(prepared!, broken);+ expect(fs.existsSync(prepared!)).toBe(false);+ const dbName = fs.readdirSync(targetHome).filter(name => /^state_\d+\.sqlite$/.test(name)).sort().at(-1)!;+ const db = new Database(path.join(targetHome, dbName));+ try { db.prepare('UPDATE threads SET rollout_path = ? WHERE id = ?').run(broken, id); }+ finally { db.close(); }+ const locations = new CodexThreadLocations(path.join(root, 'locations'), prepareCodexRolloutForResume);+ await locations.record(id, broken, targetHome);+ await expect(target.request('thread/resume', { ...resume, path: broken })).rejects.toThrow('canonical rollout filename');+ const storage = await locations.readStorage(id, { home: targetHome, prepare: prepareExternalCodexSessionForResume });+ prepared = storage!.rolloutPath;+ expect(await locations.prepareResume(id, prepareExternalCodexSessionForResume)).toBe(prepared);+ }+ const result = await target.request<{ thread: { id: string } }>('thread/resume', { ...resume, path: prepared });+ expect(result.thread.id).toBe(id);+ const completed = new Promise<string>(resolve => {+ target.subscribeThread(id, { turnCompleted: event => resolve(event.turn.status) });+ });+ await target.request('turn/start', { threadId: id, input: [{ type: 'text', text: 'Continue the imported task.' }] });+ expect(await completed).toBe('completed');+ expect(requests.some(body => body.includes(marker))).toBe(true);+ for (const ancestor of ancestors) {+ expect(requests.some(body => body.includes(ancestor.marker))).toBe(true);+ expect(fs.readFileSync(ancestor.file, 'utf8')).toBe(ancestor.contents);+ expect(fs.readFileSync(path.join(targetHome, path.relative(sourceHome, ancestor.file)), 'utf8')).toBe(ancestor.contents);+ }+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe(original);+ expect(fs.readFileSync(prepared!, 'utf8')).toContain('Continue the imported task.');+ } finally {+ await Promise.all(hosts.map(instance => instance.retire('native import test finished')));+ await new Promise<void>(resolve => { server.closeAllConnections(); server.close(() => resolve()); });+ homedir.mockRestore();+ if (oldHome === undefined) delete process.env.CODEX_HOME; else process.env.CODEX_HOME = oldHome;+ if (oldAppData === undefined) delete process.env.APPDATA; else process.env.APPDATA = oldAppData;+ fs.rmSync(root, { recursive: true, force: true });+ }+ }, 45_000,+);diff --git a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts b/apps/desktop/src/main/__tests__/codexLocalSessions.test.tsindex cd01786e28..73e9fa3e68 100644--- a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts+++ b/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts@@ -42,7 +42,11 @@ import {readCodexThreadStorageForArchive,dumpCodexThreadStateRows,classifyCodexHistoryOversized,+ repairCodexRolloutPath,+ prepareCodexRolloutForResume,+ normalizeCodexWindowsPath,} from '../maker-host/codex-local-sessions';+import { CodexThreadLocations } from '../maker-host/codex-thread-locations';import { clearCurrentDbClient, setCurrentDbClient } from '../localDb/client/current';import type { DbClient } from '../localDb/client/DbClient';import * as schema from '../localDb/schema';@@ -59,6 +63,7 @@ let targetUserData = '';let homedirSpy: { mockRestore: () => void } | null = null;let dateNowSpy: { mockRestore: () => void } | null = null;let originalCodexHome: string | undefined;+let originalAppData: string | undefined;function createLocalDb(): Database.Database {const db = new Database(':memory:');@@ -265,6 +270,7 @@ function rolloutLineWithImage(id: string, text: string, timestamp: string): stribeforeEach(() => {electronMock.region = 'global';originalCodexHome = process.env.CODEX_HOME;+ originalAppData = process.env.APPDATA;rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-local-sessions-'));externalHome = path.join(rootDir, 'external-codex-home');targetUserData = path.join(rootDir, 'xdt-user-data');@@ -274,6 +280,7 @@ beforeEach(() => {fs.mkdirSync(targetUserData, { recursive: true });electronMock.userData = targetUserData;process.env.CODEX_HOME = externalHome;+ process.env.APPDATA = path.join(rootDir, 'appdata');dbMock.current = createLocalDb();setCurrentDbClient(makeTestDbClient(dbMock.current), 'test-user');});@@ -291,6 +298,8 @@ afterEach(() => {} else {process.env.CODEX_HOME = originalCodexHome;}+ if (originalAppData === undefined) delete process.env.APPDATA;+ else process.env.APPDATA = originalAppData;fs.rmSync(rootDir, { recursive: true, force: true });});@@ -1503,6 +1512,264 @@ describe('importExternalCodexMessagesForSession', () => {});});+// #7436: unit regression through the real import/preparation entry. Existing+// recovery cases use legacy session_meta and never exercise paginated filenames.+// Minimal input: a paginated source rollout + source/target thread databases.+// Windows run: the added group takes <0.4s; the existing 133-case I/O-heavy+// file takes ~23s including collection (no new module reloads or real waits).+describe('paginated Codex rollout adoption (#7436)', () => {+ it.each([+ ['\\\\?\\C:\\Users\\Example\\.codex', 'C:\\Users\\Example\\.codex'],+ ['\\\\?\\UNC\\server\\share\\sessions', '\\\\server\\share\\sessions'],+ ['/home/example/.codex', '/home/example/.codex'],+ ])('normalizes filesystem aliases without changing their destination: %s', (source, expected) => {+ expect(normalizeCodexWindowsPath(source)).toBe(expected);+ });++ function brokenHistory(reverted = false, archived = false) {+ const home = path.join(targetUserData, 'account-history');+ const sqliteHome = path.join(targetUserData, 'account-state');+ const filename = `rollout-2026-10-14T10-13-41-${threadId}${reverted ? `_${execThreadId}` : ''}.jsonl`;+ const canonical = path.join(home, archived ? 'archived_sessions' : 'sessions', '2026', '10', '14', filename);+ const broken = path.join(path.dirname(canonical), `rollout-cindy-adopted-2-${filename}`);+ const contents = `${JSON.stringify({ type: 'session_meta', payload: {+ id: threadId, history_mode: 'paginated', timestamp: '2026-10-14T10:13:41Z',+ } })}\n`;+ fs.mkdirSync(path.dirname(broken), { recursive: true });+ fs.writeFileSync(broken, contents);+ const dbPath = createStateDb(sqliteHome);+ insertThread(dbPath, threadId, broken, { updatedAt: 2000, title: 'Keep my metadata' });+ const locations = new CodexThreadLocations(path.join(targetUserData, 'locations'), prepareCodexRolloutForResume);+ const readState = () => {+ const db = new Database(dbPath, { readonly: true });+ try { return db.prepare('SELECT * FROM threads WHERE id = ?').get(threadId) as Record<string, unknown>; }+ finally { db.close(); }+ };+ return { home, sqliteHome, canonical, broken, contents, dbPath, locations, readState };+ }++ // #7436 review: root-only native fixtures missed history_base dependencies.+ // Unit tier drives the same preparation used by indexed resume, observing+ // files and pointers on invalid lineage, interrupted publication and retries.+ function ancestorHistory() {+ const f = brokenHistory();+ const filename = `rollout-2026-10-13T10-13-41-${execThreadId}.jsonl`;+ const relative = path.join('archived_sessions', filename);+ const parent = path.join(externalHome, relative);+ const localParent = path.join(f.home, relative);+ const parentContents = `${JSON.stringify({ ordinal: 0, type: 'session_meta', payload: {+ id: execThreadId, history_mode: 'paginated',+ } })}\n${JSON.stringify({ ordinal: 1, type: 'response_item', payload: { text: 'parent history' } })}\n`;+ fs.mkdirSync(path.dirname(parent), { recursive: true });+ fs.writeFileSync(parent, parentContents);+ const rootRecord = JSON.parse(f.contents);+ rootRecord.payload.history_base = {+ thread_id: execThreadId, end_ordinal_exclusive: 2, end_byte_offset: Buffer.byteLength(parentContents),+ };+ const childContents = `${JSON.stringify(rootRecord)}\n`;+ fs.writeFileSync(f.broken, childContents);+ const sourceChild = path.join(externalHome, 'sessions', path.basename(f.canonical));+ fs.mkdirSync(path.dirname(sourceChild), { recursive: true });+ fs.writeFileSync(sourceChild, childContents);+ return { ...f, parent, localParent, parentContents, childContents, sourceChild };+ }++ it.each(['missing', 'truncated', 'cycle', 'conflict'] as const)(+ 'blocks %s ancestry without replacing the selected history or index', async fault => {+ const f = ancestorHistory();+ await f.locations.record(threadId, f.broken, f.sqliteHome);+ if (fault === 'missing') fs.unlinkSync(f.parent);+ if (fault === 'truncated') fs.writeFileSync(f.parent, '{}\n');+ if (fault === 'cycle') {+ fs.writeFileSync(f.parent, `${JSON.stringify({ type: 'session_meta', payload: {+ id: execThreadId, history_mode: 'paginated', history_base: {+ thread_id: threadId, end_ordinal_exclusive: 3, end_byte_offset: Buffer.byteLength(f.childContents),+ },+ } })}\n`);+ }+ if (fault === 'conflict') {+ fs.mkdirSync(path.dirname(f.localParent), { recursive: true });+ fs.writeFileSync(f.localParent, f.parentContents.replace('parent history', 'other! history'));+ }+ const before = f.readState();+ await expect(prepareCodexRolloutForResume(threadId, f.broken, f.sqliteHome, true)).rejects.toThrow(+ fault === 'missing' ? 'missing paginated' : fault === 'truncated' ? 'shorter' : fault === 'cycle' ? 'cyclic' : 'conflicts',+ );+ expect(f.readState()).toEqual(before);+ expect(await f.locations.read(threadId)).toBe(f.broken);+ expect(fs.readFileSync(f.broken, 'utf8')).toBe(f.childContents);+ expect(fs.existsSync(f.canonical)).toBe(false);+ if (fault === 'conflict') expect(fs.readFileSync(f.localParent, 'utf8')).toContain('other! history');+ else expect(fs.existsSync(f.localParent)).toBe(false);+ },+ );++ it('retries a partially published ancestor and later resumes without the external home', async () => {+ const f = ancestorHistory();+ await f.locations.record(threadId, f.broken, f.sqliteHome);+ const link = fs.promises.link;+ const spy = vi.spyOn(fs.promises, 'link').mockImplementationOnce(async (source, destination) => {+ await link(source, destination);+ throw Object.assign(new Error('interrupted after publication'), { code: 'EIO' });+ });+ try { await expect(f.locations.prepareResume(threadId, async () => undefined)).rejects.toThrow('interrupted'); }+ finally { spy.mockRestore(); }+ expect(await f.locations.read(threadId)).toBe(f.broken);+ expect(f.readState().rollout_path).toBe(f.broken);+ expect(fs.readFileSync(f.localParent, 'utf8')).toBe(f.parentContents);+ const inode = fs.statSync(f.localParent).ino;+ expect(await f.locations.prepareResume(threadId, async () => undefined)).toBe(f.canonical);+ expect(fs.statSync(f.localParent).ino).toBe(inode);+ fs.appendFileSync(f.localParent, 'later local history\n');+ // Ancestors can already have additional local turns: compare only the+ // immutable range referenced by the child, never overwrite that live tail.+ expect(await prepareCodexRolloutForResume(threadId, f.canonical, f.sqliteHome, true)).toBe(f.canonical);+ fs.rmSync(externalHome, { recursive: true, force: true });+ expect(await f.locations.prepareResume(threadId, async () => undefined)).toBe(f.canonical);+ expect(fs.readFileSync(f.localParent, 'utf8')).toBe(`${f.parentContents}later local history\n`);+ });++ it('reuses an already-imported ancestor inode so both child and parent can resume', async () => {+ const f = ancestorHistory();+ const oldParent = path.join(path.dirname(f.localParent), `rollout-cindy-adopted-${path.basename(f.localParent)}`);+ fs.mkdirSync(path.dirname(oldParent), { recursive: true });+ fs.writeFileSync(oldParent, f.parentContents);+ insertThread(f.dbPath, execThreadId, oldParent, { updatedAt: 2000 });+ await f.locations.record(threadId, f.broken, f.sqliteHome);+ await f.locations.record(execThreadId, oldParent, f.sqliteHome);+ expect(await f.locations.prepareResume(threadId, async () => undefined)).toBe(f.canonical);+ expect(fs.statSync(f.localParent).ino).toBe(fs.statSync(oldParent).ino);+ fs.appendFileSync(oldParent, 'parent native writer progress\n');+ expect(await f.locations.prepareResume(execThreadId, async () => undefined)).toBe(f.localParent);+ expect(fs.readFileSync(f.localParent, 'utf8')).toBe(`${f.parentContents}parent native writer progress\n`);+ });++ it('preserves a concurrent SQLite winner while importing an ancestor', async () => {+ const f = ancestorHistory();+ const winner = path.join(path.dirname(f.broken), 'winner.jsonl');+ fs.writeFileSync(winner, 'new native history');+ await f.locations.record(threadId, f.broken, f.sqliteHome);+ const link = fs.promises.link;+ const spy = vi.spyOn(fs.promises, 'link').mockImplementationOnce(async (source, destination) => {+ await link(source, destination);+ const db = new Database(f.dbPath);+ try { db.prepare('UPDATE threads SET rollout_path = ? WHERE id = ?').run(winner, threadId); }+ finally { db.close(); }+ });+ try { await expect(f.locations.prepareResume(threadId, async () => undefined)).rejects.toThrow('state changed'); }+ finally { spy.mockRestore(); }+ expect(f.readState().rollout_path).toBe(winner);+ expect(await f.locations.read(threadId)).toBe(f.broken);+ expect(fs.existsSync(f.canonical)).toBe(false);+ expect(fs.readFileSync(winner, 'utf8')).toBe('new native history');+ });++ it('does not publish an ancestor replaced after lineage planning', async () => {+ const f = ancestorHistory();+ await f.locations.record(threadId, f.broken, f.sqliteHome);+ const copy = fs.promises.copyFile;+ const spy = vi.spyOn(fs.promises, 'copyFile').mockImplementationOnce(async (source, destination, mode) => {+ fs.unlinkSync(f.parent);+ fs.writeFileSync(f.parent, f.parentContents.replace('parent history', 'other! history'));+ await copy(source, destination, mode);+ });+ try { await expect(f.locations.prepareResume(threadId, async () => undefined)).rejects.toThrow('changed'); }+ finally { spy.mockRestore(); }+ expect(fs.existsSync(f.localParent)).toBe(false);+ expect(fs.existsSync(f.canonical)).toBe(false);+ expect(f.readState().rollout_path).toBe(f.broken);+ expect(await f.locations.read(threadId)).toBe(f.broken);+ });++ // Indexed resume used to bypass preparation completely. Cover both the host+ // storage lookup and direct resume, with separate SQLite ownership and revert IDs.+ it.each(['storage', 'resume'] as const)('repairs indexed reverted history through %s without adopting another home', async entry => {+ const f = brokenHistory(true, entry === 'storage');+ const before = f.readState();+ await f.locations.record(threadId, f.broken, f.sqliteHome);+ expect(await f.locations.readStorage(threadId)).toEqual({ historyHome: f.home, sqliteHome: f.sqliteHome, rolloutPath: f.broken });+ expect(fs.existsSync(f.canonical)).toBe(false); // archive/export remains read-only+ const legacy = vi.fn(async () => { throw new Error('must not rediscover history'); });+ if (entry === 'storage') {+ expect(await f.locations.readStorage(threadId, { home: externalHome, prepare: legacy })).toEqual({+ historyHome: f.home, sqliteHome: f.sqliteHome, rolloutPath: f.canonical,+ });+ } else {+ expect(await f.locations.prepareResume(threadId, legacy)).toBe(f.canonical);+ }+ expect(legacy).not.toHaveBeenCalled();+ expect(await f.locations.read(threadId)).toBe(f.canonical);+ expect(f.readState()).toEqual({ ...before, rollout_path: f.canonical });+ expect(fs.readFileSync(f.canonical, 'utf8')).toBe(f.contents);+ expect(fs.readFileSync(f.broken, 'utf8')).toBe(f.contents);+ });++ it('retries after SQLite promotion but before index publication without losing appended history', async () => {+ const f = brokenHistory();+ await f.locations.record(threadId, f.broken, f.sqliteHome);+ expect(repairCodexRolloutPath(threadId, f.broken, f.sqliteHome)).toBe(f.canonical);+ fs.appendFileSync(f.broken, 'native writer progress\n');+ expect(await f.locations.prepareResume(threadId, async () => undefined)).toBe(f.canonical);+ expect(fs.readFileSync(f.canonical, 'utf8')).toBe(`${f.contents}native writer progress\n`);+ expect(fs.statSync(f.canonical).ino).toBe(fs.statSync(f.broken).ino);+ expect(await f.locations.prepareResume(threadId, async () => undefined)).toBe(f.canonical);+ });++ it('preserves a conflicting canonical file and both original pointers', async () => {+ const f = brokenHistory();+ await f.locations.record(threadId, f.broken, f.sqliteHome);+ fs.writeFileSync(f.canonical, 'another authoritative history');+ await expect(f.locations.prepareResume(threadId, async () => undefined)).rejects.toThrow('conflicts');+ expect(f.readState().rollout_path).toBe(f.broken);+ expect(await f.locations.read(threadId)).toBe(f.broken);+ expect(fs.readFileSync(f.broken, 'utf8')).toBe(f.contents);+ expect(fs.readFileSync(f.canonical, 'utf8')).toBe('another authoritative history');+ });++ it('does not overwrite a concurrent SQLite winner during canonical publication', () => {+ const f = brokenHistory();+ const winner = path.join(path.dirname(f.broken), 'concurrent.jsonl');+ fs.writeFileSync(winner, 'new history');+ const link = fs.linkSync;+ const spy = vi.spyOn(fs, 'linkSync').mockImplementation((source, destination) => {+ link(source, destination);+ const db = new Database(f.dbPath);+ try { db.prepare('UPDATE threads SET rollout_path = ? WHERE id = ?').run(winner, threadId); }+ finally { db.close(); }+ });+ try { expect(() => repairCodexRolloutPath(threadId, f.broken, f.sqliteHome)).toThrow('state changed'); }+ finally { spy.mockRestore(); }+ expect(f.readState().rollout_path).toBe(winner);+ expect(fs.readFileSync(winner, 'utf8')).toBe('new history');+ });++ it.each([false, true])('publishes a native filename and preserves history (Windows namespace=%s)', async namespaced => {+ const filename = `rollout-2026-10-14T10-13-41-${threadId}.jsonl`;+ const sourcePath = path.join(externalHome, 'sessions', '2026', '10', '14', filename);+ const contents = `${JSON.stringify({ type: 'session_meta', payload: {+ id: threadId, history_mode: 'paginated', timestamp: '2026-10-14T10:13:41Z',+ } })}\n`;+ fs.mkdirSync(path.dirname(sourcePath), { recursive: true });+ fs.writeFileSync(sourcePath, contents);+ const sourceDb = createStateDb(externalHome);+ insertThread(sourceDb, threadId, namespaced ? path.toNamespacedPath(sourcePath) : sourcePath, { updatedAt: 2000 });+ const targetDb = createStateDb(path.join(targetUserData, 'codex-home'));++ const prepared = await prepareExternalCodexSessionForResume(threadId);+ expect(path.basename(prepared!)).toBe(filename);+ expect(path.relative(path.join(targetUserData, 'codex-home'), prepared!)).toBe(+ path.join('sessions', '2026', '10', '14', filename),+ );+ const db = new Database(targetDb, { readonly: true });+ try {+ expect(db.prepare('SELECT rollout_path FROM threads WHERE id = ?').get(threadId)).toEqual({ rollout_path: prepared });+ } finally { db.close(); }+ expect(fs.readFileSync(prepared!, 'utf8')).toBe(contents);+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe(contents);+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(prepared);+ });+});+describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () => {// 桌面端 codex-home = app.getPath('userData')/codex-home(见 getDesktopCodexHome)。const desktopHome = () => path.join(targetUserData, 'codex-home');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.tsindex ee69c147cc..d2003c2bae 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@@ -16,6 +16,46 @@ async function fixture() {return { root, locations: new CodexThreadLocations(path.join(root, 'owner', 'locations')) };}describe('native thread locations across accounts', () => {+ it('rejects a stale index after asynchronous ancestry repair without a filename change', async () => {+ const { root } = await fixture();+ const old = path.join(root, 'sessions', 'old.jsonl');+ const archived = path.join(root, 'archived_sessions', 'old.jsonl');+ await fs.mkdir(path.dirname(old), { recursive: true });+ await fs.writeFile(old, 'history');+ const locations = new CodexThreadLocations(path.join(root, 'locations'), async () => {+ await fs.mkdir(path.dirname(archived), { recursive: true });+ await fs.rename(old, archived);+ await locations.record('thread', archived, root);+ return old;+ });+ await locations.record('thread', old, root);+ await expect(locations.prepareResume('thread', async () => undefined)).rejects.toThrow('location changed');+ expect(await locations.read('thread')).toBe(archived);+ });+ // #7436 unit: a concurrent archive can publish its index during repair's+ // asynchronous temp write. Existing tests cover only sequential index writes.+ // Windows: this file completes in 0.31s, including module collection.+ it('does not overwrite a newer location while publishing a repaired index', async () => {+ const { root } = await fixture();+ const directory = path.join(root, 'locations');+ const old = path.join(root, 'sessions', 'old.jsonl');+ const repaired = path.join(root, 'sessions', 'repaired.jsonl');+ const archived = path.join(root, 'archived_sessions', 'new.jsonl');+ await fs.mkdir(path.dirname(old), { recursive: true });+ await fs.writeFile(old, 'history');+ const locations = new CodexThreadLocations(directory, () => repaired);+ await locations.record('thread', old, root);+ const writeFile = fs.writeFile;+ const spy = vi.spyOn(fs, 'writeFile').mockImplementation(async (file, contents, options) => {+ await writeFile(file, contents, options);+ await writeFile(path.join(directory, 'thread.json'), JSON.stringify({ threadId: 'thread', path: archived, sqliteHome: root }));+ });+ try {+ await expect(locations.prepareResume('thread', async () => undefined)).rejects.toThrow('location changed');+ } finally { spy.mockRestore(); }+ expect(await locations.readStorage('thread')).toEqual({ historyHome: root, sqliteHome: root, rolloutPath: archived });+ });+it('keeps the original database home and recovers legacy location records', async () => {const { root, locations } = await fixture();const home = path.join(root, 'account-a');diff --git a/apps/desktop/src/main/maker-host/codex-local-sessions.ts b/apps/desktop/src/main/maker-host/codex-local-sessions.tsindex 2342eae13f..86618defa0 100644--- a/apps/desktop/src/main/maker-host/codex-local-sessions.ts+++ b/apps/desktop/src/main/maker-host/codex-local-sessions.ts@@ -203,24 +203,30 @@ function nonEmptyRolloutStillMatches(}/** Bounded-memory equality check used only for Cindy-owned immutable candidates. */-function filesHaveSameContents(leftPath: string, rightPath: string): boolean {+function filesHaveSameContents(leftPath: string, rightPath: string, prefixBytes?: number): boolean {let leftFd: number | null = null;let rightFd: number | null = null;try {const leftStat = fs.statSync(leftPath);const rightStat = fs.statSync(rightPath);- if (!leftStat.isFile() || !rightStat.isFile() || leftStat.size !== rightStat.size) return false;+ if (!leftStat.isFile() || !rightStat.isFile()) return false;+ if (prefixBytes === undefined ? leftStat.size !== rightStat.size+ : leftStat.size < prefixBytes || rightStat.size < prefixBytes) return false;leftFd = fs.openSync(leftPath, 'r');rightFd = fs.openSync(rightPath, 'r');const left = Buffer.allocUnsafe(64 * 1024);const right = Buffer.allocUnsafe(64 * 1024);- for (;;) {- const leftRead = fs.readSync(leftFd, left, 0, left.length, null);- const rightRead = fs.readSync(rightFd, right, 0, right.length, null);+ let remaining = prefixBytes ?? leftStat.size;+ while (remaining > 0) {+ const length = Math.min(left.length, remaining);+ const leftRead = fs.readSync(leftFd, left, 0, length, null);+ const rightRead = fs.readSync(rightFd, right, 0, length, null);if (leftRead !== rightRead) return false;- if (leftRead === 0) return true;+ if (leftRead === 0) return false;if (!left.subarray(0, leftRead).equals(right.subarray(0, rightRead))) return false;+ remaining -= leftRead;}+ return true;} catch {return false;} finally {@@ -455,6 +461,14 @@ export function readCodexThreadStorageForArchive(threadId: string): {/** Ensure a Codex thread from another local CODEX_HOME is visible to xdt-maker's app-server. */export async function prepareExternalCodexSessionForResume(threadId: string): Promise<string | undefined> {+ const prepared = await prepareExternalCodexSessionStorage(threadId);+ // Keep the existing snapshot/namespace handoff intact. Its Cindy-owned stage+ // must be promoted before native resume (and repaired after an interrupted+ // promotion), since paginated Codex derives rollout identity from the basename.+ return prepared ? prepareCodexRolloutForResume(threadId, prepared, getDesktopCodexHome(), true) : prepared;+}++async function prepareExternalCodexSessionStorage(threadId: string): Promise<string | undefined> {if (!isLikelyThreadId(threadId)) return;const targetHome = getDesktopCodexHome();const targetDbPath = findLatestStateDb(targetHome);@@ -1213,7 +1227,10 @@ export async function prepareExternalCodexSessionForResume(threadId: string): Pr/** 为外部 thread 派生当前 Codex HOME 内的稳定 rollout 路径。 */function targetRolloutPathForExternalThread(thread: CodexThreadSummary, targetHome: string): string {- const relative = path.relative(thread.sourceHome, thread.rolloutPath);+ const relative = path.relative(+ normalizeCodexWindowsPath(thread.sourceHome),+ normalizeCodexWindowsPath(thread.rolloutPath),+ );const firstSegment = relative.split(path.sep)[0];const isSafeCodexRelativePath = relative !== ''&& relative !== '..'@@ -1227,6 +1244,252 @@ function targetRolloutPathForExternalThread(thread: CodexThreadSummary, targetHoreturn path.join(targetHome, directory, filename);}+/** Normalize only Win32 filesystem aliases, including extended UNC paths. */+export function normalizeCodexWindowsPath(value: string): string {+ if (/^\\\\\?\\UNC\\/i.test(value)) return `\\\\${value.slice(8)}`;+ return /^\\\\\?\\[a-z]:\\/i.test(value) ? value.slice(4) : value;+}++function originalCodexRolloutName(file: string): string {+ return path.basename(file).replace(/^(?:rollout-cindy-(?:adopted|empty-recovery|synthetic)(?:-\d+)?-)+/, '');+}++function nativeRolloutIdentity(file: string): { threadId: string; rolloutId: string } | undefined {+ const uuid = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';+ const match = originalCodexRolloutName(file).match(new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${uuid})(?:_(${uuid}))?\\.jsonl$`, 'i'));+ return match ? { threadId: match[1]!.toLowerCase(), rolloutId: (match[2] ?? match[1])!.toLowerCase() } : undefined;+}++interface CodexHistoryBase {+ thread_id: string;+ end_ordinal_exclusive: number;+ end_byte_offset: number;+}++function readPaginatedBase(threadId: string, file: string): CodexHistoryBase | undefined {+ const line = readFirstLineSync(file);+ if (!line) return;+ let record: unknown;+ try { record = JSON.parse(line); } catch { return; }+ if (!isRecord(record) || record.type !== 'session_meta' || !isRecord(record.payload)+ || record.payload.history_mode !== 'paginated' || record.payload.history_base == null) return;+ const base = record.payload.history_base;+ if (!isRecord(base) || typeof base.thread_id !== 'string'+ || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(base.thread_id)+ || !Number.isSafeInteger(base.end_ordinal_exclusive) || (base.end_ordinal_exclusive as number) <= 0+ || !Number.isSafeInteger(base.end_byte_offset) || (base.end_byte_offset as number) <= 0) {+ throw resumePreparationBlocked(threadId, 'invalid paginated history ancestor reference');+ }+ return base as unknown as CodexHistoryBase;+}++/** Finish a native history handoff before resume, including old indexed imports. */+export async function prepareCodexRolloutForResume(+ threadId: string, rolloutPath: string, sqliteHome: string, verifyExternalSource = false,+): Promise<string> {+ const dbPath = findLatestStateDb(sqliteHome);+ const expected = dbPath ? readThreadRolloutPath(dbPath, threadId) : null;+ await ensureCodexHistoryAncestors(threadId, rolloutPath, verifyExternalSource);+ if (dbPath && readThreadRolloutPath(dbPath, threadId) !== expected) {+ throw resumePreparationBlocked(threadId, 'the selected Codex state changed during ancestor import');+ }+ return repairCodexRolloutPath(threadId, rolloutPath, sqliteHome);+}++async function ensureCodexHistoryAncestors(threadId: string, rolloutPath: string, verifyExternalSource: boolean): Promise<void> {+ const targetHome = historyHomeForRollout(rolloutPath);+ const rootSnapshot = readPrivateNonEmptyRolloutSnapshot(targetHome, rolloutPath);+ if (!rootSnapshot) return; // Preserve existing missing/empty/unsafe recovery behavior.+ // Most histories are self-contained. Do not scan external homes on this path.+ let base = readPaginatedBase(threadId, rolloutPath);+ if (!base) return;+ const rootLine = readFirstLineSync(rolloutPath);+ const rootIdentity = nativeRolloutIdentity(rolloutPath);+ if (!rootIdentity || rootIdentity.threadId !== threadId.toLowerCase()) {+ throw resumePreparationBlocked(threadId, 'the selected paginated history has an invalid identity');+ }+ const filesByHome = new Map<string, string[]>();+ const files = (home: string) => {+ let value = filesByHome.get(home);+ if (!value) { value = collectRolloutFiles(home, samePath(home, targetHome)); filesByHome.set(home, value); }+ return value;+ };+ let sourceHome: string | undefined;+ let searchedSource = false;+ const source = () => {+ if (!searchedSource) {+ searchedSource = true;+ // Anchor recovery to the exact imported child's immutable metadata and+ // rollout identity. Never pick a similarly named thread or reimport its tail.+ const homes = discoverExternalCodexHomesSync().filter(home => !samePath(home, targetHome)+ && files(home).some(file => path.basename(file) === originalCodexRolloutName(rolloutPath)+ && !!readPrivateNonEmptyRolloutSnapshot(home, file) && readFirstLineSync(file) === rootLine));+ if (homes.length > 1) throw resumePreparationBlocked(threadId, 'ambiguous paginated history source');+ sourceHome = homes[0];+ }+ return sourceHome;+ };+ if (verifyExternalSource) source();+ const find = (home: string, id: string) => {+ const matches = files(home).filter(file => nativeRolloutIdentity(file)?.rolloutId === id.toLowerCase())+ .sort((a, b) => Number(path.basename(a) !== originalCodexRolloutName(a)) - Number(path.basename(b) !== originalCodexRolloutName(b)));+ if (matches.some(file => !sameRegularFileIdentity(file, matches[0]!))) {+ throw resumePreparationBlocked(threadId, 'ambiguous paginated history ancestor');+ }+ return matches[0];+ };+ const seen = new Set([rootIdentity.rolloutId]);+ const plan: Array<{ sourcePath?: string; localAlias?: string; destination: string; snapshot: NonEmptyRolloutSnapshot }> = [];+ while (base) {+ const id = base.thread_id.toLowerCase();+ if (seen.has(id)) throw resumePreparationBlocked(threadId, 'cyclic paginated history ancestry');+ seen.add(id);+ const local = find(targetHome, id);+ if (!local) source();+ const external = sourceHome ? find(sourceHome, id) : undefined;+ const selected = external ?? local;+ const home = external ? sourceHome! : targetHome;+ if (!selected) throw resumePreparationBlocked(threadId, 'missing paginated history ancestor');+ const snapshot = readPrivateNonEmptyRolloutSnapshot(home, selected);+ if (!snapshot || snapshot.size < base.end_byte_offset) {+ throw resumePreparationBlocked(threadId, 'paginated history ancestor is unsafe or shorter than its referenced range');+ }+ const metaLine = readFirstLineSync(selected);+ let meta: unknown;+ try { meta = metaLine ? JSON.parse(metaLine) : undefined; }+ catch { throw resumePreparationBlocked(threadId, 'invalid paginated history ancestor metadata'); }+ if (!isRecord(meta) || meta.type !== 'session_meta' || !isRecord(meta.payload)+ || meta.payload.history_mode !== 'paginated' || typeof meta.payload.id !== 'string'+ || meta.payload.id.toLowerCase() !== nativeRolloutIdentity(selected)?.threadId) {+ throw resumePreparationBlocked(threadId, 'invalid paginated history ancestor metadata');+ }+ if (local && external) {+ const localSnapshot = readPrivateNonEmptyRolloutSnapshot(targetHome, local);+ if (!localSnapshot || !filesHaveSameContents(local, external, base.end_byte_offset)+ || !nonEmptyRolloutStillMatches(local, localSnapshot) || !nonEmptyRolloutStillMatches(external, snapshot)) {+ throw resumePreparationBlocked(threadId, 'paginated history ancestor conflicts with local history');+ }+ plan.push({ localAlias: local, destination: path.join(path.dirname(local), originalCodexRolloutName(local)), snapshot: localSnapshot });+ } else if (local) {+ plan.push({ localAlias: local, destination: path.join(path.dirname(local), originalCodexRolloutName(local)), snapshot });+ } else {+ const relative = path.relative(normalizeCodexWindowsPath(home), normalizeCodexWindowsPath(selected));+ const destination = path.join(targetHome, relative);+ if (!isPathInside(targetHome, destination)) throw resumePreparationBlocked(threadId, 'invalid paginated ancestor destination');+ plan.push({ sourcePath: selected, destination, snapshot });+ }+ base = readPaginatedBase(threadId, selected);+ }+ // Validate the entire chain before publishing anything. Ancestors are published+ // oldest-first without replacement; interrupted attempts can reuse exact copies.+ const publications: PrivateRolloutPublication[] = [];+ for (const entry of plan.reverse()) {+ if (!entry.sourcePath) {+ if (entry.localAlias && !samePath(entry.localAlias, entry.destination)) {+ // A parent may itself be an old imported task with a live writer/index.+ // Give that same inode a native name; copying would strand its own resume.+ const original = { path: entry.localAlias, created: false, snapshot: entry.snapshot };+ if (!privateRolloutPublicationStillMatches(targetHome, original)+ || !isPathInside(targetHome, entry.destination)) {+ throw resumePreparationBlocked(threadId, 'paginated history ancestor changed before publication');+ }+ try { await fsp.link(entry.localAlias, entry.destination); }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; }+ if (!privateRolloutPublicationOwnsPath(targetHome, original, entry.destination)) {+ throw resumePreparationBlocked(threadId, 'paginated history ancestor conflicts with local history');+ }+ publications.push(original);+ }+ publications.push({ path: entry.destination, created: false, snapshot: entry.snapshot });+ continue;+ }+ if (!nonEmptyRolloutStillMatches(entry.sourcePath, entry.snapshot)) {+ throw resumePreparationBlocked(threadId, 'paginated history ancestor changed during import');+ }+ const publication = await copyExternalRolloutAtomically(entry.sourcePath, entry.destination, threadId,+ { allowSibling: false, targetHome, sourceSnapshot: entry.snapshot });+ if (!publication) throw resumePreparationBlocked(threadId, 'paginated history ancestor changed or conflicts during import');+ publications.push(publication);+ }+ if (!privateRolloutPublicationOwnsPath(targetHome, { path: rolloutPath, created: false, snapshot: rootSnapshot })+ || readFirstLineSync(rolloutPath) !== rootLine+ || publications.some(publication => !privateRolloutPublicationStillMatches(targetHome, publication))) {+ throw resumePreparationBlocked(threadId, 'paginated history changed before resume');+ }+}++/**+ * Repair #7436 at the native-resume boundary, using only the selected history.+ * A hard link keeps both names on the same inode: interrupted index publication+ * and an already-open writer cannot strand newer bytes on an obsolete copy.+ * Never overwrite a conflicting canonical file or rediscover an external HOME.+ */+export function repairCodexRolloutPath(threadId: string, rolloutPath: string, sqliteHome: string): string {+ const originalName = path.basename(rolloutPath);+ if (!originalName.startsWith('rollout-cindy-')) return rolloutPath;+ const historyHome = historyHomeForRollout(rolloutPath);+ const snapshot = readPrivateNonEmptyRolloutSnapshot(historyHome, rolloutPath);+ // Missing/empty paths retain the existing native recovery behavior. Never+ // read metadata through a final symlink or an escaped sessions ancestor.+ if (!snapshot) {+ if (readPrivateRolloutPathState(historyHome, rolloutPath) === 'unsafe') {+ throw resumePreparationBlocked(threadId, 'the selected rollout is not a private regular file');+ }+ return rolloutPath;+ }+ const line = readFirstLineSync(rolloutPath);+ if (!line) return rolloutPath;+ let meta: unknown;+ try { meta = JSON.parse(line); } catch { return rolloutPath; }+ if (!isRecord(meta) || meta.type !== 'session_meta' || !isRecord(meta.payload)+ || meta.payload.history_mode !== 'paginated') return rolloutPath;+ if (meta.payload.id !== threadId) {+ throw resumePreparationBlocked(threadId, 'the selected paginated rollout belongs to another thread');+ }++ const filename = originalCodexRolloutName(rolloutPath);+ // Native revert uses <threadId>_<rolloutId>. Preserve both IDs, not a newly+ // generated UUID or the last UUID extracted by the legacy scanner.+ const match = filename.match(/^rollout-(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2})-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))?\.jsonl$/i);+ const timestamp = match?.[1]?.replace(/T(\d{2})-(\d{2})-(\d{2})$/, 'T$1:$2:$3');+ if (!match || match[2]!.toLowerCase() !== threadId.toLowerCase() || !timestamp+ || !Number.isFinite(Date.parse(`${timestamp}Z`))+ || new Date(`${timestamp}Z`).toISOString().slice(0, 19) !== timestamp) {+ throw resumePreparationBlocked(threadId, 'the original paginated rollout filename cannot be recovered');+ }++ const canonical = path.join(path.dirname(rolloutPath), filename);+ if (!isPathInside(historyHome, canonical)) {+ throw resumePreparationBlocked(threadId, 'the selected paginated rollout is not a private regular file');+ }+ const dbPath = findLatestStateDb(sqliteHome);+ if (!dbPath) throw resumePreparationBlocked(threadId, 'the selected Codex state database is unavailable');+ const current = readThreadRolloutPath(dbPath, threadId);+ const normalized = (value: string) => path.resolve(normalizeCodexWindowsPath(value));+ if (!current || (normalized(current) !== normalized(rolloutPath) && normalized(current) !== normalized(canonical))) {+ throw resumePreparationBlocked(threadId, 'the selected Codex state changed before filename repair');+ }++ try { fs.linkSync(rolloutPath, canonical); } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {+ throw resumePreparationBlocked(threadId, 'the canonical rollout could not be published');+ }+ }+ const publication: PrivateRolloutPublication = { path: canonical, created: false, snapshot };+ const validateIdentity = () => {+ if (!privateRolloutPublicationOwnsPath(historyHome, publication)+ || !privateRolloutPublicationOwnsPath(historyHome, publication, rolloutPath)) {+ throw resumePreparationBlocked(threadId, 'the canonical rollout conflicts with the selected history');+ }+ };+ validateIdentity();+ if (!handoffThreadToNativeRollout(dbPath, threadId, historyHome, current, publication, validateIdentity)) {+ throw resumePreparationBlocked(threadId, 'the selected Codex state changed during filename repair');+ }+ validateIdentity();+ return canonical;+}+/** Resolve a missing path through its nearest existing ancestor, including symlinks. */function resolvePathForBoundary(candidate: string): string {let current = path.resolve(candidate);@@ -1476,12 +1739,12 @@ async function copyExternalRolloutAtomically(sourcePath: string,preferredPath: string,threadId: string,- opts: { allowSibling: boolean; skipPreferred?: boolean },+ opts: { allowSibling: boolean; skipPreferred?: boolean; targetHome?: string; sourceSnapshot?: NonEmptyRolloutSnapshot },): Promise<PrivateRolloutPublication | null> {if (samePath(sourcePath, preferredPath)) return null;- const targetHome = getDesktopCodexHome();+ const targetHome = opts.targetHome ?? getDesktopCodexHome();if (!isPathInside(targetHome, preferredPath)) return null;- const sourceSnapshot = readNonEmptyRolloutSnapshot(sourcePath);+ const sourceSnapshot = opts.sourceSnapshot ?? readNonEmptyRolloutSnapshot(sourcePath);if (!sourceSnapshot) return null;await fsp.mkdir(path.dirname(preferredPath), { recursive: true });@@ -4028,7 +4291,7 @@ function isCindyRolloutArtifactFileName(name: string): boolean {|| name.startsWith('.cindy-state-less-recovery');}-function collectRolloutFiles(home: string): string[] {+function collectRolloutFiles(home: string, includeCindyArtifacts = false): string[] {const roots = [path.join(home, 'sessions'), path.join(home, 'archived_sessions')];const files: Array<{ file: string; mtime: number }> = [];const visit = (dir: string, depth: number) => {@@ -4047,7 +4310,7 @@ function collectRolloutFiles(home: string): string[] {entry.isFile()&& entry.name.endsWith('.jsonl')&& entry.name.includes('rollout-')- && !isCindyRolloutArtifactFileName(entry.name)+ && (includeCindyArtifacts || !isCindyRolloutArtifactFileName(entry.name))) {try {files.push({ file: full, mtime: fs.statSync(full).mtimeMs });diff --git a/apps/desktop/src/main/maker-host/codex-thread-locations.ts b/apps/desktop/src/main/maker-host/codex-thread-locations.tsindex 7d4bdf70db..e8ba3ba87c 100644--- a/apps/desktop/src/main/maker-host/codex-thread-locations.ts+++ b/apps/desktop/src/main/maker-host/codex-thread-locations.ts@@ -1,4 +1,5 @@import fs from 'node:fs/promises';+import { readFileSync, renameSync } from 'node:fs';import path from 'node:path';import { randomUUID } from 'node:crypto';@@ -10,7 +11,26 @@ interface ThreadLocation {/** A native thread has one durable rollout, regardless of the account resuming it. */export class CodexThreadLocations {- constructor(private readonly directory: string) {}+ constructor(+ private readonly directory: string,+ private readonly repairRollout?: (threadId: string, rolloutPath: string, sqliteHome: string) => string | Promise<string>,+ ) {}++ private async prepareLocation(value: ThreadLocation): Promise<ThreadLocation> {+ if (!this.repairRollout) return value;+ const sqliteHome = value.sqliteHome ?? historyHomeForRollout(value.path);+ const repaired = await this.repairRollout(value.threadId, value.path, sqliteHome);+ if (repaired === value.path) {+ const current = await this.readLocation(value.threadId);+ if (current?.path !== value.path || current.sqliteHome !== value.sqliteHome) {+ throw new Error('Codex thread location changed during history repair');+ }+ return value;+ }+ const next = { ...value, path: repaired };+ await this.writeLocation(next, value);+ return next;+ }private file(threadId: string): string {if (!/^[a-zA-Z0-9-]{1,100}$/.test(threadId)) throw new Error('Invalid Codex thread id');@@ -64,14 +84,14 @@ export class CodexThreadLocations {): Promise<string | undefined> {const value = await this.readLocation(threadId);if (!value) return prepareLegacy(threadId);- return await this.rolloutExists(value.path) ? value.path : undefined;+ return await this.rolloutExists(value.path) ? (await this.prepareLocation(value)).path : undefined;}async readStorage(threadId: string,legacy?: { home: string; prepare: (threadId: string) => Promise<string | undefined> },): Promise<{ historyHome: string; sqliteHome: string; rolloutPath?: string } | undefined> {- const value = await this.readLocation(threadId);+ let 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.@@ -80,6 +100,9 @@ export class CodexThreadLocations {await this.record(threadId, legacyRollout, legacy.home);return { historyHome: historyHomeForRollout(legacyRollout), sqliteHome: legacy.home, rolloutPath: legacyRollout };}+ // No legacy preparation argument means a read-only lookup (archive/export).+ // Resolve repairs before account-host startup, while retaining sqliteHome.+ if (legacy) value = await this.prepareLocation(value);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@@ -93,14 +116,30 @@ export class CodexThreadLocations {async record(threadId: string, rolloutPath: string, sqliteHome?: string): Promise<void> {if (!path.isAbsolute(rolloutPath)) throw new Error('Invalid Codex rollout path');- const file = this.file(threadId);+ await this.writeLocation({ threadId, path: rolloutPath, sqliteHome });+ }++ private async writeLocation(value: ThreadLocation, expected?: ThreadLocation): Promise<void> {+ const file = this.file(value.threadId);await fs.mkdir(this.directory, { recursive: true, mode: 0o700 });const temporary = `${file}.${randomUUID()}.tmp`;try {- await fs.writeFile(temporary, JSON.stringify({ threadId, path: rolloutPath, sqliteHome }), {+ await fs.writeFile(temporary, JSON.stringify(value), {mode: 0o600,});- await fs.rename(temporary, file);+ if (expected) {+ // Do not yield between rechecking the index and publishing the repair:+ // an archive/model switch may have recorded a new location while the+ // temporary file was being written. SQLite promotion is retryable.+ const current = JSON.parse(readFileSync(file, 'utf8')) as ThreadLocation;+ if (current.threadId !== expected.threadId || current.sqliteHome !== expected.sqliteHome+ || (current.path !== expected.path && current.path !== value.path)) {+ throw new Error('Codex thread location changed during history repair');+ }+ renameSync(temporary, file);+ } else {+ await fs.rename(temporary, file);+ }} finally {await fs.rm(temporary, { force: true });}diff --git a/apps/desktop/src/main/maker-host/codex-thread-storage.ts b/apps/desktop/src/main/maker-host/codex-thread-storage.tsindex b85413aa51..8c28a67e30 100644--- a/apps/desktop/src/main/maker-host/codex-thread-storage.ts+++ b/apps/desktop/src/main/maker-host/codex-thread-storage.ts@@ -1,12 +1,12 @@import path from 'node:path';import { getActiveAppSession } from '../appSessionState.js';import { codexAccountHome } from './codex-account-auth.js';-import { readCodexThreadStorageForArchive } from './codex-local-sessions.js';+import { readCodexThreadStorageForArchive, prepareCodexRolloutForResume } from './codex-local-sessions.js';import { CodexThreadLocations } from './codex-thread-locations.js';/** Thread locations of the active owner. Multi-account history lives outside the desktop Codex home. */export function ownerCodexThreadLocations(): CodexThreadLocations {- return new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations'));+ return new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations'), prepareCodexRolloutForResume);}/**diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex 148a5f9f4e..2410ebdfe6 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -227,6 +227,23 @@ Codex 跨凭证优先保留同一个原生线程;仅当目标需要另一个 h本地恢复与分叉必须同时固定该线程的原生历史根(`CODEX_HOME`,含 `sessions` / `archived_sessions`)和数据库根(`sqlite_home`);仅固定 SQLite 不足以恢复分页祖先,原生按不可变 rollout ID 在历史根内查找祖先。+本机外部 Codex 导入完成历史快照交接后、调用原生恢复前,必须将 paginated 历史的+`rollout-cindy-adopted-*` 名称恢复为原生规范文件名(#7436)。保留原名中的 thread ID+及可选的独立 rollout ID,不修改历史内容。存量错误路径在已记录的历史根和 SQLite 根内+修复:不覆盖地建立同 inode 的规范名称、条件更新 SQLite 指针,最后更新位置索引;+保留旧名称,使中断重试与已打开的 writer 不会丢失追加内容。遇到另一份规范文件或状态+已被其它操作切换时明确失败,不覆盖、不重新导入子历史,也不从聊天投影重建。+带 `history_base` 的分页历史恢复前必须补齐所引用的完整祖先链,按原生 rollout ID+(可能不同于 thread ID)查找,并保留原始字节、序号与归档位置。存量导入缺少祖先时,+仅从与已选子历史的原文件名、首条元数据完全匹配的外部 HOME 补齐;来源不明确、+祖先缺失/越界/循环或已有副本的引用范围冲突时明确失败。已有子历史和祖先的后续+追加不被替换;已有祖先仍使用 Cindy 旧文件名时,通过同 inode 规范名称复用,不能另拷贝+导致父任务恢复冲突。整链先校验,再从最早祖先开始不覆盖发布,中断可重试。补齐后外部 HOME+不可用也能恢复。异步复制后重查 SQLite 指针和位置索引,不能覆盖并发归档或切换。+只读归档/导出查询不触发修复。Windows 扩展盘符与 UNC 路径在相对路径计算前统一表示。+实现见 `maker-host/codex-local-sessions.ts`、`codex-thread-locations.ts`;默认回归在+`main/__tests__/codexLocalSessions.test.ts`,真实恢复与下一轮发送在同目录的+`codexLocalSessions.native.test.ts`(显式指定 `CINDY_CODEX_TEST_BINARY`,隔离目录与本机模型服务)。归档状态以 Cindy 的 `sessions.status` 为准。Codex 经原生 `thread/archive` /`thread/unarchive` 同步历史位置与索引,成功后更新线程位置记录;禁止直接改原生 SQLite或搬动 rollout,也不能为归档触发历史复制/重建。启动时补齐存量状态,忙碌任务、离线