Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): retain custom ancestry sources without stale index writes
DavidShen011359b4fddb
diff --git a/apps/desktop/src/main/__tests__/codexLocalSessions.native.test.ts b/apps/desktop/src/main/__tests__/codexLocalSessions.native.test.tsindex deb3d08cbc..986a2ec05e 100644--- a/apps/desktop/src/main/__tests__/codexLocalSessions.native.test.ts+++ b/apps/desktop/src/main/__tests__/codexLocalSessions.native.test.ts@@ -4,7 +4,7 @@* 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.+ * Windows 0.159.2: 6.31s test body for all six native cases (runtime tier).*/import fs from 'node:fs';import os from 'node:os';@@ -26,7 +26,7 @@ vi.mock('../logger.js', () => ({ createLogger: () => ({ debug() {}, info() {}, wconst 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)(+it.skipIf(!binary).each(['import', 'indexed', 'indexed-reverted', 'lineage', 'indexed-lineage', 'custom-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');@@ -115,6 +115,19 @@ it.skipIf(!binary).each(['import', 'indexed', 'indexed-reverted', 'lineage', 'inawait 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 });+ if (mode === 'custom-lineage') {+ // Existing state can reference history outside every discovery candidate.+ process.env.CODEX_HOME = path.join(root, 'unrelated-home');+ const sourceDbName = fs.readdirSync(sourceHome).find(name => /^state_\d+\.sqlite$/.test(name))!;+ const targetDbName = fs.readdirSync(targetHome).find(name => /^state_\d+\.sqlite$/.test(name))!;+ const sourceDb = new Database(path.join(sourceHome, sourceDbName), { readonly: true });+ const targetDb = new Database(path.join(targetHome, targetDbName));+ try {+ const row = sourceDb.prepare('SELECT * FROM threads WHERE id = ?').get(id) as Record<string, unknown>;+ const columns = Object.keys(row);+ targetDb.prepare(`INSERT INTO threads (${columns.map(column => `"${column}"`).join(',')}) VALUES (${columns.map(() => '?').join(',')})`).run(...columns.map(column => row[column]));+ } finally { sourceDb.close(); targetDb.close(); }+ }let prepared = await prepareExternalCodexSessionForResume(id);expect(path.basename(prepared!)).toBe(filename);if (mode.startsWith('indexed')) {diff --git a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts b/apps/desktop/src/main/__tests__/codexLocalSessions.test.tsindex 73e9fa3e68..34c679dcd7 100644--- a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts+++ b/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts@@ -1574,6 +1574,36 @@ describe('paginated Codex rollout adoption (#7436)', () => {return { ...f, parent, localParent, parentContents, childContents, sourceChild };}+ // #7458 review, unit: an existing SQLite pointer can select a custom source+ // outside discovery. Previously copying the child lost that source on retry.+ it.each([false, true])('imports ancestry from a custom state-pointed root (interrupted: %s)', async interrupted => {+ const f = ancestorHistory();+ const customHome = path.join(rootDir, 'custom-history');+ fs.renameSync(externalHome, customHome);+ const sourceChild = path.join(customHome, path.relative(externalHome, f.sourceChild));+ const parent = path.join(customHome, path.relative(externalHome, f.parent));+ const targetHome = path.join(targetUserData, 'codex-home');+ const dbPath = createStateDb(targetHome);+ insertThread(dbPath, threadId, sourceChild, { updatedAt: 2000 });+ if (interrupted) {+ fs.unlinkSync(parent);+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow('missing paginated');+ const db = new Database(dbPath, { readonly: true });+ try { expect((db.prepare('SELECT rollout_path FROM threads WHERE id = ?').get(threadId) as { rollout_path: string }).rollout_path).not.toBe(sourceChild); }+ finally { db.close(); }+ fs.writeFileSync(parent, f.parentContents);+ }+ const prepared = await prepareExternalCodexSessionForResume(threadId);+ expect(path.basename(prepared!)).toBe(path.basename(f.canonical));+ expect(fs.readFileSync(prepared!, 'utf8')).toBe(f.childContents);+ expect(fs.readFileSync(path.join(targetHome, path.relative(customHome, parent)), 'utf8')).toBe(f.parentContents);+ fs.appendFileSync(prepared!, 'new local turn\n');+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(prepared);+ expect(fs.readFileSync(sourceChild, 'utf8')).toBe(f.childContents);+ expect(fs.readFileSync(parent, 'utf8')).toBe(f.parentContents);+ expect(fs.readFileSync(prepared!, 'utf8')).toContain('new local turn');+ });+it.each(['missing', 'truncated', 'cycle', 'conflict'] as const)('blocks %s ancestry without replacing the selected history or index', async fault => {const f = ancestorHistory();@@ -1698,7 +1728,7 @@ describe('paginated Codex rollout adoption (#7436)', () => {expect(await f.locations.prepareResume(threadId, legacy)).toBe(f.canonical);}expect(legacy).not.toHaveBeenCalled();- expect(await f.locations.read(threadId)).toBe(f.canonical);+ expect(await f.locations.read(threadId)).toBe(f.broken);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);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 d2003c2bae..33d1e1c63a 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,7 +16,7 @@ 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 () => {+ it.each([false, true])('rejects a stale index after asynchronous repair (filename changes: %s)', async renamed => {const { root } = await fixture();const old = path.join(root, 'sessions', 'old.jsonl');const archived = path.join(root, 'archived_sessions', 'old.jsonl');@@ -25,35 +25,33 @@ describe('native thread locations across accounts', () => {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 new CodexThreadLocations(path.join(root, 'locations')).record('thread', archived, root);+ return renamed ? path.join(root, 'sessions', 'repaired.jsonl') : 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.+ // #7436 unit: read-then-rename cannot CAS against another process. Keep the+ // durable alias intact until the normal native lifecycle records its location.// Windows: this file completes in 0.31s, including module collection.- it('does not overwrite a newer location while publishing a repaired index', async () => {+ it('returns the repaired path without replacing the index before native registration', 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');+ await fs.link(old, repaired);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 });+ const before = await fs.readFile(path.join(directory, 'thread.json'), 'utf8');+ expect(await locations.prepareResume('thread', async () => undefined)).toBe(repaired);+ expect(await fs.readFile(path.join(directory, 'thread.json'), 'utf8')).toBe(before);+ const reopened = new CodexThreadLocations(directory, () => repaired);+ expect(await reopened.prepareResume('thread', async () => undefined)).toBe(repaired);+ await reopened.record('thread', repaired, root);+ expect(await locations.readStorage('thread')).toEqual({ historyHome: root, sqliteHome: root, rolloutPath: repaired });});it('keeps the original database home and recovers legacy location records', async () => {diff --git a/apps/desktop/src/main/maker-host/codex-local-sessions.ts b/apps/desktop/src/main/maker-host/codex-local-sessions.tsindex 86618defa0..613d5816ef 100644--- a/apps/desktop/src/main/maker-host/codex-local-sessions.ts+++ b/apps/desktop/src/main/maker-host/codex-local-sessions.ts@@ -645,6 +645,11 @@ async function prepareExternalCodexSessionStorage(threadId: string): Promise<strif (!adopted) {throw resumePreparationBlocked(threadId, 'external rollout changed during private adoption');}+ // Save the exact source before SQLite stops pointing at it. A custom+ // history root need not be discoverable, including after a failed retry.+ if (readPaginatedBase(threadId, adopted.path)) {+ rememberCodexHistorySource(threadId, targetHome, adopted.path, targetRollout);+ }if (handoffThreadToCopiedRollout(targetDbPath,threadId,@@ -1296,6 +1301,20 @@ export async function prepareCodexRolloutForResume(return repairCodexRolloutPath(threadId, rolloutPath, sqliteHome);}+function rememberCodexHistorySource(threadId: string, targetHome: string, rolloutPath: string, sourcePath: string): void {+ const file = `${rolloutPath}.source.json`;+ const contents = JSON.stringify({ sourceHome: historyHomeForRollout(sourcePath), rootLine: readFirstLineSync(rolloutPath) });+ const temporary = `${file}.${randomUUID()}.tmp`;+ try {+ fs.writeFileSync(temporary, contents, { flag: 'wx', mode: 0o600 });+ try { fs.linkSync(temporary, file); }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; }+ if (!readPrivateNonEmptyRolloutSnapshot(targetHome, file) || fs.readFileSync(file, 'utf8') !== contents) {+ throw resumePreparationBlocked(threadId, 'conflicting paginated history source');+ }+ } finally { fs.rmSync(temporary, { force: true }); }+}+async function ensureCodexHistoryAncestors(threadId: string, rolloutPath: string, verifyExternalSource: boolean): Promise<void> {const targetHome = historyHomeForRollout(rolloutPath);const rootSnapshot = readPrivateNonEmptyRolloutSnapshot(targetHome, rolloutPath);@@ -1321,7 +1340,22 @@ async function ensureCodexHistoryAncestors(threadId: string, rolloutPath: stringsearchedSource = 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)+ const sourceFile = `${rolloutPath}.source.json`;+ let candidates: string[];+ if (fs.existsSync(sourceFile)) {+ if (!readPrivateNonEmptyRolloutSnapshot(targetHome, sourceFile)) {+ throw resumePreparationBlocked(threadId, 'unsafe paginated history source');+ }+ const saved: unknown = JSON.parse(fs.readFileSync(sourceFile, 'utf8'));+ if (!isRecord(saved) || typeof saved.sourceHome !== 'string' || !path.isAbsolute(saved.sourceHome)+ || saved.rootLine !== rootLine) {+ throw resumePreparationBlocked(threadId, 'invalid paginated history source');+ }+ candidates = [saved.sourceHome];+ } else {+ candidates = discoverExternalCodexHomesSync();+ }+ const homes = candidates.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');diff --git a/apps/desktop/src/main/maker-host/codex-thread-locations.ts b/apps/desktop/src/main/maker-host/codex-thread-locations.tsindex e8ba3ba87c..77d842584b 100644--- a/apps/desktop/src/main/maker-host/codex-thread-locations.ts+++ b/apps/desktop/src/main/maker-host/codex-thread-locations.ts@@ -1,5 +1,4 @@import fs from 'node:fs/promises';-import { readFileSync, renameSync } from 'node:fs';import path from 'node:path';import { randomUUID } from 'node:crypto';@@ -20,16 +19,14 @@ export class CodexThreadLocations {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 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');}- const next = { ...value, path: repaired };- await this.writeLocation(next, value);- return next;+ // Repair retains the old name as a hard link. Return the native name without+ // writing a stale index over another process's archive/account update.+ // The normal native thread-started callback records its resulting location.+ return { ...value, path: repaired };}private file(threadId: string): string {@@ -119,7 +116,7 @@ export class CodexThreadLocations {await this.writeLocation({ threadId, path: rolloutPath, sqliteHome });}- private async writeLocation(value: ThreadLocation, expected?: ThreadLocation): Promise<void> {+ private async writeLocation(value: ThreadLocation): Promise<void> {const file = this.file(value.threadId);await fs.mkdir(this.directory, { recursive: true, mode: 0o700 });const temporary = `${file}.${randomUUID()}.tmp`;@@ -127,19 +124,7 @@ export class CodexThreadLocations {await fs.writeFile(temporary, JSON.stringify(value), {mode: 0o600,});- 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);- }+ await fs.rename(temporary, file);} finally {await fs.rm(temporary, { force: true });}diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex 2410ebdfe6..20e4bc3b43 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -230,12 +230,15 @@ Codex 跨凭证优先保留同一个原生线程;仅当目标需要另一个 h本机外部 Codex 导入完成历史快照交接后、调用原生恢复前,必须将 paginated 历史的`rollout-cindy-adopted-*` 名称恢复为原生规范文件名(#7436)。保留原名中的 thread ID及可选的独立 rollout ID,不修改历史内容。存量错误路径在已记录的历史根和 SQLite 根内-修复:不覆盖地建立同 inode 的规范名称、条件更新 SQLite 指针,最后更新位置索引;+修复:不覆盖地建立同 inode 的规范名称、条件更新 SQLite 指针,返回规范路径;修复阶段不写位置索引,+避免读取后替换覆盖另一进程的最新记录。旧索引仍能通过同 inode 别名恢复,由正常原生线程登记更新索引;保留旧名称,使中断重试与已打开的 writer 不会丢失追加内容。遇到另一份规范文件或状态已被其它操作切换时明确失败,不覆盖、不重新导入子历史,也不从聊天投影重建。带 `history_base` 的分页历史恢复前必须补齐所引用的完整祖先链,按原生 rollout ID(可能不同于 thread ID)查找,并保留原始字节、序号与归档位置。存量导入缺少祖先时,-仅从与已选子历史的原文件名、首条元数据完全匹配的外部 HOME 补齐;来源不明确、+仅从与已选子历史的原文件名、首条元数据完全匹配的外部 HOME 补齐;已有 SQLite 指针指向自定义目录时,+在交接指针前将来源根与子历史首条元数据原子保存到私有副本旁的 `.source.json`,中断重试仍使用该来源。+来源记录不覆盖,且不能绕过子历史匹配和祖先校验;无记录的旧导入仍走候选目录发现。来源不明确、祖先缺失/越界/循环或已有副本的引用范围冲突时明确失败。已有子历史和祖先的后续追加不被替换;已有祖先仍使用 Cindy 旧文件名时,通过同 inode 规范名称复用,不能另拷贝导致父任务恢复冲突。整链先校验,再从最早祖先开始不覆盖发布,中断可重试。补齐后外部 HOME