Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(sessions): synchronize harness archive state and preserve directory scope (#5261)
Chris Zhang913fbc718441
diff --git a/apps/desktop/src/main/__tests__/claudeLocalSessions.test.ts b/apps/desktop/src/main/__tests__/claudeLocalSessions.test.tsindex 862c239f6a..b43ed848ab 100644--- a/apps/desktop/src/main/__tests__/claudeLocalSessions.test.ts+++ b/apps/desktop/src/main/__tests__/claudeLocalSessions.test.ts@@ -88,6 +88,8 @@ function createLocalDb(): Database.Database {feishu_bot_app_id TEXT,used_project_context INTEGER NOT NULL DEFAULT 0,extra_dirs TEXT NOT NULL DEFAULT '[]',+ writable_dirs TEXT NOT NULL DEFAULT '[]',+ remote_host_id TEXT,list_preview TEXT,list_preview_role TEXT,list_message_count INTEGER,@@ -1013,6 +1015,14 @@ describe('parseClaudeCodeMessageLine', () => {expect(result).toMatchObject({ scanned: 1, inserted: 1, updated: 0 });const rows = db.prepare('SELECT id, title FROM sessions ORDER BY id').all();expect(rows).toEqual([{ id: `claude-${sdkSessionId}`, title: 'import me' }]);+ db.prepare(`UPDATE sessions SET status='archived', working_dir='/moved-project',+ extra_dirs='["/reference"]', writable_dirs='["/output"]', updated_at=1`).run();+ expect((await scanExternalClaudeCodeSessions()).candidates.find(item => item.id === sdkSessionId))+ .toMatchObject({ archived: true, cwd: '/moved-project', extraDirs: ['/reference'], writableDirs: ['/output'] });+ await importExternalClaudeCodeSessions([sdkSessionId]);+ expect(db.prepare('SELECT status, working_dir, extra_dirs, writable_dirs FROM sessions').get()).toEqual({+ status: 'archived', working_dir: '/moved-project', extra_dirs: '["/reference"]', writable_dirs: '["/output"]',+ });} finally {homedir.mockRestore();resetLocalDb();diff --git a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts b/apps/desktop/src/main/__tests__/codexLocalSessions.test.tsindex d01be11c8b..2bee661482 100644--- a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts+++ b/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts@@ -35,6 +35,7 @@ import {parseCodexRolloutMessageLine,scanExternalCodexSessions,prepareExternalCodexSessionForResume,+ readCodexThreadStorageForArchive,} from '../maker-host/codex-local-sessions';import { clearCurrentDbClient, setCurrentDbClient } from '../localDb/client/current';import type { DbClient } from '../localDb/client/DbClient';@@ -86,6 +87,8 @@ function createLocalDb(): Database.Database {feishu_bot_app_id TEXT,used_project_context INTEGER NOT NULL DEFAULT 0,extra_dirs TEXT NOT NULL DEFAULT '[]',+ writable_dirs TEXT NOT NULL DEFAULT '[]',+ remote_host_id TEXT,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);@@ -281,6 +284,80 @@ afterEach(() => {});describe('Codex local session import', () => {+ it('locates archive storage in the known state DB after sqlite_home changes', () => {+ const dbPath = createStateDb(externalHome);+ const newHome = path.join(rootDir, 'new-state');+ const newDbPath = createStateDb(newHome);+ const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);+ fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });+ fs.writeFileSync(rolloutPath, '');+ insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });+ const config = `sqlite_home = ${JSON.stringify(newHome)}\n`;+ fs.writeFileSync(path.join(externalHome, 'config.toml'), config);+ const before = [fs.readFileSync(dbPath), fs.readFileSync(newDbPath)];++ expect(readCodexThreadStorageForArchive(threadId)).toEqual({+ historyHome: externalHome, sqliteHome: fs.realpathSync(externalHome), rolloutPath,+ });+ expect([fs.readFileSync(dbPath), fs.readFileSync(newDbPath)]).toEqual(before);+ expect(fs.readFileSync(path.join(externalHome, 'config.toml'), 'utf8')).toBe(config);+ });++ it.each(['absolute', 'relative'])('locates archive storage with a separate %s sqlite_home', kind => {+ const sqliteHome = path.join(rootDir, 'separate-state');+ const dbPath = createStateDb(sqliteHome);+ const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);+ fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });+ const content = JSON.stringify({ type: 'session_meta', timestamp: '2026-05-13T00:00:00.000Z',+ payload: { id: threadId, timestamp: '2026-05-13T00:00:00.000Z', cwd: '/project', source: 'cli' } }) + '\n';+ fs.writeFileSync(rolloutPath, content);+ insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });+ const config = `sqlite_home = ${JSON.stringify(kind === 'absolute' ? sqliteHome : '../separate-state')}\n`;+ fs.writeFileSync(path.join(externalHome, 'config.toml'), config);+ const before = fs.readFileSync(dbPath);++ const storage = readCodexThreadStorageForArchive(threadId)!;+ expect(fs.realpathSync(storage.historyHome)).toBe(fs.realpathSync(externalHome));+ expect(fs.realpathSync(storage.sqliteHome)).toBe(fs.realpathSync(sqliteHome));+ expect(fs.readFileSync(storage.rolloutPath, 'utf8')).toBe(content);+ expect(fs.readFileSync(dbPath)).toEqual(before);+ expect(fs.readFileSync(path.join(externalHome, 'config.toml'), 'utf8')).toBe(config);+ expect(currentTestDb().prepare('SELECT COUNT(*) AS n FROM sessions').get()).toEqual({ n: 0 });+ });++ it.each(['sessions', 'archived_sessions'])('locates current-home archive storage in %s without a location record', directory => {+ const home = path.join(targetUserData, 'codex-home');+ const dbPath = createStateDb(home);+ const rolloutPath = path.join(home, directory, `rollout-2026-05-13-${threadId}.jsonl`);+ fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });+ fs.writeFileSync(rolloutPath, '');+ insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });+ const before = fs.readFileSync(dbPath);++ expect(readCodexThreadStorageForArchive(threadId)).toEqual({+ historyHome: home, sqliteHome: home, rolloutPath,+ });+ expect(fs.readFileSync(dbPath)).toEqual(before);+ expect(currentTestDb().prepare('SELECT COUNT(*) AS n FROM sessions').get()).toEqual({ n: 0 });+ expect(fs.readFileSync(rolloutPath, 'utf8')).toBe('');+ });++ it('locates archive storage without importing or copying history', () => {+ const dbPath = createStateDb(externalHome);+ const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);+ fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });+ fs.writeFileSync(rolloutPath, '');+ insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });+ const before = fs.readFileSync(dbPath);++ expect(readCodexThreadStorageForArchive(threadId)).toEqual({+ historyHome: externalHome, sqliteHome: fs.realpathSync(externalHome), rolloutPath,+ });+ expect(fs.readFileSync(dbPath)).toEqual(before);+ expect(currentTestDb().prepare('SELECT COUNT(*) AS n FROM sessions').get()).toEqual({ n: 0 });+ expect(fs.readFileSync(rolloutPath, 'utf8')).toBe('');+ });+it('defensively removes complete IDE context from Codex user messages', () => {const ideContext = '<ide_opened_file>The user opened /tmp/a.ts in the IDE.</ide_opened_file>';const cleaned = parseCodexRolloutMessageLine(@@ -714,6 +791,25 @@ describe('Codex local session import', () => {});});+ it('keeps Cindy archive and directory scope when a newer native index still says active', async () => {+ const dbPath = createStateDb(externalHome);+ const rolloutPath = path.join(externalHome, 'sessions', `rollout-${threadId}.jsonl`);+ fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });+ fs.writeFileSync(rolloutPath, '');+ insertThread(dbPath, threadId, rolloutPath, { updatedAt: 2000 });+ insertImportedCodexSession(currentTestDb(), `codex-${threadId}`, threadId);+ currentTestDb().prepare(`UPDATE sessions SET status='archived', working_dir='/moved-project',+ extra_dirs='["/reference"]', writable_dirs='["/output"]'`).run();+ const scan = await scanExternalCodexSessions();+ expect(scan.candidates).toEqual([expect.objectContaining({+ archived: true, cwd: '/moved-project', extraDirs: ['/reference'], writableDirs: ['/output'],+ })]);+ await importExternalCodexSessions([threadId]);+ expect(currentTestDb().prepare('SELECT status, working_dir, extra_dirs, writable_dirs FROM sessions').get()).toEqual({+ status: 'archived', working_dir: '/moved-project', extra_dirs: '["/reference"]', writable_dirs: '["/output"]',+ });+ });+it('maps external Codex archived state while preserving the project working dir', async () => {const dbPath = createStateDb(externalHome);const rolloutPath = path.join(diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 99501ce69e..8e4b448857 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -101,6 +101,7 @@ import { removeTurnChangeSetsForSession } from '../../turn-change-set/store.js';import { quiesceSessionBeforeWorktreeRecycle } from './sessionRemovalOperations.js';import { withSessionRouteLock, withSessionRouteLocks } from '../sessionRouteLock.js';import { cleanupSessionRuntimeForTerminalStatus } from '../sessionRuntimeCleanup.js';+import { requestSessionArchiveSync } from '../sessionArchiveSync.js';import { cindyMakeManager } from '../../cindy-make/manager.js';import { recycleCindyMakeTask } from '../../cindy-make/taskManagement.js';import { broadcastSubagentRunsInvalidated } from './subagentRuns.js';@@ -610,6 +611,7 @@ function notifyGhostSessionStatusChange(status: unknown,workingDir?: string | null,): void {+ if (status === 'active' || status === 'archived') requestSessionArchiveSync();if (status !== 'archived') return;void import('../../cindy-brain/index.js').then((m) =>diff --git a/apps/desktop/src/main/localDb/sessionArchiveSync.ts b/apps/desktop/src/main/localDb/sessionArchiveSync.tsnew file mode 100644index 0000000000..49b668a9de--- /dev/null+++ b/apps/desktop/src/main/localDb/sessionArchiveSync.ts@@ -0,0 +1,10 @@+let requestSync: (() => void) | null = null;++/** Native storage is a projection. Failed work remains recoverable from sessions.status. */+export function setSessionArchiveSyncRequester(request: (() => void) | null): void {+ requestSync = request;+}++export function requestSessionArchiveSync(): void {+ requestSync?.();+}diff --git a/apps/desktop/src/main/localDb/sessionRuntimeCleanup.ts b/apps/desktop/src/main/localDb/sessionRuntimeCleanup.tsindex c15e05e55c..eb8aaae944 100644--- a/apps/desktop/src/main/localDb/sessionRuntimeCleanup.ts+++ b/apps/desktop/src/main/localDb/sessionRuntimeCleanup.ts@@ -1,3 +1,5 @@+import { requestSessionArchiveSync } from './sessionArchiveSync.js';+type SessionRuntimeCleanup = (sessionId: string) => void;let sessionRuntimeCleanup: SessionRuntimeCleanup | null = null;@@ -16,4 +18,5 @@ export function setSessionRuntimeCleanup(cleanup: SessionRuntimeCleanup | null):export function cleanupSessionRuntimeForTerminalStatus(sessionId: string, status: unknown): void {if (status !== 'deleted' && status !== 'archived') return;sessionRuntimeCleanup?.(sessionId);+ requestSessionArchiveSync();}diff --git a/apps/desktop/src/main/maker-host/__tests__/session-archive-sync.test.ts b/apps/desktop/src/main/maker-host/__tests__/session-archive-sync.test.tsnew file mode 100644index 0000000000..86952b361d--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/session-archive-sync.test.ts@@ -0,0 +1,152 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import Database from 'better-sqlite3';+import { createSessionArchiveSync, prepareArchiveSessions, type ArchiveSessionRow } from '../session-archive-sync.js';+import { projectNativeSessionMetadata } from '../native-session-metadata.js';+import { setCurrentDbClient, clearCurrentDbClient } from '../../localDb/client/current.js';+import type { DbClient } from '../../localDb/client/DbClient.js';++const cleanups: Array<() => void> = [];+afterEach(() => { for (const cleanup of cleanups.splice(0).reverse()) cleanup(); clearCurrentDbClient(); vi.useRealTimers(); });++function fixture() {+ const db = new Database(':memory:');+ cleanups.push(() => db.close());+ db.exec(`CREATE TABLE sessions (id TEXT PRIMARY KEY, agent_kind TEXT, sdk_session_id TEXT,+ status TEXT, remote_host_id TEXT, working_dir TEXT DEFAULT '/project', workspace_kind TEXT DEFAULT 'project',+ extra_dirs TEXT DEFAULT '["/reference"]', writable_dirs TEXT DEFAULT '["/output"]', updated_at INTEGER DEFAULT 1)`);+ const client = { query: async <T>(sql: string, params: unknown[] = []) => db.prepare(sql).all(...params) as T[] };+ setCurrentDbClient(client as DbClient, 'owner');+ const sync = vi.fn(async (_input: { threadId: string; archived: boolean; remoteHostId?: string; assertCurrent(): void }) => {});+ const prepare = vi.fn(async (_rows: ArchiveSessionRow[]) => true);+ const warn = vi.fn();+ const assertCurrent = vi.fn();+ const canUseRemote = vi.fn(() => true);+ const coordinator = createSessionArchiveSync({+ capture: () => ({ client, assertCurrent }), prepare, sync, warn, canUseRemote, release: vi.fn(async () => {}),+ });+ cleanups.push(() => coordinator.stop());+ const insert = (id: string, kind = 'codex', status = 'archived', sdk = id, remote: string | null = null) => {+ db.prepare('INSERT INTO sessions(id,agent_kind,status,sdk_session_id,remote_host_id) VALUES(?,?,?,?,?)').run(id, kind, status, sdk, remote);+ };+ return { db, client, sync, prepare, warn, assertCurrent, canUseRemote, coordinator, insert };+}++describe('task archive projection', () => {+ it('rechecks an idle active handle without closing it', async () => {+ vi.useFakeTimers();+ const f = fixture();+ f.insert('task', 'codex', 'active');+ const live = { getStatus: () => 'active', isTurnRunning: () => false, closeIfIdle: vi.fn(async () => true) };+ f.prepare.mockImplementation(rows => prepareArchiveSessions(rows, () => live));+ await f.coordinator.request();+ await vi.advanceTimersByTimeAsync(5 * 60_000);+ expect(f.sync).toHaveBeenCalledTimes(2);+ expect(f.sync).toHaveBeenLastCalledWith(expect.objectContaining({ archived: false }));+ expect(live.closeIfIdle).not.toHaveBeenCalled();+ });++ it('defers running handles and closes idle archived handles before syncing', async () => {+ const f = fixture();+ f.insert('task');+ const live = { getStatus: () => 'active', isTurnRunning: vi.fn(() => true), closeIfIdle: vi.fn(async () => true) };+ f.prepare.mockImplementation(rows => prepareArchiveSessions(rows, () => live));+ await f.coordinator.request();+ expect(f.sync).not.toHaveBeenCalled();+ expect(live.closeIfIdle).not.toHaveBeenCalled();+ live.isTurnRunning.mockReturnValue(false);+ await f.coordinator.request();+ expect(live.closeIfIdle).toHaveBeenCalledTimes(1);+ expect(f.sync).toHaveBeenCalledTimes(1);+ });++ it.each(['active', 'archived'])('periodically repairs native drift while Cindy stays %s', async status => {+ vi.useFakeTimers();+ const f = fixture();+ f.insert('task', 'codex', status);+ let nativeArchived = status !== 'archived';+ f.sync.mockImplementation(async input => { nativeArchived = input.archived; });+ await f.coordinator.request();+ expect(nativeArchived).toBe(status === 'archived');++ // Another native client changes the thread; Cindy's row is unchanged.+ nativeArchived = !nativeArchived;+ await vi.advanceTimersByTimeAsync(60_000);+ expect(f.sync).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(4 * 60_000);+ expect(f.sync).toHaveBeenCalledTimes(2);+ expect(nativeArchived).toBe(status === 'archived');+ expect(f.db.prepare('SELECT status FROM sessions').get()).toEqual({ status });+ });++ it('backfills Codex, restores it, and preserves all three harnesses and directory scopes', async () => {+ const f = fixture();+ for (const kind of ['cc', 'codex', 'pi']) f.insert(kind, kind);+ const before = f.db.prepare('SELECT * FROM sessions ORDER BY id').all();+ await f.coordinator.request();+ expect(f.sync).toHaveBeenCalledTimes(1);+ expect(f.sync).toHaveBeenLastCalledWith(expect.objectContaining({ threadId: 'codex', archived: true }));+ expect(f.db.prepare('SELECT * FROM sessions ORDER BY id').all()).toEqual(before);+ await f.coordinator.request();+ expect(f.sync).toHaveBeenCalledTimes(1);+ f.db.prepare("UPDATE sessions SET status='active' WHERE id='codex'").run();+ await f.coordinator.request();+ expect(f.sync).toHaveBeenLastCalledWith(expect.objectContaining({ threadId: 'codex', archived: false }));+ expect(f.db.prepare('SELECT working_dir,extra_dirs,writable_dirs FROM sessions WHERE id=?').get('codex'))+ .toEqual({ working_dir: '/project', extra_dirs: '["/reference"]', writable_dirs: '["/output"]' });+ });++ it('retries busy and failed records without repeating successful work', async () => {+ const f = fixture();+ f.insert('a'); f.insert('b');+ f.prepare.mockResolvedValueOnce(false);+ f.sync.mockRejectedValueOnce(new Error('offline'));+ await f.coordinator.request();+ expect(f.warn).toHaveBeenCalledWith(1);+ await f.coordinator.request();+ expect(f.sync).toHaveBeenCalledTimes(3);+ await f.coordinator.request();+ expect(f.sync).toHaveBeenCalledTimes(3);+ });++ it('protects active references sharing a thread, and keeps SSH identities separate', async () => {+ const f = fixture();+ f.insert('a', 'codex', 'archived', 'thread');+ f.insert('b', 'codex', 'active', 'thread');+ f.insert('c', 'codex', 'archived', 'thread', 'remote');+ f.insert('d', 'codex', 'deleted');+ f.canUseRemote.mockReturnValue(false);+ await f.coordinator.request();+ expect(f.sync).toHaveBeenCalledTimes(1);+ expect(f.sync).toHaveBeenCalledWith(expect.objectContaining({ threadId: 'thread', archived: false }));+ f.canUseRemote.mockReturnValue(true);+ await f.coordinator.request();+ expect(f.sync).toHaveBeenLastCalledWith(expect.objectContaining({ threadId: 'thread', archived: true, remoteHostId: 'remote' }));+ });++ it('stops a backfill when the owner changes', async () => {+ const f = fixture(); f.insert('a'); f.insert('b');+ f.sync.mockImplementationOnce(async () => { f.assertCurrent.mockImplementation(() => { throw new Error('changed'); }); });+ await f.coordinator.request();+ expect(f.sync).toHaveBeenCalledTimes(1);+ });++ it.each(['cc', 'codex'] as const)('overlays %s archive and project scope onto CLI scan results', async kind => {+ const f = fixture(); f.insert('task', kind, 'archived', 'native');+ const candidate = { id: 'native', cwd: '/old-project', archived: false };+ expect(await projectNativeSessionMetadata(kind, [candidate])).toEqual([+ { ...candidate, archived: true, cwd: '/project', workspaceKind: 'project', extraDirs: ['/reference'], writableDirs: ['/output'] },+ ]);+ f.db.prepare("UPDATE sessions SET status='active'").run();+ expect(await projectNativeSessionMetadata(kind, [{ ...candidate, archived: true }])).toEqual([+ expect.objectContaining({ archived: false }),+ ]);+ f.db.prepare("UPDATE sessions SET status='deleted'").run();+ expect(await projectNativeSessionMetadata(kind, [candidate])).toEqual([candidate]);+ });++ it('does not overlay another harness or SSH task with an identical native ID', async () => {+ const f = fixture(); f.insert('cc', 'cc', 'archived', 'same'); f.insert('remote', 'codex', 'archived', 'same', 'ssh');+ const candidate = { id: 'same', cwd: '/cli', archived: false };+ expect(await projectNativeSessionMetadata('codex', [candidate])).toEqual([candidate]);+ });+});diff --git a/apps/desktop/src/main/maker-host/claude-local-sessions.ts b/apps/desktop/src/main/maker-host/claude-local-sessions.tsindex d8c6e9b622..39be2edcf6 100644--- a/apps/desktop/src/main/maker-host/claude-local-sessions.ts+++ b/apps/desktop/src/main/maker-host/claude-local-sessions.ts@@ -7,6 +7,7 @@* continues to consume the existing Session/Message contracts.*/+import { projectNativeSessionMetadata, type NativeSessionScope } from './native-session-metadata.js';import fs from 'node:fs';import { promises as fsp } from 'node:fs';import { createReadStream } from 'node:fs';@@ -105,7 +106,7 @@ export interface ClaudeCodeExternalImportResult {updated: number;}-export interface ClaudeCodeExternalSessionCandidate {+export interface ClaudeCodeExternalSessionCandidate extends NativeSessionScope {source: 'claude';id: string;title: string;@@ -155,7 +156,7 @@ export async function scanExternalClaudeCodeSessions(});}}- return { roots, candidates, rejectedCount };+ return { roots, candidates: await projectNativeSessionMetadata('cc', candidates), rejectedCount };}/** Import the selected external Claude Code sessions into xdt-maker's session table. */@@ -570,8 +571,8 @@ async function upsertLocalSession(summary: ClaudeCodeSessionSummary): Promise<'i-- 令牌统计会停留在首次导入的旧快照,与当前源会话不一致;updated_at 同时-- 收敛回源值,后续同步不再被删除时刻挡住。非删除行为完全不变。title = CASE WHEN sessions.status = 'deleted' OR sessions.updated_at <= excluded.updated_at THEN excluded.title ELSE sessions.title END,- working_dir = CASE WHEN sessions.status = 'deleted' OR sessions.updated_at <= excluded.updated_at THEN excluded.working_dir ELSE sessions.working_dir END,- workspace_kind = excluded.workspace_kind,+ working_dir = CASE WHEN sessions.status = 'archived' THEN sessions.working_dir WHEN sessions.status = 'deleted' OR sessions.updated_at <= excluded.updated_at THEN excluded.working_dir ELSE sessions.working_dir END,+ workspace_kind = CASE WHEN sessions.status = 'archived' THEN sessions.workspace_kind ELSE excluded.workspace_kind END,model = CASE WHEN sessions.status = 'deleted' OR sessions.updated_at <= excluded.updated_at THEN excluded.model ELSE sessions.model END,permission_mode = CASE WHEN sessions.status = 'deleted' OR sessions.updated_at <= excluded.updated_at THEN excluded.permission_mode ELSE sessions.permission_mode END,sdk_session_id = excluded.sdk_session_id,diff --git a/apps/desktop/src/main/maker-host/codex-local-sessions.ts b/apps/desktop/src/main/maker-host/codex-local-sessions.tsindex 2cd71643e7..557e2f5034 100644--- a/apps/desktop/src/main/maker-host/codex-local-sessions.ts+++ b/apps/desktop/src/main/maker-host/codex-local-sessions.ts@@ -6,6 +6,8 @@* "prepare this thread before resume" hook.*/+import { projectNativeSessionMetadata, type NativeSessionScope } from './native-session-metadata.js';+import { historyHomeForRollout } from './codex-thread-locations.js';import { app } from 'electron';import { atomicWriteFileSync } from '../utils/atomicWriteFile';import type Database from 'better-sqlite3';@@ -16,6 +18,7 @@ import { randomUUID } from 'node:crypto';import os from 'node:os';import path from 'node:path';import readline from 'node:readline';+import { parse as parseToml } from 'smol-toml';import {allUserDataDirNames,@@ -338,7 +341,7 @@ export interface CodexExternalImportResult {updated: number;}-export interface CodexExternalSessionCandidate {+export interface CodexExternalSessionCandidate extends NativeSessionScope {source: 'codex';id: string;title: string;@@ -401,7 +404,7 @@ export async function scanExternalCodexSessions(): Promise<CodexExternalScanResu}}}- return { homes, candidates: [...candidatesById.values()], rejectedCount };+ return { homes, candidates: await projectNativeSessionMetadata('codex', [...candidatesById.values()]), rejectedCount };}/** Import the selected external Codex sessions into xdt-maker's session table. */@@ -420,6 +423,36 @@ export async function importExternalCodexSessions(threadIds: string[]): Promise<return out;}+/** Locate existing history without adopting, copying or reconstructing it. */+export function readCodexThreadStorageForArchive(threadId: string): {+ historyHome: string; sqliteHome: string; rolloutPath: string;+} | undefined {+ if (!isLikelyThreadId(threadId)) return;+ // External discovery deliberately excludes our current home. Legacy/local+ // tasks without a location record must still resolve their original storage.+ const thread = findThreadByIdInHome(getDesktopCodexHome(), threadId)+ ?? findExternalThreadById(threadId);+ if (!thread) return;+ // An actual thread row establishes storage ownership even if config changed+ // afterward. Consult current config only for the pure rollout fallback.+ let sqliteHome = thread.sourceDbPath ? path.dirname(thread.sourceDbPath) : thread.sourceHome;+ if (!thread.sourceDbPath) {+ let config: Record<string, unknown>;+ try { config = parseToml(fs.readFileSync(path.join(thread.sourceHome, 'config.toml'), 'utf8')); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ config = {};+ }+ if (config.sqlite_home !== undefined && typeof config.sqlite_home !== 'string') {+ throw new Error('Invalid Codex sqlite_home');+ }+ if (typeof config.sqlite_home === 'string') sqliteHome = path.resolve(thread.sourceHome, config.sqlite_home);+ }+ return { historyHome: historyHomeForRollout(thread.rolloutPath),+ sqliteHome,+ rolloutPath: thread.rolloutPath };+}+/** 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> {if (!isLikelyThreadId(threadId)) return;@@ -4881,17 +4914,15 @@ async function upsertLocalSession(thread: CodexThreadSummary): Promise<'inserted-- 复活语义(#3548,与 claude 侧同口径):旧行已软删时按全新导入对待,-- 元数据与 updated_at 一并收敛回源值,不残留删除时刻的旧快照。title = CASE WHEN sessions.status = 'deleted' OR sessions.updated_at <= excluded.updated_at THEN excluded.title ELSE sessions.title END,- working_dir = CASE WHEN sessions.status = 'deleted' OR sessions.updated_at <= excluded.updated_at THEN excluded.working_dir ELSE sessions.working_dir END,- -- Classification follows Codex global state, not local edit recency.- -- This lets a re-import fix rows previously misclassified as projects- -- while preserving newer local title/metadata via the CASE clauses.- workspace_kind = excluded.workspace_kind,+ working_dir = CASE WHEN sessions.status = 'archived' THEN sessions.working_dir WHEN sessions.status = 'deleted' OR sessions.updated_at <= excluded.updated_at THEN excluded.working_dir ELSE sessions.working_dir END,+ -- Active imports follow native classification; archived tasks retain the+ -- project and directory scope they must restore with.+ workspace_kind = CASE WHEN sessions.status = 'archived' THEN sessions.workspace_kind ELSE excluded.workspace_kind END,model = CASE WHEN sessions.status = 'deleted' OR sessions.updated_at <= excluded.updated_at THEN excluded.model ELSE sessions.model END,effort = CASE WHEN sessions.status = 'deleted' OR sessions.updated_at <= excluded.updated_at THEN excluded.effort ELSE sessions.effort END,permission_mode = CASE WHEN sessions.status = 'deleted' OR sessions.updated_at <= excluded.updated_at THEN excluded.permission_mode ELSE sessions.permission_mode END,status = CASEWHEN sessions.status = 'deleted' THEN excluded.status- WHEN sessions.updated_at <= excluded.updated_at THEN excluded.statusELSE sessions.statusEND,sdk_session_id = excluded.sdk_session_id,diff --git a/apps/desktop/src/main/maker-host/codex-thread-locations.ts b/apps/desktop/src/main/maker-host/codex-thread-locations.tsindex 478bacf677..7d4bdf70db 100644--- a/apps/desktop/src/main/maker-host/codex-thread-locations.ts+++ b/apps/desktop/src/main/maker-host/codex-thread-locations.ts@@ -107,7 +107,7 @@ export class CodexThreadLocations {}}-function historyHomeForRollout(rollout: string): string {+export function historyHomeForRollout(rollout: string): string {for (let dir = path.dirname(rollout); path.dirname(dir) !== dir; dir = path.dirname(dir)) {if (['sessions', 'archived_sessions'].includes(path.basename(dir))) return path.dirname(dir);}diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 59bc65be68..f6687ce928 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -19,6 +19,9 @@ import { clearCodexAccountUsageSnapshot } from '../usageBroadcaster.js';import { createMediaDownloadContext } from '../cindy-media/mediaDownloadApproval.js';import { isCodexAccountProvider, codexAccountHome, setCodexAccountRetirement } from './codex-account-auth.js';import { CodexThreadLocations } from './codex-thread-locations.js';+import { createSessionArchiveSync, prepareArchiveSessions } from './session-archive-sync.js';+import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';+import { setSessionArchiveSyncRequester } from '../localDb/sessionArchiveSync.js';import { getActiveAppSession, activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';import { remoteCodexProvider } from './ssh-codex-models.js';import { getActiveAuthRealm } from '../authManager.js';@@ -341,7 +344,7 @@ import {} from '../process-monitor/codex-process-registry.js';import { getOutboundPathSnapshotFor } from './outbound-proxy-resolver.js';import { createDesktopMakerMemoryManager, attachAgentsToMakerMemory } from './maker-memory-host.js';-import { prepareExternalCodexSessionForResume } from './codex-local-sessions.js';+import { prepareExternalCodexSessionForResume, readCodexThreadStorageForArchive } from './codex-local-sessions.js';import {rehydrateCloseSuppression,withRehydrateCloseSuppressed,@@ -499,6 +502,7 @@ export function refreshProviderAccessAfterAuthChange(): void {* api_key 变更时 dispose 重建 app-server。getMaker() 构造后回填,resetMaker() 清空。*/let _codexAgent: CodexAgent | null = null;+let _sessionArchiveSync: ReturnType<typeof createSessionArchiveSync> | null = null;/*** Actual provider array references, shared by runtime catalogs and the lazy Codex bridge.* Custom MCP refresh mutates these arrays in place; resetMaker drops every reference.@@ -1961,10 +1965,13 @@ export function getMaker(): Maker {const locations = new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations'));return locations.prepareResume(threadId, prepareExternalCodexSessionForResume);},- resolveCodexThreadStorage: async (threadId) => {- if (!getActiveAppSession().dataOwnerId) return;+ resolveCodexThreadStorage: async (threadId, options) => {+ if (!getActiveAppSession().dataOwnerId) return options?.readOnly ? readCodexThreadStorageForArchive(threadId) : undefined;const ownerScope = activeOwnerScopeKey();- const storage = await new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations')).readStorage(threadId, {+ const locations = new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations'));+ const storage = options?.readOnly+ ? await locations.readStorage(threadId) ?? readCodexThreadStorageForArchive(threadId)+ : await locations.readStorage(threadId, {home: getCodexHome(),prepare: prepareExternalCodexSessionForResume,});@@ -2838,6 +2845,27 @@ export function getMaker(): Maker {// 为 false —— 一次性调用会被 skipped-unauthed 白白消费掉唯一机会。授权就绪后的重试// 由 codex auth 事件驱动(见下方 requestCodexModelBackfill 的调用点)。const makerRef = _maker;+ _sessionArchiveSync = createSessionArchiveSync({+ capture: () => {+ const snapshot = getCurrentDbClientSnapshot();+ if (!snapshot) throw new Error('Archive sync database is not ready');+ const owner = activeOwnerScopeKey();+ return { client: snapshot.client, assertCurrent: () => {+ if (_maker !== makerRef || _codexAgent !== codexAgent || isAppSessionBoundaryPending()+ || activeOwnerScopeKey() !== owner || getCurrentDbClientSnapshot() !== snapshot) {+ throw new Error('Archive sync owner changed');+ }+ } };+ },+ prepare: (rows) => prepareArchiveSessions(rows, id => makerRef.getSession(id)),+ canUseRemote: (id) => getRemoteSshPool().get(id)?.getStatus() === 'ready',+ sync: (input) => codexAgent.syncThreadArchiveState(input),+ release: () => codexAgent.releaseArchiveHosts(),+ warn: (failures) => desktopMakerLogger.warn('native archive sync deferred', { failures }),+ });+ const archiveSync = _sessionArchiveSync;+ setSessionArchiveSyncRequester(() => { void archiveSync.request(); });+ void archiveSync.request();_codexModelBackfill = createCodexModelBackfillCoordinator({hasCodexLogin: () => desktopCodexAuthAdapter.hasCodexOAuthLogin(),hasCodexModels: () =>@@ -2973,6 +3001,9 @@ export async function preflightBotRuntimeResources(* 重置 Maker 单例(切账号 / 测试用)。*/export function resetMaker(): void {+ _sessionArchiveSync?.stop();+ _sessionArchiveSync = null;+ setSessionArchiveSyncRequester(null);cancelCodexAuthModeChange();setCodexAppliedCustomProviderRoutes([]);_maker = null;diff --git a/apps/desktop/src/main/maker-host/native-session-metadata.ts b/apps/desktop/src/main/maker-host/native-session-metadata.tsnew file mode 100644index 0000000000..da621e9f9a--- /dev/null+++ b/apps/desktop/src/main/maker-host/native-session-metadata.ts@@ -0,0 +1,45 @@+import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';++export interface NativeSessionScope {+ workspaceKind?: 'project' | 'dialogue';+ extraDirs?: string[];+ writableDirs?: string[];+}++/** CLI metadata has no knowledge of Cindy archive and project choices. Overlay+ * only local, non-deleted tasks from the currently bound database; never infer+ * extra-directory permissions from a transcript's cwd.+ */+export async function projectNativeSessionMetadata<T extends { id: string; cwd: string; archived: boolean }>(+ agentKind: 'cc' | 'codex', candidates: T[],+): Promise<Array<T & NativeSessionScope>> {+ const snapshot = getCurrentDbClientSnapshot();+ if (!snapshot || candidates.length === 0) return candidates;+ type Row = { sdkSessionId: string; status: string; workingDir: string | null;+ workspaceKind: 'project' | 'dialogue'; extraDirs: string; writableDirs: string };+ const byId = new Map<string, Row>();+ const ids = [...new Set(candidates.map(candidate => candidate.id))];+ for (let offset = 0; offset < ids.length; offset += 200) {+ const batch = ids.slice(offset, offset + 200);+ const rows = await snapshot.client.query<Row>(`SELECT sdk_session_id AS sdkSessionId,+ status, working_dir AS workingDir, workspace_kind AS workspaceKind,+ extra_dirs AS extraDirs, writable_dirs AS writableDirs FROM sessions+ WHERE agent_kind = ? AND remote_host_id IS NULL AND status IN ('active', 'archived')+ AND sdk_session_id IN (${batch.map(() => '?').join(',')})+ ORDER BY CASE status WHEN 'active' THEN 0 ELSE 1 END, updated_at DESC, id`, [agentKind, ...batch]);+ if (getCurrentDbClientSnapshot() !== snapshot) throw new Error('Native session metadata owner changed');+ for (const row of rows) if (!byId.has(row.sdkSessionId)) byId.set(row.sdkSessionId, row);+ }+ return candidates.map(candidate => {+ const row = byId.get(candidate.id);+ return row ? { ...candidate, archived: row.status === 'archived', cwd: row.workingDir ?? candidate.cwd,+ workspaceKind: row.workspaceKind, extraDirs: parseDirs(row.extraDirs), writableDirs: parseDirs(row.writableDirs) } : candidate;+ });+}++function parseDirs(raw: string): string[] {+ try {+ const value: unknown = JSON.parse(raw);+ return Array.isArray(value) && value.every(item => typeof item === 'string') ? value : [];+ } catch { return []; }+}diff --git a/apps/desktop/src/main/maker-host/session-archive-sync.ts b/apps/desktop/src/main/maker-host/session-archive-sync.tsnew file mode 100644index 0000000000..178dc25fd4--- /dev/null+++ b/apps/desktop/src/main/maker-host/session-archive-sync.ts@@ -0,0 +1,131 @@+import type { DbClient } from '../localDb/client/DbClient.js';+import { withSessionRouteLocks } from '../localDb/sessionRouteLock.js';++export interface ArchiveSessionRow {+ id: string;+ sdkSessionId: string;+ remoteHostId: string | null;+ status: 'active' | 'archived';+}++const SELECT = `SELECT id, sdk_session_id AS sdkSessionId, remote_host_id AS remoteHostId, status+ FROM sessions WHERE agent_kind = 'codex' AND sdk_session_id IS NOT NULL+ AND status IN ('active', 'archived')`;++const NATIVE_RECHECK_MS = 5 * 60_000;++/** Keep idle active handles available to their native writer; only archived+ * handles need closing before the native archive operation. Called under route locks. */+export async function prepareArchiveSessions(+ rows: ArchiveSessionRow[],+ getSession: (id: string) => {+ getStatus(): string; isTurnRunning(): boolean; closeIfIdle(): Promise<boolean>;+ } | undefined,+): Promise<boolean> {+ const live = rows.map(row => getSession(row.id))+ .filter((session): session is NonNullable<typeof session> => session !== undefined && session.getStatus() !== 'closed');+ if (live.some(session => session.isTurnRunning())) return false;+ if (rows.some(row => row.status === 'active')) return true;+ for (const session of live) if (!await session.closeIfIdle()) return false;+ return true;+}++/** Reconcile native storage without changing Cindy metadata or interrupting live work.+ * The database is the durable retry source; no second status store or schema is needed.+ */+export function createSessionArchiveSync(deps: {+ capture(): { client: Pick<DbClient, 'query'>; assertCurrent(): void };+ prepare(rows: ArchiveSessionRow[]): Promise<boolean>;+ canUseRemote(hostId: string): boolean;+ sync(input: { threadId: string; archived: boolean; remoteHostId?: string; assertCurrent(): void }): Promise<void>;+ release(): Promise<void>;+ warn(failures: number): void;+}) {+ const applied = new Map<string, { signature: string; checkedAt: number }>();+ let stopped = false;+ let pending = false;+ let running: Promise<void> | undefined;+ let timer: ReturnType<typeof setTimeout> | undefined;++ async function reconcile(): Promise<void> {+ const scope = deps.capture();+ const assertCurrent = () => {+ if (stopped) throw new Error('Archive sync stopped');+ scope.assertCurrent();+ };+ const rows = await scope.client.query<ArchiveSessionRow>(SELECT);+ assertCurrent();+ const groups = new Map<string, ArchiveSessionRow[]>();+ for (const row of rows) {+ const key = JSON.stringify([row.remoteHostId, row.sdkSessionId]);+ const group = groups.get(key) ?? [];+ group.push(row);+ groups.set(key, group);+ }+ for (const key of applied.keys()) if (!groups.has(key)) applied.delete(key);+ let failures = 0;+ for (const [key, group] of groups) {+ assertCurrent();+ const signature = JSON.stringify(group.map(row => [row.id, row.status]).sort());+ const previous = applied.get(key);+ // Native CLI actions can change storage without updating Cindy. Bound the+ // cache lifetime, while avoiding a full native scan on every UI mutation.+ if (previous?.signature === signature && Date.now() - previous.checkedAt < NATIVE_RECHECK_MS) continue;+ const first = group[0]!;+ if (first.remoteHostId && !deps.canUseRemote(first.remoteHostId)) continue;+ try {+ await withSessionRouteLocks(group.map(row => row.id), async () => {+ const current = await scope.client.query<ArchiveSessionRow>(+ `${SELECT} AND sdk_session_id = ? AND remote_host_id IS ?`,+ [first.sdkSessionId, first.remoteHostId],+ );+ assertCurrent();+ // A copied task can share a native ID. Active references win; a changed+ // group is retried under its complete set of locks on the next pass.+ const currentSignature = JSON.stringify(current.map(row => [row.id, row.status]).sort());+ if (currentSignature !== signature || !await deps.prepare(current)) return;+ assertCurrent();+ await deps.sync({+ threadId: first.sdkSessionId,+ archived: current.every(row => row.status === 'archived'),+ ...(first.remoteHostId ? { remoteHostId: first.remoteHostId } : {}),+ assertCurrent,+ });+ assertCurrent();+ applied.set(key, { signature, checkedAt: Date.now() });+ });+ } catch {+ assertCurrent();+ failures++;+ }+ }+ if (failures) deps.warn(failures);+ }++ function request(): Promise<void> {+ if (stopped) return Promise.resolve();+ pending = true;+ if (running) return running;+ if (timer) clearTimeout(timer);+ running = (async () => {+ do {+ pending = false;+ try { await reconcile(); } catch { if (!stopped) deps.warn(1); }+ } while (pending && !stopped);+ try { await deps.release(); } catch { if (!stopped) deps.warn(1); }+ })().finally(() => {+ running = undefined;+ if (!stopped) {+ // Also covers internal lifecycle writers and retries after a busy task,+ // offline SSH target, unavailable credentials or an interrupted backfill.+ timer = setTimeout(() => { void request(); }, pending ? 0 : 60_000);+ timer.unref?.();+ }+ });+ return running;+ }+ return {+ request,+ stop() { stopped = true; if (timer) clearTimeout(timer); },+ };+}diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex 6221cb5250..9f10834f5d 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -107,6 +107,13 @@ Codex 跨凭证优先保留同一个原生线程;仅当目标需要另一个 h本地恢复与分叉必须同时固定该线程的原生历史根(`CODEX_HOME`,含 `sessions` / `archived_sessions`)和数据库根(`sqlite_home`);仅固定 SQLite 不足以恢复分页祖先,原生按不可变 rollout ID 在历史根内查找祖先。+归档状态以 Cindy 的 `sessions.status` 为准。Codex 经原生 `thread/archive` /+`thread/unarchive` 同步历史位置与索引,成功后更新线程位置记录;禁止直接改原生 SQLite+或搬动 rollout,也不能为归档触发历史复制/重建。启动时补齐存量状态,忙碌任务、离线+SSH 或暂时失败留待重试;共享原生 ID 的活动任务优先,不关闭其他任务的进程。同步必须+持有任务路由锁并验证当前 owner,使用原历史根与数据库根。Claude Code 与 Pi 当前没有+原生归档接口,保持 Cindy 状态;历史扫描及重新导入不得覆盖 Cindy 的归档与归档任务的+项目目录、额外目录及可写目录范围。手机远控复用宿主同一状态写入路径。凭证、代理路由和模型目录仍按本轮选中账号准备,不能把历史根写回全局账号配置。跨历史根的原生进程从启动参数要求 `cli_auth_credentials_store="ephemeral"`,清除继承的原生身份环境变量;OAuth 通过独立的 external-auth adapter 在进程内安装目标账号 token,diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex abc82f4a66..8b8c6c4228 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -1328,7 +1328,8 @@ 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; rolloutPath?: string } | undefined>;+ /** readOnly locates existing storage without invoking resume recovery or copying history. */+ resolveCodexThreadStorage?: (threadId: string, options?: { readOnly?: boolean }) => 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.tsindex 756e57bb90..cb9ba2cfad 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@@ -3,6 +3,7 @@ import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';import { randomUUID } from 'node:crypto';+import { syncCodexArchiveState } from '../archive-state.js';import { createServer, type Server } from 'node:http';import { afterEach, describe, expect, it } from 'vitest';import { AppServerHost } from './host.js';@@ -146,6 +147,39 @@ async function fixture(archivedParent = false, testRefresh = false, revokedRefre}describe.skipIf(!binaryPath)('real Codex history/account isolation contract', () => {+ it('archives and restores native history without changing cwd or losing content', async () => {+ const f = await fixture();+ const native = f.host(f.historyHome);+ const started = await native.request<{ thread: { id: string; path: string } }>('thread/start', {+ cwd: f.root, model: 'gpt-6-astra', approvalPolicy: 'never', sandbox: 'read-only',+ });+ const thread = started.thread;+ const completed = new Promise<void>(resolve => {+ native.subscribeThread(thread.id, { turnCompleted: () => resolve() });+ });+ await native.request('turn/start', { threadId: thread.id, input: [{ type: 'text', text: 'archive fixture' }] });+ await completed;+ await native.unsubscribeThread(thread.id);+ const contents = await fs.readFile(thread.path, 'utf8');+ const request: Parameters<typeof syncCodexArchiveState>[0] = (method, params) => native.request(method, params);+ const archived = await syncCodexArchiveState(request, thread.id, true, () => {});+ expect(archived.split(path.sep)).toContain('archived_sessions');+ await expect(fs.stat(thread.path)).rejects.toMatchObject({ code: 'ENOENT' });+ expect(await fs.readFile(archived, 'utf8')).toBe(contents);+ const archivedList = await native.request<{ data: Array<{ id: string }> }>('thread/list', { archived: true, limit: 100 });+ expect(archivedList.data.map(item => item.id)).toContain(thread.id);+ expect(await syncCodexArchiveState(request, thread.id, true, () => {})).toBe(archived);+ const restored = await syncCodexArchiveState(request, thread.id, false, () => {});+ expect(restored.split(path.sep)).toContain('sessions');+ expect(await fs.readFile(restored, 'utf8')).toBe(contents);+ const activeList = await native.request<{ data: Array<{ id: string }> }>('thread/list', { archived: false, limit: 100 });+ expect(activeList.data.map(item => item.id)).toContain(thread.id);+ await expect(f.resume(native, { id: thread.id, file: restored })).resolves.toMatchObject({+ thread: { id: thread.id, cwd: f.root },+ });+ await f.assertOriginals();+ }, 30_000);+it('reproduces the old split-home defect with a complete source rollout still on disk', async () => {const f = await fixture();const original = f.host(f.historyHome);diff --git a/packages/maker-core/src/agents/codex/archive-state.test.ts b/packages/maker-core/src/agents/codex/archive-state.test.tsnew file mode 100644index 0000000000..131e243dcb--- /dev/null+++ b/packages/maker-core/src/agents/codex/archive-state.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it, vi } from 'vitest';+import { syncCodexArchiveState } from './archive-state.js';++describe('native archive projection', () => {+ it.each(['/', '\\'])('uses the closest storage bucket beneath a same-named ancestor (%s)', async separator => {+ let archived = false;+ const request = vi.fn(async (method: string) => {+ if (method === 'thread/archive') archived = true;+ if (method === 'thread/unarchive') archived = false;+ return { thread: { id: 'thread', path: ['root', 'archived_sessions', 'codex',+ archived ? 'archived_sessions' : 'sessions', '2026', '09', 'history.jsonl'].join(separator) } };+ });+ const invoke = request as Parameters<typeof syncCodexArchiveState>[0];+ await syncCodexArchiveState(invoke, 'thread', false, () => {});+ expect(request).toHaveBeenCalledTimes(1);+ await syncCodexArchiveState(invoke, 'thread', true, () => {});+ expect(request).toHaveBeenCalledWith('thread/archive', { threadId: 'thread' });+ await syncCodexArchiveState(invoke, 'thread', false, () => {});+ expect(request).toHaveBeenCalledWith('thread/unarchive', { threadId: 'thread' });+ });++ it.each(['/', '\\'])('archives and restores through native APIs with %s paths', async separator => {+ let archived = false;+ const request = vi.fn(async (method: string) => {+ if (method === 'thread/archive') archived = true;+ if (method === 'thread/unarchive') archived = false;+ return { thread: { id: 'thread', path: ['root', archived ? 'archived_sessions' : 'sessions', 'history.jsonl'].join(separator) } };+ });+ const invoke = request as Parameters<typeof syncCodexArchiveState>[0];+ const archivedPath = await syncCodexArchiveState(invoke, 'thread', true, () => {});+ expect(archivedPath).toContain('archived_sessions');+ await syncCodexArchiveState(invoke, 'thread', true, () => {});+ expect(request.mock.calls.filter(([method]) => method === 'thread/archive')).toHaveLength(1);+ expect(await syncCodexArchiveState(invoke, 'thread', false, () => {})).not.toContain('archived_sessions');+ expect(request.mock.calls.filter(([method]) => method === 'thread/unarchive')).toHaveLength(1);+ expect(request).toHaveBeenCalledWith('thread/read', { threadId: 'thread', includeTurns: false });+ });++ it('rejects stale ownership before any native mutation', async () => {+ const request = vi.fn(async () => ({ thread: { id: 't', path: '/sessions/history.jsonl' } }));+ await expect(syncCodexArchiveState(request as Parameters<typeof syncCodexArchiveState>[0], 't', true,+ () => { throw new Error('owner changed'); })).rejects.toThrow('owner changed');+ expect(request).toHaveBeenCalledTimes(1);+ });++ it('does not archive a running native thread', async () => {+ const request = vi.fn(async () => ({ thread: { id: 't', path: '/sessions/history.jsonl', status: { type: 'active' } } }));+ await expect(syncCodexArchiveState(request as Parameters<typeof syncCodexArchiveState>[0], 't', true, () => {}))+ .rejects.toThrow('busy');+ expect(request).toHaveBeenCalledTimes(1);+ });++ it('does not claim success when native storage did not change', async () => {+ const request = vi.fn(async () => ({ thread: { id: 't', path: '/sessions/history.jsonl' } }));+ await expect(syncCodexArchiveState(request as Parameters<typeof syncCodexArchiveState>[0], 't', true, () => {}))+ .rejects.toThrow('did not converge');+ });+});diff --git a/packages/maker-core/src/agents/codex/archive-state.ts b/packages/maker-core/src/agents/codex/archive-state.tsnew file mode 100644index 0000000000..835604bdd8--- /dev/null+++ b/packages/maker-core/src/agents/codex/archive-state.ts@@ -0,0 +1,28 @@+/** Native archive owns both the rollout move and SQLite update. Never edit either here. */+export async function syncCodexArchiveState(+ request: <T>(method: string, params: Record<string, unknown>) => Promise<T>,+ threadId: string,+ archived: boolean,+ assertCurrent: () => void,+): Promise<string> {+ type ThreadResult = { thread: { id: string; path?: string | null; status?: { type: string } } };+ const read = () => request<ThreadResult>('thread/read', { threadId, includeTurns: false });+ const isArchived = (result: ThreadResult): boolean => {+ if (result.thread.id !== threadId || !result.thread.path) throw new Error('Codex archive history is unavailable');+ // Native SSH paths use the remote platform's separators.+ const bucket = result.thread.path.split(/[\\/]/).slice(0, -1).reverse()+ .find(part => part === 'sessions' || part === 'archived_sessions');+ if (!bucket) throw new Error('Codex archive history storage is unavailable');+ return bucket === 'archived_sessions';+ };+ let result = await read();+ assertCurrent();+ if (isArchived(result) !== archived) {+ if (result.thread.status?.type === 'active') throw new Error('Codex thread is busy; archive sync deferred');+ await request(archived ? 'thread/archive' : 'thread/unarchive', { threadId });+ result = await read();+ assertCurrent();+ if (isArchived(result) !== archived) throw new Error('Codex archive state did not converge');+ }+ return result.thread.path!;+}diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 157a99d62b..4f425336b8 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -368,6 +368,63 @@ function createDeps(};}+describe('Codex archive synchronization', () => {+ it('uses the retained writer and records the native archive path without closing sibling tasks', async () => {+ const storage = { historyHome: '/history', sqliteHome: '/state' };+ const resolveCodexThreadStorage = vi.fn(async () => storage);+ const recordCodexThreadLocation = vi.fn(async () => {});+ const agent = new CodexAgent(createDeps({}, { resolveCodexThreadStorage, recordCodexThreadLocation }));+ try {+ const source = await agent.startSession({ sessionId: 'source', model: 'gpt-5.4', workingDir: '/repo' });+ const sibling = await agent.startSession({ sessionId: 'sibling', model: 'gpt-5.4', workingDir: '/repo' });+ await source.close();+ const transport = createdTransports[0];+ transport.setMockResponse('thread/loaded/list', { result: { data: [source.id, sibling.id] } });+ let archived = false;+ const write = transport.writeLine.bind(transport);+ vi.spyOn(transport, 'writeLine').mockImplementation(async line => {+ const { method } = JSON.parse(line);+ if (method === 'thread/archive') {+ archived = true;+ transport.setMockResponse(method, { result: {} });+ }+ if (method === 'thread/read') transport.setMockResponse(method, { result: { thread: {+ id: source.id, status: { type: 'idle' },+ path: `/history/${archived ? 'archived_sessions' : 'sessions'}/rollout.jsonl`,+ } } });+ await write(line);+ });++ await agent.syncThreadArchiveState({ threadId: source.id, archived: true, assertCurrent: () => {} });+ await agent.releaseArchiveHosts();+ expect(resolveCodexThreadStorage).toHaveBeenCalledWith(source.id, { readOnly: true });+ expect(recordCodexThreadLocation).toHaveBeenLastCalledWith(source.id, '/state', '/history/archived_sessions/rollout.jsonl');+ expect(createdTransports).toHaveLength(1);+ expect(transport.closed).toBe(false);+ await sibling.close();+ } finally { await agent.dispose(); }+ });++ it('uses a storage-scoped control host for cold history and releases it after the batch', async () => {+ const recordCodexThreadLocation = vi.fn(async () => {});+ MockCodexTransport.onCreate = transport => transport.setMockResponse('thread/read', { result: {+ thread: { id: 'archived-thread', path: '/history/archived_sessions/rollout.jsonl' },+ } });+ const agent = new CodexAgent(createDeps({}, {+ resolveCodexThreadStorage: async () => ({ historyHome: '/history', sqliteHome: '/state' }),+ recordCodexThreadLocation,+ }));+ try {+ await agent.syncThreadArchiveState({ threadId: 'archived-thread', archived: true, assertCurrent: () => {} });+ expect(createdTransports).toHaveLength(1);+ expect(createdStdioOptions[0].extraArgs).toContain('sqlite_home="/state"');+ expect(recordCodexThreadLocation).toHaveBeenCalledWith('archived-thread', '/state', '/history/archived_sessions/rollout.jsonl');+ await agent.releaseArchiveHosts();+ expect(createdTransports[0].closed).toBe(true);+ } finally { await agent.dispose(); }+ });+});+describe('Codex official OAuth host isolation', () => {function isolatedDeps() {return createDeps({}, {diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex b7c72a8667..924ffadbe4 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -26,6 +26,7 @@ import path from 'node:path';import { randomUUID } from 'node:crypto';import { promises as fs } from 'node:fs';import { structuredPatch } from 'diff';+import { syncCodexArchiveState } from './archive-state.js';import {BaseAgent,@@ -1944,6 +1945,73 @@ export class CodexAgent extends BaseAgent {* "1 agent N host" 是 codex 端做不到 "1 server N transport" 的必然后果。*/private hosts = new Map<string, AppServerHost>();+ private archiveHostKeys = new Set<string>();++ /** Project the host's durable task status through Codex's own storage API. */+ async syncThreadArchiveState(opts: {+ threadId: string;+ archived: boolean;+ remoteHostId?: string;+ assertCurrent: () => void;+ }): Promise<void> {+ opts.assertCurrent();+ const storage = opts.remoteHostId ? undefined : await this.deps.resolveCodexThreadStorage?.(opts.threadId, { readOnly: true });+ if (!opts.remoteHostId && this.deps.resolveCodexThreadStorage && !storage) {+ throw new Error('Codex archive storage is unavailable');+ }+ opts.assertCurrent();+ let target: { key: string; host: AppServerHost } | undefined;+ // Unsubscribe does not release the native writer immediately. Use its host+ // when it still owns this thread; never kill a shared host to move a file.+ for (const [key, host] of this.hosts) {+ if (this.archiveHostKeys.has(key) || !host.writerCandidate) continue;+ if (opts.remoteHostId ? key !== hostKey(opts.remoteHostId) : !key.startsWith('local')) continue;+ let cursor: string | null = null;+ do {+ const page: { data: string[]; nextCursor?: string | null } = await host.request(+ 'thread/loaded/list', { cursor }, { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS },+ );+ opts.assertCurrent();+ if (page.data.includes(opts.threadId)) { target = { key, host }; break; }+ cursor = page.nextCursor ?? null;+ } while (cursor);+ if (target) break;+ }+ const key = opts.remoteHostId ? hostKey(opts.remoteHostId)+ : `local:archive:${JSON.stringify(storage ? [storage.historyHome, storage.sqliteHome] : [])}`;+ await this.withHostOperation(async () => {+ opts.assertCurrent();+ if (target && this.hosts.get(target.key) === target.host) return target;+ if (!opts.remoteHostId) this.archiveHostKeys.add(key);+ const host = await this.getHost(opts.remoteHostId, undefined, {+ keyOverride: key, hostPurpose: 'control-plane',+ ...(storage ? { historyHome: storage.historyHome, sqliteHome: storage.sqliteHome } : {}),+ });+ return { key, host };+ }, async (host) => {+ const init = await host.ensureStarted();+ opts.assertCurrent();+ const rollout = await syncCodexArchiveState(+ (method, params) => host.request(method, params, { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS }),+ opts.threadId, opts.archived, opts.assertCurrent,+ );+ opts.assertCurrent();+ if (!opts.remoteHostId) {+ const home = storage?.sqliteHome ?? init.codexHome;+ if (home) await this.deps.recordCodexThreadLocation?.(opts.threadId, home, rollout);+ }+ });+ }++ /** A backfill reuses one control host per storage root, then releases them. */+ async releaseArchiveHosts(): Promise<void> {+ for (const key of this.archiveHostKeys) {+ await this.retireHostKey(key, 'Codex archive sync finished', {+ failIfActive: true, logPrefix: 'codex archive host cleanup', throwOnShutdownFailure: true,+ });+ this.archiveHostKeys.delete(key);+ }+ }/*** getHost() 的 in-flight Promise 去重, per target — 创建过程含 3 个 await