Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(codex): 安全恢复空 rollout (#1608)

lilsnake0ee0eaa53aed
diff --git a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts b/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts
index 9f7f261eb2..2ce79ec8a4 100644
--- a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts
+++ b/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts
@@ -50,6 +50,7 @@ let rootDir = '';
let externalHome = '';
let targetUserData = '';
let homedirSpy: { mockRestore: () => void } | null = null;
+let dateNowSpy: { mockRestore: () => void } | null = null;
let originalCodexHome: string | undefined;
function createLocalDb(): Database.Database {
@@ -264,6 +265,8 @@ beforeEach(() => {
});
afterEach(() => {
+ dateNowSpy?.mockRestore();
+ dateNowSpy = null;
homedirSpy?.mockRestore();
homedirSpy = null;
dbMock.current?.close();
@@ -1240,6 +1243,46 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>
.run(`${clientId}-id`, clientId, sessionId, role, content, createdAt);
}
+ function markEmptyRolloutStable(filePath: string): void {
+ const stat = fs.statSync(filePath);
+ const latestIdentityTime = Math.max(
+ stat.mtimeMs,
+ stat.ctimeMs,
+ Number.isFinite(stat.birthtimeMs) && stat.birthtimeMs > 0 ? stat.birthtimeMs : 0,
+ );
+ dateNowSpy?.mockRestore();
+ dateNowSpy = vi.spyOn(Date, 'now').mockReturnValue(latestIdentityTime + 20 * 60_000);
+ }
+
+ function materializeAfterInitialPrivateCanonicalScan(
+ targetSessionsDir: string,
+ materialize: () => void,
+ ): { restore: () => void; didMaterialize: () => boolean } {
+ const realReaddirSync = fs.readdirSync;
+ let targetSessionsScanCount = 0;
+ let materialized = false;
+ const readdirSpy = vi.spyOn(fs, 'readdirSync').mockImplementation((function (
+ directory: fs.PathLike,
+ options?: unknown,
+ ) {
+ if (path.resolve(directory.toString()) === path.resolve(targetSessionsDir)) {
+ targetSessionsScanCount += 1;
+ // The first root scan enforces the grace period. The second belongs to
+ // interrupted-preservation discovery immediately before the state-backed
+ // rescan, which models a writer appearing in that exact preflight gap.
+ if (targetSessionsScanCount === 2) {
+ materialize();
+ materialized = true;
+ }
+ }
+ return Reflect.apply(realReaddirSync, fs, [directory, options]);
+ }) as typeof fs.readdirSync);
+ return {
+ restore: () => readdirSpy.mockRestore(),
+ didMaterialize: () => materialized,
+ };
+ }
+
it('adopts a legacy branded Codex HOME and remains resumable after the old directory is removed', async () => {
const legacyUserData = path.join(path.dirname(targetUserData), 'xdt-maker');
const legacyHome = path.join(legacyUserData, 'codex-home');
@@ -1275,7 +1318,9 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>
targetRow.close();
expect(adopted.title).toBe('Legacy branded session');
expect(adopted.rolloutPath.startsWith(path.join(desktopHome(), 'sessions'))).toBe(true);
- expect(path.basename(adopted.rolloutPath)).toBe(path.basename(sourceRollout));
+ expect(path.basename(adopted.rolloutPath)).toBe(
+ `rollout-cindy-adopted-${path.basename(sourceRollout)}`,
+ );
expect(fs.readFileSync(adopted.rolloutPath, 'utf-8')).toBe(sourceContents);
// 接管后不再依赖老目录;重复 prepare 走当前 HOME 热路径且不改写 rollout。
@@ -1313,6 +1358,391 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>
expect(fs.readFileSync(targetRow.rolloutPath, 'utf-8')).toBe('LEGACY_ROLLOUT');
});
+ it('keeps an existing external adoption hidden until a local precursor passes the state transaction', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-07-14T11-56-18-${threadId}.jsonl`,
+ );
+ const sourceContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/existing-row' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, sourceContents);
+
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, sourceRollout, { updatedAt: 3_000 });
+ const canonical = path.join(desktopHome(), 'sessions', path.basename(sourceRollout));
+ fs.mkdirSync(path.dirname(canonical), { recursive: true });
+ fs.writeFileSync(canonical, '');
+ markEmptyRolloutStable(canonical);
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/existing-row' },
+ })}\n`;
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ const realLink = fs.promises.link.bind(fs.promises);
+ const realLstat = fs.lstatSync.bind(fs);
+ let preservedCanonical: string | null = null;
+ let publication: string | null = null;
+ let preservedLstatCount = 0;
+ let filled = false;
+ const linkSyncSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ const linked = realLinkSync(source, target);
+ if (
+ path.resolve(source.toString()) === path.resolve(canonical)
+ && path.basename(target.toString()).startsWith('rollout-cindy-preserved-empty')
+ ) preservedCanonical = path.resolve(target.toString());
+ return linked;
+ });
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (path.basename(target.toString()).startsWith('rollout-cindy-adopted')) {
+ publication = path.resolve(target.toString());
+ }
+ });
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((file: fs.PathLike) => {
+ const observed = realLstat(file);
+ if (
+ publication
+ && preservedCanonical
+ && !filled
+ && path.resolve(file.toString()) === preservedCanonical
+ ) {
+ preservedLstatCount += 1;
+ // The same preserved inode is guarded once through the canonical plan
+ // and once through interrupted-preservation recovery. Four probes pass
+ // before UPDATE; the fifth begins the post-UPDATE transaction guard.
+ if (preservedLstatCount === 5) {
+ fs.writeFileSync(preservedCanonical, nativeContents);
+ filled = true;
+ }
+ }
+ return observed;
+ }) as typeof fs.lstatSync);
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /external rollout pointer changed during private adoption/,
+ );
+ } finally {
+ lstatSpy.mockRestore();
+ linkSpy.mockRestore();
+ linkSyncSpy.mockRestore();
+ }
+
+ expect(filled).toBe(true);
+ expect(publication).toBeTruthy();
+ expect(publication).not.toBe(canonical);
+ expect(fs.existsSync(canonical)).toBe(false);
+ let targetDb = new Database(targetDbPath, { readonly: true });
+ let targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(sourceRollout);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(canonical);
+ targetDb = new Database(targetDbPath, { readonly: true });
+ targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(canonical);
+ expect(fs.readFileSync(canonical, 'utf-8')).toBe(nativeContents);
+ expect(fs.readFileSync(canonical, 'utf-8')).not.toBe(sourceContents);
+ });
+
+ it('rejects a different concurrent state winner beside the planned native canonical', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-07-14T10-00-00-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/concurrent-state-source' },
+ })}\n`);
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, externalRollout, { updatedAt: 3_000 });
+
+ const directory = path.join(desktopHome(), 'sessions', '2026', '07', '14');
+ const nativeCanonical = path.join(
+ directory,
+ `rollout-2026-07-14T11-00-00-${threadId}.jsonl`,
+ );
+ const concurrentWinner = path.join(
+ directory,
+ `rollout-cindy-adopted-${path.basename(nativeCanonical)}`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/planned-canonical' },
+ })}\n`;
+ const concurrentContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/recovery/concurrent-state-winner' },
+ })}\n`;
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(nativeCanonical, nativeContents);
+ fs.writeFileSync(concurrentWinner, concurrentContents);
+
+ const realLstat = fs.lstatSync.bind(fs);
+ let stateChanged = false;
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((candidate: fs.PathLike) => {
+ if (
+ !stateChanged
+ && path.resolve(candidate.toString()) === path.resolve(nativeCanonical)
+ ) {
+ const db = new Database(targetDbPath);
+ db.prepare('UPDATE threads SET rollout_path = ? WHERE id = ?')
+ .run(concurrentWinner, threadId);
+ db.close();
+ stateChanged = true;
+ }
+ return realLstat(candidate);
+ }) as typeof fs.lstatSync);
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /concurrent state selected a different private winner/,
+ );
+ } finally {
+ lstatSpy.mockRestore();
+ }
+
+ expect(stateChanged).toBe(true);
+ expect(fs.readFileSync(nativeCanonical, 'utf-8')).toBe(nativeContents);
+ expect(fs.readFileSync(concurrentWinner, 'utf-8')).toBe(concurrentContents);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(concurrentWinner);
+ });
+
+ it('fails closed when a second preserved native writer wakes before reconciliation commits', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-07-14T10-00-00-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/uncommitted' },
+ })}\n`);
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, externalRollout, { updatedAt: 3_000 });
+
+ const directory = path.join(desktopHome(), 'sessions', '2026', '07', '14');
+ const firstCanonical = path.join(
+ directory,
+ `rollout-2026-07-14T11-00-00-${threadId}.jsonl`,
+ );
+ const secondCanonical = path.join(
+ directory,
+ `rollout-2026-07-14T12-00-00-${threadId}.jsonl`,
+ );
+ const firstPreserved = path.join(
+ directory,
+ `rollout-cindy-preserved-empty-${path.basename(firstCanonical)}`,
+ );
+ const secondPreserved = path.join(
+ directory,
+ `rollout-cindy-preserved-empty-${path.basename(secondCanonical)}`,
+ );
+ const firstNative = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/first' },
+ })}\n`;
+ const secondNative = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/second' },
+ })}\n`;
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(firstCanonical, firstNative);
+ fs.linkSync(firstCanonical, firstPreserved);
+ fs.writeFileSync(secondPreserved, '');
+
+ const realLstat = fs.lstatSync.bind(fs);
+ let secondPreservedLstatCount = 0;
+ let filled = false;
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((file: fs.PathLike) => {
+ const observed = realLstat(file);
+ if (
+ !filled
+ && path.resolve(file.toString()) === path.resolve(secondPreserved)
+ ) {
+ secondPreservedLstatCount += 1;
+ // Strict planning and snapshot capture use four probes; the native CAS
+ // pre-guard uses two more. The seventh starts its post-UPDATE guard.
+ if (secondPreservedLstatCount === 7) {
+ fs.writeFileSync(secondPreserved, secondNative);
+ filled = true;
+ }
+ }
+ return observed;
+ }) as typeof fs.lstatSync);
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /state changed before native rollout reconciliation/,
+ );
+ } finally {
+ lstatSpy.mockRestore();
+ }
+
+ expect(filled).toBe(true);
+ let targetDb = new Database(targetDbPath, { readonly: true });
+ let targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(externalRollout);
+ expect(fs.readFileSync(firstCanonical, 'utf-8')).toBe(firstNative);
+ expect(fs.existsSync(secondCanonical)).toBe(false);
+ expect(fs.readFileSync(secondPreserved, 'utf-8')).toBe(secondNative);
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /multiple native private rollouts conflict before state handoff/,
+ );
+ targetDb = new Database(targetDbPath, { readonly: true });
+ targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(externalRollout);
+ });
+
+ it('rolls back a copied-rollout inode swap before updating an existing state pointer', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-07-14-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, 'EXTERNAL_FULL_ROLLOUT');
+ const sourceDbPath = createStateDb(externalHome);
+ insertThread(sourceDbPath, threadId, sourceRollout, { updatedAt: 2_000 });
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, sourceRollout, { updatedAt: 3_000 });
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ const realLstat = fs.lstatSync.bind(fs);
+ let candidate: string | null = null;
+ let candidateLstatCount = 0;
+ let swapped = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ source.toString().includes('.migration-tmp')
+ && path.resolve(target.toString()).startsWith(path.resolve(desktopHome()))
+ ) candidate = path.resolve(target.toString());
+ });
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((file: fs.PathLike) => {
+ const observed = realLstat(file);
+ if (candidate && path.resolve(file.toString()) === candidate) {
+ candidateLstatCount += 1;
+ if (!swapped && candidateLstatCount === 9) {
+ const validatedInode = `${candidate}.validated-inode`;
+ fs.renameSync(candidate, validatedInode);
+ fs.copyFileSync(validatedInode, candidate);
+ swapped = true;
+ }
+ }
+ return observed;
+ }) as typeof fs.lstatSync);
+
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /external rollout pointer changed during private adoption/,
+ );
+ } finally {
+ lstatSpy.mockRestore();
+ linkSpy.mockRestore();
+ }
+
+ expect(swapped).toBe(true);
+ let targetDb = new Database(targetDbPath, { readonly: true });
+ let targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(sourceRollout);
+
+ const recovered = await prepareExternalCodexSessionForResume(threadId);
+ expect(recovered).toBe(candidate);
+ targetDb = new Database(targetDbPath, { readonly: true });
+ targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(candidate);
+ expect(fs.readFileSync(candidate!, 'utf-8')).toBe('EXTERNAL_FULL_ROLLOUT');
+ });
+
+ it('keeps a missing private pointer when its native writer wakes during external copy', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-07-14-${threadId}.jsonl`,
+ );
+ const sourceContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/project' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, sourceContents);
+ const sourceDbPath = createStateDb(externalHome);
+ insertThread(sourceDbPath, threadId, sourceRollout, { updatedAt: 2_000 });
+
+ const targetDbPath = createStateDb(desktopHome());
+ const missingPrivate = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-07-14-${threadId}.jsonl`,
+ );
+ insertThread(targetDbPath, threadId, missingPrivate, { updatedAt: 3_000 });
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/writer' },
+ })}\n`;
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let materialized = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ if (
+ !materialized
+ && source.toString().includes('.migration-tmp')
+ && path.basename(target.toString()).startsWith('rollout-cindy-adopted')
+ ) {
+ fs.mkdirSync(path.dirname(missingPrivate), { recursive: true });
+ fs.writeFileSync(missingPrivate, nativeContents);
+ materialized = true;
+ }
+ await realLink(source, target);
+ });
+ let prepared: string | undefined;
+ try {
+ prepared = await prepareExternalCodexSessionForResume(threadId);
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(prepared).toBe(missingPrivate);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(missingPrivate);
+ expect(fs.readFileSync(missingPrivate, 'utf-8')).toBe(nativeContents);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(missingPrivate);
+ });
+
it('prioritizes the legacy rollout already referenced by target state over a newer linked external copy', async () => {
const legacyHome = path.join(path.dirname(targetUserData), 'xdt-maker', 'codex-home');
const legacyRollout = path.join(legacyHome, 'sessions', `rollout-2026-07-14-${threadId}.jsonl`);
@@ -1369,19 +1799,52 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>
await prepareExternalCodexSessionForResume(threadId);
- const adoptedRollout = path.join(desktopHome(), 'sessions', path.basename(sourceRollout));
+ const preferredRollout = path.join(desktopHome(), 'sessions', path.basename(sourceRollout));
const targetDb = new Database(targetDbPath, { readonly: true });
const targetRow = targetDb
.prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
.get(threadId) as { rolloutPath: string };
targetDb.close();
- // 方案 A:desktop state 指向私有副本,而非源 rollout;副本落盘、内容与源一致。
- expect(targetRow.rolloutPath).toBe(adoptedRollout);
- expect(fs.readFileSync(adoptedRollout, 'utf-8')).toBe('EXTERNAL_ROLLOUT');
+ // State-backed copies stay hidden from the canonical scanner until the
+ // transaction selects them, then desktop state points at that private copy.
+ expect(targetRow.rolloutPath).not.toBe(preferredRollout);
+ expect(path.basename(targetRow.rolloutPath)).toBe(
+ `rollout-cindy-adopted-${path.basename(sourceRollout)}`,
+ );
+ expect(fs.existsSync(preferredRollout)).toBe(false);
+ expect(fs.readFileSync(targetRow.rolloutPath, 'utf-8')).toBe('EXTERNAL_ROLLOUT');
// 源 rollout 原样不动——不再有任何回写通道。
expect(fs.readFileSync(sourceRollout, 'utf-8')).toBe('EXTERNAL_ROLLOUT');
});
+ it('does not return a non-canonical rollout-only copy without a state pointer', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-custom-${threadId}.jsonl`,
+ );
+ const sourceContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/tmp/project' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, sourceContents);
+ const targetDbPath = createStateDb(desktopHome());
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /not discoverable without state/,
+ );
+
+ const privateCopy = path.join(desktopHome(), 'sessions', path.basename(sourceRollout));
+ expect(fs.readFileSync(privateCopy, 'utf-8')).toBe(sourceContents);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const stateCount = targetDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ targetDb.close();
+ expect(stateCount.count).toBe(0);
+ });
+
it('synthesizes into the current HOME when legacy state survives but its rollout is missing', async () => {
const legacyHome = path.join(path.dirname(targetUserData), 'xdt-maker', 'codex-home');
const missingSourceRollout = path.join(
@@ -1414,6 +1877,85 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>
expect(fs.readFileSync(targetRow.rolloutPath, 'utf-8')).toContain('recover me');
});
+ it('rolls back when a missing external rollout materializes inside the state-copy transaction', async () => {
+ const missingSourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '07',
+ '14',
+ `rollout-2026-07-14-${threadId}.jsonl`,
+ );
+ const sourceDbPath = createStateDb(externalHome);
+ insertThread(sourceDbPath, threadId, missingSourceRollout, { updatedAt: 2_000 });
+ const targetDbPath = createStateDb(desktopHome());
+ const sessionId = `local-missing-external-race-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'missing-external-race-c1',
+ 'user',
+ JSON.stringify({ text: 'lossy fallback' }),
+ 1_000,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/native' },
+ })}\n`;
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ const realLstat = fs.lstatSync.bind(fs);
+ let publicationReady = false;
+ let sourceProbeCount = 0;
+ let materialized = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (path.basename(target.toString()).startsWith('rollout-cindy-empty-recovery')) {
+ publicationReady = true;
+ }
+ });
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((file: fs.PathLike) => {
+ if (
+ publicationReady
+ && !materialized
+ && path.resolve(file.toString()) === path.resolve(missingSourceRollout)
+ ) {
+ sourceProbeCount += 1;
+ if (sourceProbeCount === 2) {
+ fs.mkdirSync(path.dirname(missingSourceRollout), { recursive: true });
+ fs.writeFileSync(missingSourceRollout, nativeContents);
+ materialized = true;
+ }
+ }
+ return realLstat(file);
+ }) as typeof fs.lstatSync);
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /missing external rollout materialized before state handoff/,
+ );
+ } finally {
+ lstatSpy.mockRestore();
+ linkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ let targetDb = new Database(targetDbPath, { readonly: true });
+ const targetCount = targetDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ targetDb.close();
+ expect(targetCount.count).toBe(0);
+
+ const adopted = await prepareExternalCodexSessionForResume(threadId);
+ expect(fs.readFileSync(adopted!, 'utf-8')).toBe(nativeContents);
+ targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(adopted);
+ });
+
it('synthesizes a standard rollout when both the Codex state row and file are missing', async () => {
const dbPath = createStateDb(desktopHome());
const sessionId = `local-missing-state-${threadId}`;
@@ -1473,6 +2015,10 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>
const originalContents = fs.readFileSync(rolloutPath, 'utf-8');
await prepareExternalCodexSessionForResume(threadId);
expect(fs.readFileSync(rolloutPath, 'utf-8')).toBe(originalContents);
+
+ insertLocalMessage(sessionId, 'c3', 'user', JSON.stringify({ text: 'new H2' }), 1_200);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(rolloutPath);
+ expect(fs.readFileSync(rolloutPath, 'utf-8')).toBe(originalContents);
});
it('prefers the fullest readable history when duplicate Cindy sessions share a Codex thread', async () => {
@@ -1526,6 +2072,87 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>
]);
});
+ it('keeps a published no-state H1 authoritative when a fuller source appears later', async () => {
+ createStateDb(desktopHome());
+ const firstSessionId = `local-first-source-${threadId}`;
+ insertLocalCodexSession(firstSessionId, threadId, { createdAt: 1_000, updatedAt: 2_000 });
+ insertLocalMessage(firstSessionId, 'first-source-c1', 'user', JSON.stringify({ text: 'H1' }), 1_000);
+ await prepareExternalCodexSessionForResume(threadId);
+
+ const firstPath = path.join(
+ desktopHome(),
+ 'sessions',
+ '1970',
+ '01',
+ '01',
+ `rollout-1970-01-01T00-00-01-${threadId}.jsonl`,
+ );
+ expect(fs.readFileSync(firstPath, 'utf-8')).toContain('H1');
+
+ const fullerSessionId = `local-fuller-source-${threadId}`;
+ insertLocalCodexSession(fullerSessionId, threadId, { createdAt: 2_000, updatedAt: 3_000 });
+ insertLocalMessage(fullerSessionId, 'fuller-source-c1', 'user', JSON.stringify({ text: 'H1' }), 1_000);
+ insertLocalMessage(fullerSessionId, 'fuller-source-c2', 'assistant', 'H2', 2_000);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(firstPath);
+
+ expect(fs.readFileSync(firstPath, 'utf-8')).not.toContain('H2');
+ const secondPath = path.join(
+ desktopHome(),
+ 'sessions',
+ '1970',
+ '01',
+ '01',
+ `rollout-1970-01-01T00-00-02-${threadId}.jsonl`,
+ );
+ expect(fs.existsSync(secondPath)).toBe(false);
+ });
+
+ it('converges H1 to H2 before exposing the only no-state canonical path', async () => {
+ createStateDb(desktopHome());
+ const sessionId = `local-no-state-h1-h2-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId, { createdAt: 1_000, updatedAt: 2_000 });
+ insertLocalMessage(sessionId, 'no-state-h1', 'user', JSON.stringify({ text: 'no-state H1' }), 1_000);
+
+ const firstPath = path.join(
+ desktopHome(),
+ 'sessions',
+ '1970',
+ '01',
+ '01',
+ `rollout-1970-01-01T00-00-01-${threadId}.jsonl`,
+ );
+ const secondPath = path.join(
+ desktopHome(),
+ 'sessions',
+ '1970',
+ '01',
+ '01',
+ `rollout-1970-01-01T00-00-02-${threadId}.jsonl`,
+ );
+ const realLink = fs.promises.link.bind(fs.promises);
+ let advanced = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ !advanced
+ && path.basename(target.toString()).startsWith('.cindy-state-less-recovery')
+ ) {
+ advanced = true;
+ insertLocalMessage(sessionId, 'no-state-h2', 'assistant', 'no-state H2', 1_100);
+ }
+ });
+ try {
+ await prepareExternalCodexSessionForResume(threadId);
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(fs.readFileSync(firstPath, 'utf-8')).toContain('no-state H2');
+ expect(fs.existsSync(secondPath)).toBe(false);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(firstPath);
+ });
+
it('uses the first positive message timestamp for concurrent recovery when session created_at is invalid', async () => {
createStateDb(desktopHome());
const sessionId = `local-zero-created-${threadId}`;
@@ -1547,7 +2174,8 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>
`rollout-1970-01-01T00-00-05-${threadId}.jsonl`,
);
expect(fs.existsSync(rolloutPath)).toBe(true);
- expect(fs.readdirSync(path.dirname(rolloutPath))).toEqual([path.basename(rolloutPath)]);
+ expect(fs.readdirSync(path.dirname(rolloutPath)).filter((name) => name.endsWith('.jsonl')))
+ .toEqual([path.basename(rolloutPath)]);
const meta = JSON.parse(fs.readFileSync(rolloutPath, 'utf-8').split('\n')[0]);
expect(meta.timestamp).toBe('1970-01-01T00:00:05.000Z');
expect(meta.payload.timestamp).toBe('1970-01-01T00:00:05.000Z');
@@ -1624,11 +2252,13 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>
);
expect(fs.existsSync(missingRollout)).toBe(false);
- await prepareExternalCodexSessionForResume(threadId);
- expect(fs.existsSync(missingRollout)).toBe(true);
+ const recoveredRollout = await prepareExternalCodexSessionForResume(threadId);
+ expect(recoveredRollout).toBeTruthy();
+ expect(recoveredRollout).not.toBe(missingRollout);
+ expect(fs.existsSync(missingRollout)).toBe(false);
const lines = fs
- .readFileSync(missingRollout, 'utf-8')
+ .readFileSync(recoveredRollout!, 'utf-8')
.trim()
.split('\n')
.map((l) => JSON.parse(l));
@@ -1648,25 +2278,3754 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>
// user 用 input_text、assistant 用 output_text。
expect(items[0].payload.content[0].type).toBe('input_text');
expect(items[1].payload.content[0].type).toBe('output_text');
+ const targetDb = new Database(dbPath, { readonly: true });
+ const state = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(state.rolloutPath).toBe(recoveredRollout);
});
- it('does not overwrite an existing rollout file (happy path short-circuit)', async () => {
+ it('blocks when a private orphan starts materializing during synthetic publication', async () => {
const dbPath = createStateDb(desktopHome());
- const rolloutPath = path.join(
+ const missingRollout = path.join(
desktopHome(),
'sessions',
`rollout-2026-06-15-${threadId}.jsonl`,
);
- fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });
- fs.writeFileSync(rolloutPath, 'ORIGINAL_CONTENT');
- insertThread(dbPath, threadId, rolloutPath, { updatedAt: 2_000 });
-
- const sessionId = `local-orphan-${threadId}`;
+ insertThread(dbPath, threadId, missingRollout, { updatedAt: 2_000 });
+ const sessionId = `local-orphan-race-${threadId}`;
insertLocalCodexSession(sessionId, threadId);
- insertLocalMessage(
- sessionId,
- 'c1',
- 'user',
+ insertLocalMessage(sessionId, 'race-c1', 'user', JSON.stringify({ text: 'recover' }), 1_000);
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ path.basename(target.toString()).startsWith('rollout-cindy-empty-recovery')
+ && !fs.existsSync(missingRollout)
+ ) {
+ fs.writeFileSync(missingRollout, '');
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /private orphan began materializing/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(fs.readFileSync(missingRollout, 'utf-8')).toBe('');
+ const targetDb = new Database(dbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(missingRollout);
+ });
+
+ it('keeps a committed recovery when the old private writer wakes afterward', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const missingRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-06-15-${threadId}.jsonl`,
+ );
+ insertThread(dbPath, threadId, missingRollout, { updatedAt: 2_000 });
+ const sessionId = `local-post-commit-writer-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'post-commit-c1',
+ 'user',
+ JSON.stringify({ text: 'continue on the committed recovery' }),
+ 1_000,
+ );
+
+ const nativeLateContents = 'NATIVE_WRITER_WOKE_AFTER_COMMIT';
+ const realLstat = fs.lstatSync.bind(fs);
+ let lateWriterWoke = false;
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((candidate: fs.PathLike) => {
+ if (
+ !lateWriterWoke
+ && path.resolve(candidate.toString()) === path.resolve(missingRollout)
+ && !fs.existsSync(missingRollout)
+ ) {
+ try {
+ const probe = new Database(dbPath, { readonly: true });
+ const row = probe
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ probe.close();
+ // A separate connection sees the synthetic pointer only after the
+ // handoff transaction commits, never during its post-inode check.
+ if (row.rolloutPath !== missingRollout) {
+ fs.writeFileSync(missingRollout, nativeLateContents);
+ lateWriterWoke = true;
+ }
+ } catch {
+ // The writer transaction may still hold the DB; retry on next lstat.
+ }
+ }
+ return realLstat(candidate);
+ }) as typeof fs.lstatSync);
+
+ let recovered: string | undefined;
+ try {
+ recovered = await prepareExternalCodexSessionForResume(threadId);
+ } finally {
+ lstatSpy.mockRestore();
+ }
+
+ expect(lateWriterWoke).toBe(true);
+ expect(recovered).toBeTruthy();
+ expect(recovered).not.toBe(missingRollout);
+ expect(fs.readFileSync(missingRollout, 'utf-8')).toBe(nativeLateContents);
+ const targetDb = new Database(dbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(recovered);
+ expect(fs.readFileSync(recovered!, 'utf-8')).toContain('continue on the committed recovery');
+ });
+
+ it('does not restore a private orphan that materializes as a symbolic link', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const missingRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-06-15-${threadId}.jsonl`,
+ );
+ insertThread(dbPath, threadId, missingRollout, { updatedAt: 2_000 });
+ const sessionId = `local-orphan-symlink-race-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'symlink-race-c1', 'user', JSON.stringify({ text: 'recover' }), 1_000);
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let lstatOverridden = false;
+ let restoreLstat = (): void => undefined;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ !lstatOverridden
+ && path.basename(target.toString()).startsWith('rollout-cindy-empty-recovery')
+ ) {
+ fs.writeFileSync(missingRollout, 'SIMULATED_EXTERNAL_TARGET');
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockReturnValue({
+ isFile: () => false,
+ isSymbolicLink: () => true,
+ } as unknown as fs.Stats);
+ lstatOverridden = true;
+ restoreLstat = () => lstatSpy.mockRestore();
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /private recovery file could not be published safely/,
+ );
+ } finally {
+ restoreLstat();
+ linkSpy.mockRestore();
+ }
+
+ const targetDb = new Database(dbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(missingRollout);
+ });
+
+ it('does not treat a freshly copied empty rollout with an old mtime as stable', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const emptyRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(emptyRollout), { recursive: true });
+ fs.writeFileSync(emptyRollout, '');
+ const preservedOldMtime = new Date(Date.now() - 20 * 60_000);
+ fs.utimesSync(emptyRollout, preservedOldMtime, preservedOldMtime);
+ insertThread(dbPath, threadId, emptyRollout, { updatedAt: 2_000 });
+ const sessionId = `local-fresh-copy-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'fresh-copy-c1', 'user', JSON.stringify({ text: 'recover' }), 1_000);
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /may still be materializing/,
+ );
+
+ expect(fs.readFileSync(emptyRollout, 'utf-8')).toBe('');
+ expect(fs.readdirSync(path.dirname(emptyRollout))).toEqual([path.basename(emptyRollout)]);
+ });
+
+ it('relinks an empty rollout to a recovered copy without overwriting the original (#1554)', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const emptyRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(emptyRollout), { recursive: true });
+ fs.writeFileSync(emptyRollout, '');
+ markEmptyRolloutStable(emptyRollout);
+ insertThread(dbPath, threadId, emptyRollout, { updatedAt: 2_000 });
+
+ const sessionId = `local-empty-rollout-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'c1',
+ 'user',
+ JSON.stringify({ text: 'continue from another device', images: [], files: [] }),
+ 1_000,
+ );
+ insertLocalMessage(sessionId, 'c2', 'assistant', 'recover this task', 1_100);
+
+ const [prepared, concurrentPrepared] = await Promise.all([
+ prepareExternalCodexSessionForResume(threadId),
+ prepareExternalCodexSessionForResume(threadId),
+ ]);
+
+ expect(prepared).toBeTruthy();
+ expect(concurrentPrepared).toBe(prepared);
+ expect(prepared).not.toBe(emptyRollout);
+ expect(fs.readFileSync(emptyRollout, 'utf-8')).toBe('');
+ const recovered = fs.readFileSync(prepared!, 'utf-8');
+ expect(recovered).toContain('continue from another device');
+ expect(recovered).toContain('recover this task');
+ const stateDb = new Database(dbPath, { readonly: true });
+ const state = stateDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ stateDb.close();
+ expect(state.rolloutPath).toBe(prepared);
+
+ // 后续终端继续同一任务时复用已发布的恢复文件,不生成新副本。
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(prepared);
+ expect(fs.readFileSync(prepared!, 'utf-8')).toBe(recovered);
+ });
+
+ it('rejects an exact-content sibling symlink before changing the state pointer', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const emptyRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(emptyRollout), { recursive: true });
+ fs.writeFileSync(emptyRollout, '');
+ markEmptyRolloutStable(emptyRollout);
+ insertThread(dbPath, threadId, emptyRollout, { updatedAt: 2_000 });
+
+ const sessionId = `local-exact-symlink-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'exact-symlink-c1',
+ 'user',
+ JSON.stringify({ text: 'recover without crossing the private boundary' }),
+ 1_000,
+ );
+
+ // Model a deterministic candidate that resolves to an external file with
+ // exactly the synthetic bytes. stat/open still see those bytes, while lstat
+ // exposes the path as a symlink; this stays portable on Windows CI.
+ const externalTarget = path.join(rootDir, 'external-exact-synthetic.jsonl');
+ const realLink = fs.promises.link.bind(fs.promises);
+ const realLstat = fs.lstatSync.bind(fs);
+ let syntheticCandidate: string | null = null;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (path.basename(target.toString()).startsWith('rollout-cindy-empty-recovery')) {
+ syntheticCandidate = path.resolve(target.toString());
+ fs.copyFileSync(syntheticCandidate, externalTarget);
+ }
+ });
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((candidate: fs.PathLike) => {
+ const resolved = path.resolve(candidate.toString());
+ if (syntheticCandidate && resolved === syntheticCandidate) {
+ const externalStat = realLstat(externalTarget);
+ return {
+ ...externalStat,
+ isFile: () => false,
+ isSymbolicLink: () => true,
+ } as fs.Stats;
+ }
+ return realLstat(candidate);
+ }) as typeof fs.lstatSync);
+
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /private recovery file could not be published safely/,
+ );
+ } finally {
+ lstatSpy.mockRestore();
+ linkSpy.mockRestore();
+ }
+
+ expect(syntheticCandidate).toBeTruthy();
+ const externalContents = fs.readFileSync(externalTarget, 'utf-8');
+ expect(externalContents).toContain('recover without crossing the private boundary');
+ const stateDb = new Database(dbPath, { readonly: true });
+ const state = stateDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ stateDb.close();
+ expect(state.rolloutPath).toBe(emptyRollout);
+ expect(fs.readFileSync(externalTarget, 'utf-8')).toBe(externalContents);
+ });
+
+ it('rolls back an inode swap transaction without undoing the next same-path winner', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const emptyRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(emptyRollout), { recursive: true });
+ fs.writeFileSync(emptyRollout, '');
+ markEmptyRolloutStable(emptyRollout);
+ insertThread(dbPath, threadId, emptyRollout, { updatedAt: 2_000 });
+
+ const sessionId = `local-cas-swap-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'cas-swap-c1',
+ 'user',
+ JSON.stringify({ text: 'keep state bound to the validated inode' }),
+ 1_000,
+ );
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ const realOpen = fs.openSync.bind(fs);
+ const realClose = fs.closeSync.bind(fs);
+ let syntheticCandidate: string | null = null;
+ let candidateCloseCount = 0;
+ let replaced = false;
+ const candidateFds = new Set<number>();
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (path.basename(target.toString()).startsWith('rollout-cindy-empty-recovery')) {
+ syntheticCandidate = path.resolve(target.toString());
+ }
+ });
+ const openSpy = vi.spyOn(fs, 'openSync').mockImplementation(((file, flags, mode) => {
+ const fd = realOpen(file, flags, mode);
+ if (syntheticCandidate && path.resolve(file.toString()) === syntheticCandidate) {
+ candidateFds.add(fd);
+ }
+ return fd;
+ }) as typeof fs.openSync);
+ const closeSpy = vi.spyOn(fs, 'closeSync').mockImplementation((fd) => {
+ const isCandidate = candidateFds.delete(fd);
+ realClose(fd);
+ if (isCandidate && ++candidateCloseCount === 3 && syntheticCandidate) {
+ const validatedInode = `${syntheticCandidate}.validated-inode`;
+ fs.renameSync(syntheticCandidate, validatedInode);
+ fs.copyFileSync(validatedInode, syntheticCandidate);
+ replaced = true;
+ }
+ });
+
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /target state changed during private orphan recovery|rollout pointer changed during recovery/,
+ );
+ } finally {
+ closeSpy.mockRestore();
+ openSpy.mockRestore();
+ linkSpy.mockRestore();
+ }
+
+ expect(replaced).toBe(true);
+ expect(fs.readFileSync(syntheticCandidate!, 'utf-8')).toContain(
+ 'keep state bound to the validated inode',
+ );
+ let stateDb = new Database(dbPath, { readonly: true });
+ let state = stateDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ stateDb.close();
+ expect(state.rolloutPath).toBe(emptyRollout);
+ expect(fs.readFileSync(emptyRollout, 'utf-8')).toBe('');
+
+ // A later recovery validates the replacement inode itself and may commit
+ // the same deterministic path; the failed transaction left no stale CAS
+ // that can roll this winner back to the empty file.
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(syntheticCandidate);
+ stateDb = new Database(dbPath, { readonly: true });
+ state = stateDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ stateDb.close();
+ expect(state.rolloutPath).toBe(syntheticCandidate);
+ });
+
+ it('does not publish through a sessions directory symlink outside Cindy storage', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const externalEmpty = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalEmpty), { recursive: true });
+ fs.writeFileSync(externalEmpty, '');
+ markEmptyRolloutStable(externalEmpty);
+ insertThread(dbPath, threadId, externalEmpty, { updatedAt: 2_000 });
+
+ const sessionId = `local-parent-symlink-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'parent-symlink-c1',
+ 'user',
+ JSON.stringify({ text: 'keep recovery inside Cindy storage' }),
+ 1_000,
+ );
+
+ const outsideDirectory = path.join(rootDir, 'outside-cindy-storage');
+ fs.mkdirSync(outsideDirectory, { recursive: true });
+ fs.symlinkSync(
+ outsideDirectory,
+ path.join(desktopHome(), 'sessions'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /private recovery file could not be published safely/,
+ );
+
+ expect(fs.readdirSync(outsideDirectory)).toEqual([]);
+ const stateDb = new Database(dbPath, { readonly: true });
+ const state = stateDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ stateDb.close();
+ expect(state.rolloutPath).toBe(externalEmpty);
+ expect(fs.readFileSync(externalEmpty, 'utf-8')).toBe('');
+ });
+
+ it('replaces a stable canonical empty when state is lost without relying on scan order', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const emptyRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(emptyRollout), { recursive: true });
+ fs.writeFileSync(emptyRollout, '');
+ markEmptyRolloutStable(emptyRollout);
+ insertThread(dbPath, threadId, emptyRollout, { updatedAt: 2_000 });
+ const sessionId = `local-lost-recovery-state-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'lost-state-c1', 'user', JSON.stringify({ text: 'recover' }), 1_000);
+
+ const recovered = await prepareExternalCodexSessionForResume(threadId);
+ expect(recovered).toBeTruthy();
+ const canonicalMtime = fs.statSync(emptyRollout).mtimeMs;
+ const newerRecoveryTime = new Date(canonicalMtime + 1_000);
+ fs.utimesSync(recovered!, newerRecoveryTime, newerRecoveryTime);
+ const writableDb = new Database(dbPath);
+ writableDb.prepare('DELETE FROM threads WHERE id = ?').run(threadId);
+ writableDb.close();
+
+ const recoveredWithoutState = await prepareExternalCodexSessionForResume(threadId);
+
+ expect(recoveredWithoutState).toBe(emptyRollout);
+ expect(fs.readFileSync(emptyRollout, 'utf-8')).toContain('recover');
+ expect(fs.readFileSync(recovered!, 'utf-8')).toContain('recover');
+ const canonicalNames = fs.readdirSync(path.dirname(emptyRollout)).filter(
+ (name) => /^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-/.test(name)
+ && name.endsWith(`${threadId}.jsonl`),
+ );
+ expect(canonicalNames).toEqual([path.basename(emptyRollout)]);
+ const preservedEmpty = fs.readdirSync(path.dirname(emptyRollout)).find(
+ (name) => name.startsWith('rollout-cindy-preserved-empty'),
+ );
+ expect(preservedEmpty).toBeTruthy();
+ expect(fs.readFileSync(path.join(path.dirname(emptyRollout), preservedEmpty!), 'utf-8')).toBe('');
+ const stateDb = new Database(dbPath, { readonly: true });
+ const stateCount = stateDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ stateDb.close();
+ expect(stateCount.count).toBe(0);
+
+ // A retained native writer may append only after the synthetic handoff.
+ // Its Cindy-only artifact must not shadow the already authoritative canonical.
+ const canonicalContents = fs.readFileSync(emptyRollout, 'utf-8');
+ const lateNative = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/late/native' },
+ })}\n`;
+ const preservedPath = path.join(path.dirname(emptyRollout), preservedEmpty!);
+ fs.writeFileSync(preservedPath, lateNative);
+ const later = new Date(Date.now() + 1_000);
+ fs.utimesSync(preservedPath, later, later);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(emptyRollout);
+ expect(fs.readFileSync(emptyRollout, 'utf-8')).toBe(canonicalContents);
+ expect(fs.readFileSync(preservedPath, 'utf-8')).toBe(lateNative);
+ });
+
+ it('keeps the synthetic canonical when the retained writer fills after link commit', async () => {
+ createStateDb(desktopHome());
+ const sessionId = `local-post-link-writer-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'post-link-writer-c1',
+ 'user',
+ JSON.stringify({ text: 'canonical link is the irreversible winner' }),
+ 1_000,
+ );
+ const canonical = path.join(
+ desktopHome(),
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(canonical), { recursive: true });
+ fs.writeFileSync(canonical, '');
+ markEmptyRolloutStable(canonical);
+ const nativeLateContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/late/retained-writer' },
+ })}\n`;
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ let filledAfterLink = false;
+ const linkSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ const linked = realLinkSync(source, target);
+ if (
+ !filledAfterLink
+ && target.toString() === canonical
+ && path.basename(source.toString()).startsWith('.cindy-state-less-recovery')
+ ) {
+ const preserved = fs.readdirSync(path.dirname(canonical))
+ .map((name) => path.join(path.dirname(canonical), name))
+ .find((candidate) => path.basename(candidate).startsWith('rollout-cindy-preserved-empty'));
+ expect(preserved).toBeTruthy();
+ fs.writeFileSync(preserved!, nativeLateContents);
+ filledAfterLink = true;
+ }
+ return linked;
+ });
+
+ let prepared: string | undefined;
+ try {
+ prepared = await prepareExternalCodexSessionForResume(threadId);
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(filledAfterLink).toBe(true);
+ expect(prepared).toBe(canonical);
+ expect(fs.readFileSync(canonical, 'utf-8')).toContain(
+ 'canonical link is the irreversible winner',
+ );
+ const preserved = fs.readdirSync(path.dirname(canonical))
+ .map((name) => path.join(path.dirname(canonical), name))
+ .find((candidate) => path.basename(candidate).startsWith('rollout-cindy-preserved-empty'));
+ expect(preserved).toBeTruthy();
+ expect(fs.readFileSync(preserved!, 'utf-8')).toBe(nativeLateContents);
+ expect(fs.readdirSync(path.dirname(canonical)).filter((name) => /^rollout-\d/.test(name))).toEqual([
+ path.basename(canonical),
+ ]);
+ });
+
+ it('keeps one existing full canonical and moves a stable empty out of scanner order', async () => {
+ createStateDb(desktopHome());
+ const directory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const emptyCanonical = path.join(
+ directory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const fullCanonical = path.join(
+ directory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const fullContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/existing/full' },
+ })}\n`;
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(emptyCanonical, '');
+ fs.writeFileSync(fullCanonical, fullContents);
+ markEmptyRolloutStable(emptyCanonical);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(fullCanonical);
+ expect(fs.readFileSync(fullCanonical, 'utf-8')).toBe(fullContents);
+ const names = fs.readdirSync(directory);
+ expect(names.filter((name) => /^rollout-\d/.test(name))).toEqual([
+ path.basename(fullCanonical),
+ ]);
+ expect(names.some((name) => name.startsWith('rollout-cindy-retired-empty'))).toBe(true);
+ });
+
+ it('keeps an existing full canonical when a retired empty inode fills during cleanup', async () => {
+ createStateDb(desktopHome());
+ const directory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const emptyCanonical = path.join(
+ directory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const fullCanonical = path.join(
+ directory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const fullContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/existing/full' },
+ })}\n`;
+ const lateContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/retired/late-writer' },
+ })}\n`;
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(emptyCanonical, '');
+ fs.writeFileSync(fullCanonical, fullContents);
+ markEmptyRolloutStable(emptyCanonical);
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ let filled = false;
+ const linkSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ const linked = realLinkSync(source, target);
+ if (
+ !filled
+ && source.toString() === emptyCanonical
+ && path.basename(target.toString()).startsWith('rollout-cindy-retired-empty')
+ ) {
+ filled = true;
+ fs.writeFileSync(emptyCanonical, lateContents);
+ }
+ return linked;
+ });
+ let prepared: string | undefined;
+ try {
+ prepared = await prepareExternalCodexSessionForResume(threadId);
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(prepared).toBe(fullCanonical);
+ expect(fs.readFileSync(fullCanonical, 'utf-8')).toBe(fullContents);
+ expect(fs.existsSync(emptyCanonical)).toBe(false);
+ const preserved = fs.readdirSync(directory)
+ .map((name) => path.join(directory, name))
+ .find((candidate) => path.basename(candidate).startsWith('rollout-cindy-retired-empty'));
+ expect(preserved).toBeTruthy();
+ expect(fs.readFileSync(preserved!, 'utf-8')).toBe(lateContents);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(fullCanonical);
+ expect(fs.readdirSync(directory).filter((name) => /^rollout-\d/.test(name))).toEqual([
+ path.basename(fullCanonical),
+ ]);
+ });
+
+ it('retries an interrupted canonical retirement after unlink fails', async () => {
+ createStateDb(desktopHome());
+ const directory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const retiredCanonical = path.join(
+ directory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const establishedWinner = path.join(
+ directory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const retiredCheckpoint = path.join(
+ directory,
+ `rollout-cindy-retired-empty-${path.basename(retiredCanonical)}`,
+ );
+ const retiredContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/retired/checkpoint' },
+ })}\n`;
+ const winnerContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/established/winner' },
+ })}\n`;
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(retiredCanonical, '');
+ fs.linkSync(retiredCanonical, retiredCheckpoint);
+ fs.writeFileSync(retiredCanonical, retiredContents);
+ fs.writeFileSync(establishedWinner, winnerContents);
+
+ const realUnlinkSync = fs.unlinkSync.bind(fs);
+ let failed = false;
+ const unlinkSpy = vi.spyOn(fs, 'unlinkSync').mockImplementation((candidate) => {
+ if (!failed && candidate.toString() === retiredCanonical) {
+ failed = true;
+ throw Object.assign(new Error('retirement busy'), { code: 'EPERM' });
+ }
+ return realUnlinkSync(candidate);
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /interrupted canonical could not be retired/,
+ );
+ } finally {
+ unlinkSpy.mockRestore();
+ }
+
+ expect(fs.existsSync(retiredCanonical)).toBe(true);
+ expect(fs.readFileSync(retiredCheckpoint, 'utf-8')).toBe(retiredContents);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(establishedWinner);
+ expect(fs.existsSync(retiredCanonical)).toBe(false);
+ expect(fs.readFileSync(retiredCheckpoint, 'utf-8')).toBe(retiredContents);
+ expect(fs.readFileSync(establishedWinner, 'utf-8')).toBe(winnerContents);
+ });
+
+ it('fails closed for multiple full canonicals without a retirement checkpoint', async () => {
+ createStateDb(desktopHome());
+ const directory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const first = path.join(
+ directory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const second = path.join(
+ directory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(first, `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/first' },
+ })}\n`);
+ fs.writeFileSync(second, `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/second' },
+ })}\n`);
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /multiple private canonical rollouts conflict/,
+ );
+ expect(fs.existsSync(first)).toBe(true);
+ expect(fs.existsSync(second)).toBe(true);
+ });
+
+ it('lets an additional stable empty become the native winner before synthetic handoff', async () => {
+ createStateDb(desktopHome());
+ const sessionId = `local-multiple-empty-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'multiple-empty-c1',
+ 'user',
+ JSON.stringify({ text: 'synthetic fallback must lose' }),
+ 1_000,
+ );
+ const directory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const primary = path.join(
+ directory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const additional = path.join(
+ directory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/additional/native' },
+ })}\n`;
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(primary, '');
+ fs.writeFileSync(additional, '');
+ markEmptyRolloutStable(additional);
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ let filled = false;
+ const linkSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ const linked = realLinkSync(source, target);
+ if (
+ !filled
+ && source.toString() === additional
+ && path.basename(target.toString()).startsWith('rollout-cindy-preserved-empty')
+ ) {
+ filled = true;
+ fs.writeFileSync(additional, nativeContents);
+ }
+ return linked;
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /additional private empty canonical materialized before handoff/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(additional);
+ expect(fs.readFileSync(additional, 'utf-8')).toBe(nativeContents);
+ expect(fs.readFileSync(additional, 'utf-8')).not.toContain('synthetic fallback must lose');
+ expect(fs.readdirSync(directory).filter((name) => /^rollout-\d/.test(name))).toEqual([
+ path.basename(additional),
+ ]);
+ });
+
+ it('guards an empty interrupted preservation until the next canonical handoff', async () => {
+ createStateDb(desktopHome());
+ const sessionId = `local-pending-preservation-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'pending-preservation-c1',
+ 'user',
+ JSON.stringify({ text: 'synthetic must wait for historical writer' }),
+ 1_000,
+ );
+ const directory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const primary = path.join(
+ directory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const interruptedCanonical = path.join(
+ directory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const interruptedPreserved = path.join(
+ directory,
+ `rollout-cindy-preserved-empty-${path.basename(interruptedCanonical)}`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/historical/late-writer' },
+ })}\n`;
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(primary, '');
+ fs.writeFileSync(interruptedPreserved, '');
+ markEmptyRolloutStable(primary);
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let filled = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (!filled && path.basename(target.toString()).startsWith('.cindy-state-less-recovery')) {
+ filled = true;
+ fs.writeFileSync(interruptedPreserved, nativeContents);
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /interrupted preserved rollout changed before canonical handoff/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(fs.existsSync(primary)).toBe(false);
+ expect(fs.existsSync(interruptedCanonical)).toBe(false);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(interruptedCanonical);
+ expect(fs.readFileSync(interruptedCanonical, 'utf-8')).toBe(nativeContents);
+ expect(fs.readFileSync(interruptedCanonical, 'utf-8'))
+ .not.toContain('synthetic must wait for historical writer');
+ });
+
+ it('does not expose a state-backed external canonical before additional empties pass handoff', async () => {
+ createStateDb(desktopHome());
+ const directory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const primary = path.join(
+ directory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const additional = path.join(
+ directory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(primary, '');
+ fs.writeFileSync(additional, '');
+ markEmptyRolloutStable(additional);
+
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T13-00-00-${threadId}.jsonl`,
+ );
+ const externalContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/state-backed' },
+ })}\n`;
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/additional/late-native' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, externalContents);
+ const externalDbPath = createStateDb(externalHome);
+ insertThread(externalDbPath, threadId, externalRollout, { updatedAt: 2_000 });
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let filled = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (!filled && path.basename(target.toString()).startsWith('rollout-cindy-adopted')) {
+ const preserved = fs.readdirSync(directory)
+ .map((name) => path.join(directory, name))
+ .find((candidate) => (
+ path.basename(candidate).startsWith('rollout-cindy-preserved-empty')
+ && path.basename(candidate).endsWith(path.basename(additional))
+ ));
+ expect(preserved).toBeTruthy();
+ fs.writeFileSync(preserved!, nativeContents);
+ filled = true;
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /additional private rollout changed before canonical handoff/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ const preferredExternalCanonical = path.join(
+ desktopHome(),
+ path.relative(externalHome, externalRollout),
+ );
+ expect(fs.existsSync(preferredExternalCanonical)).toBe(false);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(additional);
+ expect(fs.readFileSync(additional, 'utf-8')).toBe(nativeContents);
+ expect(fs.readFileSync(externalRollout, 'utf-8')).toBe(externalContents);
+ expect(fs.readdirSync(directory).filter((name) => /^rollout-\d/.test(name))).toEqual([
+ path.basename(additional),
+ ]);
+ });
+
+ it('blocks an existing full canonical while another same-thread empty is recent', async () => {
+ createStateDb(desktopHome());
+ const directory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const emptyCanonical = path.join(
+ directory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const fullCanonical = path.join(
+ directory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(emptyCanonical, '');
+ fs.writeFileSync(fullCanonical, `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/existing/full' },
+ })}\n`);
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /private rollout may still be materializing/,
+ );
+ expect(fs.existsSync(emptyCanonical)).toBe(true);
+ expect(fs.existsSync(fullCanonical)).toBe(true);
+ });
+
+ it('restores one interrupted native canonical after moving another stable empty aside', async () => {
+ createStateDb(desktopHome());
+ const directory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const emptyCanonical = path.join(
+ directory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const nativeCanonical = path.join(
+ directory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const preservedNative = path.join(
+ directory,
+ `rollout-cindy-preserved-empty-${path.basename(nativeCanonical)}`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/interrupted/native' },
+ })}\n`;
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(emptyCanonical, '');
+ fs.writeFileSync(preservedNative, nativeContents);
+ markEmptyRolloutStable(emptyCanonical);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(nativeCanonical);
+ expect(fs.readFileSync(nativeCanonical, 'utf-8')).toBe(nativeContents);
+ expect(fs.readdirSync(directory).filter((name) => /^rollout-\d/.test(name))).toEqual([
+ path.basename(nativeCanonical),
+ ]);
+ });
+
+ it('does not restore an interrupted native canonical beside a recent empty writer', async () => {
+ createStateDb(desktopHome());
+ const directory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const recentEmpty = path.join(
+ directory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const nativeCanonical = path.join(
+ directory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const preservedNative = path.join(
+ directory,
+ `rollout-cindy-preserved-empty-${path.basename(nativeCanonical)}`,
+ );
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(recentEmpty, '');
+ fs.writeFileSync(preservedNative, `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/interrupted/native' },
+ })}\n`);
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /private rollout may still be materializing/,
+ );
+ expect(fs.existsSync(nativeCanonical)).toBe(false);
+ expect(fs.existsSync(recentEmpty)).toBe(true);
+ });
+
+ it('adopts a rollout-only external source over a differently named stable canonical empty', async () => {
+ createStateDb(desktopHome());
+ const targetDirectory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const emptyCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(targetDirectory, { recursive: true });
+ fs.writeFileSync(emptyCanonical, '');
+ markEmptyRolloutStable(emptyCanonical);
+
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const externalContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/full' },
+ })}\n${rolloutLine(
+ 'rollout-only-m1',
+ 'user',
+ 'preserve all external bytes',
+ '2026-08-03T12:00:01.000Z',
+ )}\n`;
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, externalContents);
+
+ const prepared = await prepareExternalCodexSessionForResume(threadId);
+
+ expect(prepared).toBe(emptyCanonical);
+ expect(fs.readFileSync(emptyCanonical, 'utf-8')).toBe(externalContents);
+ expect(fs.readFileSync(externalRollout, 'utf-8')).toBe(externalContents);
+ const canonicalNames = fs.readdirSync(targetDirectory).filter(
+ (name) => /^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-/.test(name)
+ && name.endsWith(`${threadId}.jsonl`),
+ );
+ expect(canonicalNames).toEqual([path.basename(emptyCanonical)]);
+ });
+
+ it('rejects a same-content staging inode swap before full state-less publication', async () => {
+ createStateDb(desktopHome());
+ const targetDirectory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const canonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(targetDirectory, { recursive: true });
+ fs.writeFileSync(canonical, '');
+ markEmptyRolloutStable(canonical);
+
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const externalContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/full' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, externalContents);
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ let swapped = false;
+ const linkSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ if (
+ !swapped
+ && path.resolve(target.toString()) === path.resolve(canonical)
+ && path.basename(source.toString()).startsWith('rollout-cindy-adopted')
+ ) {
+ const stagedPath = source.toString();
+ const capturedInode = `${stagedPath}.captured-inode`;
+ fs.renameSync(stagedPath, capturedInode);
+ fs.copyFileSync(capturedInode, stagedPath);
+ swapped = true;
+ }
+ return realLinkSync(source, target);
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /external rollout publication changed before handoff/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(swapped).toBe(true);
+ expect(fs.readFileSync(canonical, 'utf-8')).toBe('');
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(canonical);
+ expect(fs.readFileSync(canonical, 'utf-8')).toBe(externalContents);
+ });
+
+ it('keeps the external canonical when a retained writer fills after link commit', async () => {
+ createStateDb(desktopHome());
+ const directory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const canonical = path.join(
+ directory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(canonical, '');
+ markEmptyRolloutStable(canonical);
+
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const externalContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/full' },
+ })}\n`;
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/retained/local-writer' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, externalContents);
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ let filled = false;
+ const linkSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ const linked = realLinkSync(source, target);
+ if (
+ !filled
+ && target.toString() === canonical
+ && path.basename(source.toString()).startsWith('rollout-cindy-adopted')
+ ) {
+ const preserved = fs.readdirSync(directory)
+ .map((name) => path.join(directory, name))
+ .find((candidate) => path.basename(candidate).startsWith('rollout-cindy-preserved-empty'));
+ expect(preserved).toBeTruthy();
+ fs.writeFileSync(preserved!, nativeContents);
+ filled = true;
+ }
+ return linked;
+ });
+ let prepared: string | undefined;
+ try {
+ prepared = await prepareExternalCodexSessionForResume(threadId);
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(prepared).toBe(canonical);
+ expect(fs.readFileSync(canonical, 'utf-8')).toBe(externalContents);
+ expect(fs.readFileSync(externalRollout, 'utf-8')).toBe(externalContents);
+ const preserved = fs.readdirSync(directory)
+ .map((name) => path.join(directory, name))
+ .find((candidate) => path.basename(candidate).startsWith('rollout-cindy-preserved-empty'));
+ expect(preserved).toBeTruthy();
+ expect(fs.readFileSync(preserved!, 'utf-8')).toBe(nativeContents);
+ expect(fs.readdirSync(directory).filter((name) => /^rollout-\d/.test(name))).toEqual([
+ path.basename(canonical),
+ ]);
+ });
+
+ it('retries when rollback leaves a same-inode preservation alias beside the canonical', async () => {
+ createStateDb(desktopHome());
+ const sessionId = `local-stale-preservation-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'stale-preservation-c1',
+ 'user',
+ JSON.stringify({ text: 'recover after stale preservation alias' }),
+ 1_000,
+ );
+ const canonical = path.join(
+ desktopHome(),
+ 'sessions',
+ '1970',
+ '01',
+ '01',
+ `rollout-1970-01-01T00-00-01-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(canonical), { recursive: true });
+ fs.writeFileSync(canonical, '');
+ markEmptyRolloutStable(canonical);
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ const realUnlinkSync = fs.unlinkSync.bind(fs);
+ let publicationFailed = false;
+ let cleanupFailed = false;
+ const linkSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ if (
+ !publicationFailed
+ && target.toString() === canonical
+ && path.basename(source.toString()).startsWith('.cindy-state-less-recovery')
+ ) {
+ publicationFailed = true;
+ throw Object.assign(new Error('publication denied'), { code: 'EPERM' });
+ }
+ return realLinkSync(source, target);
+ });
+ const unlinkSpy = vi.spyOn(fs, 'unlinkSync').mockImplementation((candidate) => {
+ if (
+ publicationFailed
+ && !cleanupFailed
+ && fs.existsSync(canonical)
+ && path.basename(candidate.toString()).startsWith('rollout-cindy-preserved-empty')
+ ) {
+ cleanupFailed = true;
+ throw Object.assign(new Error('cleanup denied'), { code: 'EACCES' });
+ }
+ return realUnlinkSync(candidate);
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /state-less empty rollout recovery failed/,
+ );
+ } finally {
+ unlinkSpy.mockRestore();
+ linkSpy.mockRestore();
+ }
+
+ const preservedPath = fs.readdirSync(path.dirname(canonical))
+ .map((name) => path.join(path.dirname(canonical), name))
+ .find((candidate) => path.basename(candidate).startsWith('rollout-cindy-preserved-empty'));
+ expect(preservedPath).toBeTruthy();
+ expect(fs.statSync(preservedPath!).ino).toBe(fs.statSync(canonical).ino);
+ markEmptyRolloutStable(canonical);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(canonical);
+ expect(fs.readFileSync(canonical, 'utf-8')).toContain('recover after stale preservation alias');
+ });
+
+ it('retries from filtered artifacts when publication and canonical restoration both fail', async () => {
+ createStateDb(desktopHome());
+ const sessionId = `local-missing-after-rollback-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'missing-after-rollback-c1',
+ 'user',
+ JSON.stringify({ text: 'recover after canonical stayed missing' }),
+ 1_000,
+ );
+ const canonical = path.join(
+ desktopHome(),
+ 'sessions',
+ '1970',
+ '01',
+ '01',
+ `rollout-1970-01-01T00-00-01-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(canonical), { recursive: true });
+ fs.writeFileSync(canonical, '');
+ markEmptyRolloutStable(canonical);
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ const linkSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ if (
+ target.toString() === canonical
+ && (
+ path.basename(source.toString()).startsWith('.cindy-state-less-recovery')
+ || path.basename(source.toString()).startsWith('rollout-cindy-preserved-empty')
+ )
+ ) {
+ throw Object.assign(new Error('canonical link failed'), { code: 'EIO' });
+ }
+ return realLinkSync(source, target);
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /state-less empty rollout recovery failed/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(fs.existsSync(canonical)).toBe(false);
+ expect(fs.readdirSync(path.dirname(canonical)).some(
+ (name) => name.startsWith('rollout-cindy-preserved-empty'),
+ )).toBe(true);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(canonical);
+ expect(fs.readFileSync(canonical, 'utf-8')).toContain('recover after canonical stayed missing');
+ });
+
+ it('restores a native writer that fills a preserved inode while canonical restoration is down', async () => {
+ createStateDb(desktopHome());
+ const sessionId = `local-native-after-crash-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'native-after-crash-c1',
+ 'user',
+ JSON.stringify({ text: 'synthetic must not replace native' }),
+ 1_000,
+ );
+ const canonical = path.join(
+ desktopHome(),
+ 'sessions',
+ '1970',
+ '01',
+ '01',
+ `rollout-1970-01-01T00-00-01-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(canonical), { recursive: true });
+ fs.writeFileSync(canonical, '');
+ markEmptyRolloutStable(canonical);
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ const linkSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ if (
+ target.toString() === canonical
+ && (
+ path.basename(source.toString()).startsWith('.cindy-state-less-recovery')
+ || path.basename(source.toString()).startsWith('rollout-cindy-preserved-empty')
+ )
+ ) {
+ throw Object.assign(new Error('canonical link failed'), { code: 'EIO' });
+ }
+ return realLinkSync(source, target);
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /state-less empty rollout recovery failed/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ const preservedPath = fs.readdirSync(path.dirname(canonical))
+ .map((name) => path.join(path.dirname(canonical), name))
+ .find((candidate) => path.basename(candidate).startsWith('rollout-cindy-preserved-empty'));
+ expect(preservedPath).toBeTruthy();
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/writer' },
+ })}\n${rolloutLine(
+ 'native-after-crash-m1',
+ 'assistant',
+ 'native writer won before handoff',
+ '2026-08-03T12:00:00.000Z',
+ )}\n`;
+ fs.writeFileSync(preservedPath!, nativeContents);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(canonical);
+ expect(fs.readFileSync(canonical, 'utf-8')).toBe(nativeContents);
+ });
+
+ it('copies a valid external rollout beside an empty private adoption target', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const sourceContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/tmp/project' },
+ })}\n${rolloutLine('m1', 'user', 'external history', '2026-08-03T11:56:19.000Z')}\n`;
+ const sourceDbPath = createStateDb(externalHome);
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, sourceContents);
+ insertThread(sourceDbPath, threadId, sourceRollout, { updatedAt: 2_000 });
+
+ const targetDbPath = createStateDb(desktopHome());
+ const interruptedTarget = path.join(
+ desktopHome(),
+ path.relative(externalHome, sourceRollout),
+ );
+ fs.mkdirSync(path.dirname(interruptedTarget), { recursive: true });
+ fs.writeFileSync(interruptedTarget, '');
+ markEmptyRolloutStable(interruptedTarget);
+
+ const prepared = await prepareExternalCodexSessionForResume(threadId);
+
+ expect(prepared).toBeTruthy();
+ expect(prepared).not.toBe(interruptedTarget);
+ expect(fs.readFileSync(sourceRollout, 'utf-8')).toBe(sourceContents);
+ expect(fs.existsSync(interruptedTarget)).toBe(false);
+ const preservedTarget = fs.readdirSync(path.dirname(interruptedTarget))
+ .map((name) => path.join(path.dirname(interruptedTarget), name))
+ .find((candidate) => (
+ path.basename(candidate).startsWith('rollout-cindy-preserved-empty')
+ && path.basename(candidate).endsWith(path.basename(interruptedTarget))
+ ));
+ expect(preservedTarget).toBeTruthy();
+ expect(fs.readFileSync(preservedTarget!, 'utf-8')).toBe('');
+ expect(fs.readFileSync(prepared!, 'utf-8')).toBe(sourceContents);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(prepared);
+ });
+
+ it.each(['full', 'empty', 'missing'] as const)(
+ 'rolls back a state-backed %s handoff when the primary native writer wakes inside the transaction',
+ async (sourceKind) => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const externalContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/state-backed' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ if (sourceKind === 'full') fs.writeFileSync(sourceRollout, externalContents);
+ if (sourceKind === 'empty') {
+ fs.writeFileSync(sourceRollout, '');
+ markEmptyRolloutStable(sourceRollout);
+ }
+ const sourceDbPath = createStateDb(externalHome);
+ insertThread(sourceDbPath, threadId, sourceRollout, { updatedAt: 2_000 });
+
+ const targetDbPath = createStateDb(desktopHome());
+ const primary = path.join(
+ desktopHome(),
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(primary), { recursive: true });
+ fs.writeFileSync(primary, '');
+ markEmptyRolloutStable(primary);
+ const sessionId = `local-primary-${sourceKind}-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ `primary-${sourceKind}-c1`,
+ 'user',
+ JSON.stringify({ text: 'synthetic fallback must not hide the native writer' }),
+ 1_000,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: `/native/${sourceKind}` },
+ })}\n`;
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ const realLink = fs.promises.link.bind(fs.promises);
+ const realLstat = fs.lstatSync.bind(fs);
+ let preservedPrimary: string | null = null;
+ let publicationReady = false;
+ let preservedLstatCount = 0;
+ let filled = false;
+ const linkSyncSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ const linked = realLinkSync(source, target);
+ if (
+ path.resolve(source.toString()) === path.resolve(primary)
+ && path.basename(target.toString()).startsWith('rollout-cindy-preserved-empty')
+ ) preservedPrimary = path.resolve(target.toString());
+ return linked;
+ });
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ path.resolve(target.toString()).startsWith(path.resolve(desktopHome()))
+ && path.basename(target.toString()).startsWith('rollout-cindy-')
+ ) publicationReady = true;
+ });
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((file: fs.PathLike) => {
+ const observed = realLstat(file);
+ if (
+ publicationReady
+ && preservedPrimary
+ && path.resolve(file.toString()) === preservedPrimary
+ && !filled
+ ) {
+ preservedLstatCount += 1;
+ if (preservedLstatCount === 3) {
+ fs.writeFileSync(preservedPrimary, nativeContents);
+ filled = true;
+ }
+ }
+ return observed;
+ }) as typeof fs.lstatSync);
+
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /primary private rollout changed before state handoff/,
+ );
+ } finally {
+ lstatSpy.mockRestore();
+ linkSpy.mockRestore();
+ linkSyncSpy.mockRestore();
+ }
+
+ expect(filled).toBe(true);
+ expect(fs.existsSync(primary)).toBe(false);
+ expect(preservedPrimary).toBeTruthy();
+ expect(fs.readFileSync(preservedPrimary!, 'utf-8')).toBe(nativeContents);
+ let targetDb = new Database(targetDbPath, { readonly: true });
+ const targetCount = targetDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ targetDb.close();
+ expect(targetCount.count).toBe(0);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(primary);
+ expect(fs.readFileSync(primary, 'utf-8')).toBe(nativeContents);
+ targetDb = new Database(targetDbPath, { readonly: true });
+ const restoredCount = targetDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ targetDb.close();
+ expect(restoredCount.count).toBe(0);
+ },
+ );
+
+ it('keeps a state-backed publication after commit when the preserved primary writer wakes later', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const sourceContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/state-backed' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, sourceContents);
+ const sourceDbPath = createStateDb(externalHome);
+ insertThread(sourceDbPath, threadId, sourceRollout, { updatedAt: 2_000 });
+
+ const targetDbPath = createStateDb(desktopHome());
+ const primary = path.join(
+ desktopHome(),
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(primary), { recursive: true });
+ fs.writeFileSync(primary, '');
+ markEmptyRolloutStable(primary);
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/post-commit' },
+ })}\n`;
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ const realLink = fs.promises.link.bind(fs.promises);
+ const realLstat = fs.lstatSync.bind(fs);
+ let preservedPrimary: string | null = null;
+ let publication: string | null = null;
+ let filledAfterCommit = false;
+ const linkSyncSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ const linked = realLinkSync(source, target);
+ if (
+ path.resolve(source.toString()) === path.resolve(primary)
+ && path.basename(target.toString()).startsWith('rollout-cindy-preserved-empty')
+ ) preservedPrimary = path.resolve(target.toString());
+ return linked;
+ });
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (path.basename(target.toString()).startsWith('rollout-cindy-adopted')) {
+ publication = path.resolve(target.toString());
+ }
+ });
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((file: fs.PathLike) => {
+ if (
+ publication
+ && preservedPrimary
+ && !filledAfterCommit
+ && path.resolve(file.toString()) === publication
+ ) {
+ let probe: Database.Database | null = null;
+ try {
+ probe = new Database(targetDbPath, { readonly: true });
+ const row = probe
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath?: string } | undefined;
+ if (row?.rolloutPath === publication) {
+ fs.writeFileSync(preservedPrimary, nativeContents);
+ filledAfterCommit = true;
+ }
+ } catch {
+ // The IMMEDIATE transaction has not committed yet.
+ } finally {
+ probe?.close();
+ }
+ }
+ return realLstat(file);
+ }) as typeof fs.lstatSync);
+
+ let prepared: string | undefined;
+ try {
+ prepared = await prepareExternalCodexSessionForResume(threadId);
+ } finally {
+ lstatSpy.mockRestore();
+ linkSpy.mockRestore();
+ linkSyncSpy.mockRestore();
+ }
+
+ expect(filledAfterCommit).toBe(true);
+ expect(prepared).toBe(publication);
+ expect(fs.existsSync(primary)).toBe(false);
+ expect(fs.readFileSync(preservedPrimary!, 'utf-8')).toBe(nativeContents);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(publication);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(publication);
+ expect(fs.readFileSync(publication!, 'utf-8')).toBe(sourceContents);
+ });
+
+ it('reconciles a pre-handoff native writer after a concurrent external row survives rollback', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const sourceContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/concurrent-row' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, sourceContents);
+ const sourceDbPath = createStateDb(externalHome);
+ insertThread(sourceDbPath, threadId, sourceRollout, { updatedAt: 2_000 });
+
+ const targetDbPath = createStateDb(desktopHome());
+ const primary = path.join(
+ desktopHome(),
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(primary), { recursive: true });
+ fs.writeFileSync(primary, '');
+ markEmptyRolloutStable(primary);
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/concurrent-row' },
+ })}\n`;
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ const realLink = fs.promises.link.bind(fs.promises);
+ const realLstat = fs.lstatSync.bind(fs);
+ let preservedPrimary: string | null = null;
+ let publicationReady = false;
+ let preservedLstatCount = 0;
+ let filled = false;
+ const linkSyncSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ const linked = realLinkSync(source, target);
+ if (
+ path.resolve(source.toString()) === path.resolve(primary)
+ && path.basename(target.toString()).startsWith('rollout-cindy-preserved-empty')
+ ) preservedPrimary = path.resolve(target.toString());
+ return linked;
+ });
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ !publicationReady
+ && path.basename(target.toString()).startsWith('rollout-cindy-adopted')
+ ) {
+ insertThread(targetDbPath, threadId, sourceRollout, { updatedAt: 3_000 });
+ publicationReady = true;
+ }
+ });
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((file: fs.PathLike) => {
+ const observed = realLstat(file);
+ if (
+ publicationReady
+ && preservedPrimary
+ && !filled
+ && path.resolve(file.toString()) === preservedPrimary
+ ) {
+ preservedLstatCount += 1;
+ if (preservedLstatCount === 3) {
+ fs.writeFileSync(preservedPrimary, nativeContents);
+ filled = true;
+ }
+ }
+ return observed;
+ }) as typeof fs.lstatSync);
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /concurrent state prevented safe private adoption/,
+ );
+ } finally {
+ lstatSpy.mockRestore();
+ linkSpy.mockRestore();
+ linkSyncSpy.mockRestore();
+ }
+
+ expect(filled).toBe(true);
+ let targetDb = new Database(targetDbPath, { readonly: true });
+ let targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(sourceRollout);
+ expect(fs.existsSync(primary)).toBe(false);
+ expect(fs.readFileSync(preservedPrimary!, 'utf-8')).toBe(nativeContents);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(primary);
+ targetDb = new Database(targetDbPath, { readonly: true });
+ targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(primary);
+ expect(fs.readFileSync(primary, 'utf-8')).toBe(nativeContents);
+ expect(fs.readFileSync(primary, 'utf-8')).not.toBe(sourceContents);
+ });
+
+ it('blocks a recent private canonical writer before considering an external rollout', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const sourceContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/tmp/project' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, sourceContents);
+ const sourceDbPath = createStateDb(externalHome);
+ insertThread(sourceDbPath, threadId, sourceRollout, { updatedAt: 2_000 });
+ const targetDbPath = createStateDb(desktopHome());
+ const privateCanonical = path.join(desktopHome(), path.relative(externalHome, sourceRollout));
+ fs.mkdirSync(path.dirname(privateCanonical), { recursive: true });
+ fs.writeFileSync(privateCanonical, '');
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /private rollout may still be materializing/,
+ );
+
+ expect(fs.readFileSync(privateCanonical, 'utf-8')).toBe('');
+ expect(fs.readFileSync(sourceRollout, 'utf-8')).toBe(sourceContents);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const stateCount = targetDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ targetDb.close();
+ expect(stateCount.count).toBe(0);
+ });
+
+ it('blocks a recent private canonical created between state-backed recovery scans', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const sourceContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/state-backed-race' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, sourceContents);
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, sourceRollout, { updatedAt: 3_000 });
+
+ const targetSessionsDir = path.join(desktopHome(), 'sessions');
+ const privateCanonical = path.join(
+ targetSessionsDir,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(targetSessionsDir, { recursive: true });
+ const injection = materializeAfterInitialPrivateCanonicalScan(
+ targetSessionsDir,
+ () => fs.writeFileSync(privateCanonical, ''),
+ );
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /private rollout may still be materializing/,
+ );
+ } finally {
+ injection.restore();
+ }
+
+ expect(injection.didMaterialize()).toBe(true);
+ expect(fs.readFileSync(privateCanonical, 'utf-8')).toBe('');
+ expect(fs.readdirSync(targetSessionsDir)).toEqual([path.basename(privateCanonical)]);
+ expect(fs.readFileSync(sourceRollout, 'utf-8')).toBe(sourceContents);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(sourceRollout);
+ });
+
+ it('blocks a recent private canonical before recovering a missing external pointer', async () => {
+ const missingSourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, missingSourceRollout, { updatedAt: 3_000 });
+ const sessionId = `local-missing-external-second-scan-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'missing-external-second-scan-c1',
+ 'user',
+ JSON.stringify({ text: 'synthetic recovery must wait' }),
+ 1_000,
+ );
+
+ const targetSessionsDir = path.join(desktopHome(), 'sessions');
+ const privateCanonical = path.join(
+ targetSessionsDir,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(targetSessionsDir, { recursive: true });
+ const injection = materializeAfterInitialPrivateCanonicalScan(
+ targetSessionsDir,
+ () => fs.writeFileSync(privateCanonical, ''),
+ );
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /private rollout may still be materializing/,
+ );
+ } finally {
+ injection.restore();
+ }
+
+ expect(injection.didMaterialize()).toBe(true);
+ expect(fs.readFileSync(privateCanonical, 'utf-8')).toBe('');
+ expect(fs.readdirSync(targetSessionsDir)).toEqual([path.basename(privateCanonical)]);
+ expect(fs.existsSync(missingSourceRollout)).toBe(false);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(missingSourceRollout);
+ });
+
+ it('retries a full private canonical created between state-backed recovery scans', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/state-backed-race' },
+ })}\n`);
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, sourceRollout, { updatedAt: 3_000 });
+
+ const targetSessionsDir = path.join(desktopHome(), 'sessions');
+ const privateCanonical = path.join(
+ targetSessionsDir,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/second-scan-winner' },
+ })}\n`;
+ fs.mkdirSync(targetSessionsDir, { recursive: true });
+ const injection = materializeAfterInitialPrivateCanonicalScan(
+ targetSessionsDir,
+ () => fs.writeFileSync(privateCanonical, nativeContents),
+ );
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /private canonical rollout materialized during recovery planning/,
+ );
+ } finally {
+ injection.restore();
+ }
+
+ expect(injection.didMaterialize()).toBe(true);
+ expect(fs.readFileSync(privateCanonical, 'utf-8')).toBe(nativeContents);
+ let targetDb = new Database(targetDbPath, { readonly: true });
+ let targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(sourceRollout);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(privateCanonical);
+ targetDb = new Database(targetDbPath, { readonly: true });
+ targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(privateCanonical);
+ expect(fs.readFileSync(privateCanonical, 'utf-8')).toBe(nativeContents);
+ });
+
+ it('blocks a recent different canonical created during hidden external adoption', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const sourceContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/hidden-adoption' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, sourceContents);
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, sourceRollout, { updatedAt: 3_000 });
+
+ const privateCanonical = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const preferredAdoption = path.join(desktopHome(), path.relative(externalHome, sourceRollout));
+ const realLink = fs.promises.link.bind(fs.promises);
+ let materialized = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ !materialized
+ && path.basename(target.toString()).startsWith('rollout-cindy-adopted')
+ ) {
+ fs.mkdirSync(path.dirname(privateCanonical), { recursive: true });
+ fs.writeFileSync(privateCanonical, '');
+ materialized = true;
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /external rollout pointer changed during private adoption/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(fs.readFileSync(privateCanonical, 'utf-8')).toBe('');
+ expect(fs.existsSync(preferredAdoption)).toBe(false);
+ expect(fs.readFileSync(sourceRollout, 'utf-8')).toBe(sourceContents);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(sourceRollout);
+ });
+
+ it('rolls back when a different canonical appears after the state update', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/post-update-race' },
+ })}\n`);
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, sourceRollout, { updatedAt: 3_000 });
+
+ const targetSessionsDir = path.join(desktopHome(), 'sessions');
+ const privateCanonical = path.join(
+ targetSessionsDir,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/post-update-winner' },
+ })}\n`;
+ const realLink = fs.promises.link.bind(fs.promises);
+ const realReaddirSync = fs.readdirSync;
+ let publicationReady = false;
+ let namespaceScanCount = 0;
+ let materialized = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (path.basename(target.toString()).startsWith('rollout-cindy-adopted')) {
+ publicationReady = true;
+ }
+ });
+ const readdirSpy = vi.spyOn(fs, 'readdirSync').mockImplementation((function (
+ directory: fs.PathLike,
+ options?: unknown,
+ ) {
+ if (
+ publicationReady
+ && path.resolve(directory.toString()) === path.resolve(targetSessionsDir)
+ ) {
+ namespaceScanCount += 1;
+ // The first scan is the pre-UPDATE guard; inject into the second so
+ // throwing from the post-UPDATE guard must roll the transaction back.
+ if (namespaceScanCount === 2) {
+ fs.writeFileSync(privateCanonical, nativeContents);
+ materialized = true;
+ }
+ }
+ return Reflect.apply(realReaddirSync, fs, [directory, options]);
+ }) as typeof fs.readdirSync);
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /external rollout pointer changed during private adoption/,
+ );
+ } finally {
+ readdirSpy.mockRestore();
+ linkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(namespaceScanCount).toBeGreaterThanOrEqual(2);
+ expect(fs.readFileSync(privateCanonical, 'utf-8')).toBe(nativeContents);
+ let targetDb = new Database(targetDbPath, { readonly: true });
+ let targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(sourceRollout);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(privateCanonical);
+ targetDb = new Database(targetDbPath, { readonly: true });
+ targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(privateCanonical);
+ });
+
+ it('keeps a missing private pointer when another canonical appears during fallback copy', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/private-missing-race' },
+ })}\n`);
+ const sourceDbPath = createStateDb(externalHome);
+ insertThread(sourceDbPath, threadId, sourceRollout, { updatedAt: 2_000 });
+
+ const targetDbPath = createStateDb(desktopHome());
+ const missingPrivate = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const privateCanonical = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03T13-00-00-${threadId}.jsonl`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/private-missing-winner' },
+ })}\n`;
+ insertThread(targetDbPath, threadId, missingPrivate, { updatedAt: 3_000 });
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let materialized = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ !materialized
+ && path.basename(target.toString()).startsWith('rollout-cindy-adopted')
+ ) {
+ fs.writeFileSync(privateCanonical, nativeContents);
+ materialized = true;
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /private orphan pointer changed during adoption/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(fs.existsSync(missingPrivate)).toBe(false);
+ expect(fs.readFileSync(privateCanonical, 'utf-8')).toBe(nativeContents);
+ let targetDb = new Database(targetDbPath, { readonly: true });
+ let targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(missingPrivate);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(privateCanonical);
+ targetDb = new Database(targetDbPath, { readonly: true });
+ targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(privateCanonical);
+ });
+
+ it('rejects a second canonical before returning a state-pointed native winner', async () => {
+ const targetDbPath = createStateDb(desktopHome());
+ const targetDirectory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const primaryCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const secondCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const primaryContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/state-primary' },
+ })}\n`;
+ const secondContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/state-second' },
+ })}\n`;
+ fs.mkdirSync(targetDirectory, { recursive: true });
+ fs.writeFileSync(primaryCanonical, '');
+ markEmptyRolloutStable(primaryCanonical);
+ insertThread(targetDbPath, threadId, primaryCanonical, { updatedAt: 3_000 });
+ const sessionId = `local-state-native-return-race-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'state-native-return-race-c1',
+ 'user',
+ JSON.stringify({ text: 'do not return into a split canonical namespace' }),
+ 1_000,
+ );
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let materialized = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ !materialized
+ && path.basename(target.toString()).startsWith('rollout-cindy-empty-recovery')
+ ) {
+ fs.writeFileSync(primaryCanonical, primaryContents);
+ fs.writeFileSync(secondCanonical, secondContents);
+ materialized = true;
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /canonical rollout namespace changed during recovery handoff/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(fs.readFileSync(primaryCanonical, 'utf-8')).toBe(primaryContents);
+ expect(fs.readFileSync(secondCanonical, 'utf-8')).toBe(secondContents);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(primaryCanonical);
+ });
+
+ it('rejects a late canonical before returning a committed state-backed copy', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const sourceContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/state-return-race' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, sourceContents);
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, sourceRollout, { updatedAt: 3_000 });
+
+ const targetDirectory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const lateCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const lateContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/state-return-winner' },
+ })}\n`;
+ const realLink = fs.promises.link.bind(fs.promises);
+ const realLstat = fs.lstatSync.bind(fs);
+ let adoptedPath: string | null = null;
+ let materialized = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (path.basename(target.toString()).startsWith('rollout-cindy-adopted')) {
+ adoptedPath = path.resolve(target.toString());
+ }
+ });
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((candidate: fs.PathLike) => {
+ if (
+ adoptedPath
+ && !materialized
+ && path.resolve(candidate.toString()) === adoptedPath
+ ) {
+ let probe: Database.Database | null = null;
+ try {
+ probe = new Database(targetDbPath, { readonly: true });
+ const state = probe
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ if (path.resolve(state.rolloutPath) === adoptedPath) {
+ fs.mkdirSync(targetDirectory, { recursive: true });
+ fs.writeFileSync(lateCanonical, lateContents);
+ materialized = true;
+ }
+ } catch {
+ // The state handoff transaction may not have committed yet.
+ } finally {
+ probe?.close();
+ }
+ }
+ return realLstat(candidate);
+ }) as typeof fs.lstatSync);
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /canonical rollout namespace changed during recovery handoff/,
+ );
+ } finally {
+ lstatSpy.mockRestore();
+ linkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(adoptedPath).toBeTruthy();
+ expect(fs.readFileSync(adoptedPath!, 'utf-8')).toBe(sourceContents);
+ expect(fs.readFileSync(lateCanonical, 'utf-8')).toBe(lateContents);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(path.resolve(targetRow.rolloutPath)).toBe(adoptedPath);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(adoptedPath);
+ });
+
+ it('keeps a state-less external adoption from publishing beside a new native canonical', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/rollout-only-race' },
+ })}\n`);
+ const targetDbPath = createStateDb(desktopHome());
+ const preferred = path.join(desktopHome(), path.relative(externalHome, sourceRollout));
+ const privateCanonical = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/rollout-only-winner' },
+ })}\n`;
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let materialized = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ !materialized
+ && path.basename(target.toString()).startsWith('rollout-cindy-adopted')
+ ) {
+ fs.mkdirSync(path.dirname(privateCanonical), { recursive: true });
+ fs.writeFileSync(privateCanonical, nativeContents);
+ materialized = true;
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /canonical rollout namespace changed during recovery handoff/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(fs.existsSync(preferred)).toBe(false);
+ expect(fs.readFileSync(privateCanonical, 'utf-8')).toBe(nativeContents);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const stateCount = targetDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ targetDb.close();
+ expect(stateCount.count).toBe(0);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(privateCanonical);
+ });
+
+ it('never publishes a rollout-only snapshot directly when the stable canonical disappears', async () => {
+ createStateDb(desktopHome());
+ const targetDirectory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const originalCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const preservedOriginal = path.join(
+ targetDirectory,
+ `rollout-cindy-preserved-empty-${path.basename(originalCanonical)}`,
+ );
+ const nativeCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T13-00-00-${threadId}.jsonl`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/staging-gap-winner' },
+ })}\n`;
+ fs.mkdirSync(targetDirectory, { recursive: true });
+ fs.writeFileSync(originalCanonical, '');
+ markEmptyRolloutStable(originalCanonical);
+
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const sourceContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/staging-gap' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, sourceContents);
+
+ const realExistsSync = fs.existsSync.bind(fs);
+ let materialized = false;
+ const existsSpy = vi.spyOn(fs, 'existsSync').mockImplementation((candidate) => {
+ const candidatePath = candidate.toString();
+ const isPublicationProbe = path.resolve(candidatePath) === path.resolve(originalCanonical)
+ || path.basename(candidatePath).startsWith('rollout-cindy-adopted');
+ if (!materialized && isPublicationProbe) {
+ fs.renameSync(originalCanonical, preservedOriginal);
+ fs.writeFileSync(nativeCanonical, nativeContents);
+ materialized = true;
+ }
+ return realExistsSync(candidate);
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /stable empty canonical changed before preservation/,
+ );
+ } finally {
+ existsSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(fs.existsSync(originalCanonical)).toBe(false);
+ expect(fs.readFileSync(preservedOriginal, 'utf-8')).toBe('');
+ expect(fs.readFileSync(nativeCanonical, 'utf-8')).toBe(nativeContents);
+ expect(fs.readFileSync(sourceRollout, 'utf-8')).toBe(sourceContents);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(nativeCanonical);
+ });
+
+ it('keeps a state-less synthetic handoff from publishing beside a new native canonical', async () => {
+ const targetDbPath = createStateDb(desktopHome());
+ const sessionId = `local-state-less-namespace-race-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'state-less-namespace-race-c1',
+ 'user',
+ JSON.stringify({ text: 'synthetic must not fork the native history' }),
+ 1_000,
+ );
+ const preferred = path.join(
+ desktopHome(),
+ 'sessions',
+ '1970',
+ '01',
+ '01',
+ `rollout-1970-01-01T00-00-01-${threadId}.jsonl`,
+ );
+ const privateCanonical = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/state-less-synthetic-winner' },
+ })}\n`;
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let materialized = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ !materialized
+ && path.basename(target.toString()).startsWith('.cindy-state-less-recovery')
+ ) {
+ fs.mkdirSync(path.dirname(privateCanonical), { recursive: true });
+ fs.writeFileSync(privateCanonical, nativeContents);
+ materialized = true;
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /canonical rollout namespace changed during recovery handoff/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(fs.existsSync(preferred)).toBe(false);
+ expect(fs.readFileSync(privateCanonical, 'utf-8')).toBe(nativeContents);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const stateCount = targetDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ targetDb.close();
+ expect(stateCount.count).toBe(0);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(privateCanonical);
+ });
+
+ it('rejects a second canonical when the primary writer wakes before preservation', async () => {
+ createStateDb(desktopHome());
+ const sessionId = `local-native-winner-namespace-race-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'native-winner-namespace-race-c1',
+ 'user',
+ JSON.stringify({ text: 'do not accept two native histories' }),
+ 1_000,
+ );
+ const targetDirectory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const primaryCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const secondCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const primaryContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/primary-writer' },
+ })}\n`;
+ const secondContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/second-writer' },
+ })}\n`;
+ fs.mkdirSync(targetDirectory, { recursive: true });
+ fs.writeFileSync(primaryCanonical, '');
+ markEmptyRolloutStable(primaryCanonical);
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let materialized = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ !materialized
+ && path.basename(target.toString()).startsWith('.cindy-state-less-recovery')
+ ) {
+ fs.writeFileSync(primaryCanonical, primaryContents);
+ fs.writeFileSync(secondCanonical, secondContents);
+ materialized = true;
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /namespace changed before completing the handoff/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(fs.readFileSync(primaryCanonical, 'utf-8')).toBe(primaryContents);
+ expect(fs.readFileSync(secondCanonical, 'utf-8')).toBe(secondContents);
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /multiple private canonical rollouts conflict/,
+ );
+ });
+
+ it('keeps the primary preserved when another canonical appears before the handoff guard', async () => {
+ createStateDb(desktopHome());
+ const sessionId = `local-preserved-rollback-namespace-race-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'preserved-rollback-namespace-race-c1',
+ 'user',
+ JSON.stringify({ text: 'do not restore beside another canonical' }),
+ 1_000,
+ );
+ const targetDirectory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const primaryCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const preservedPrimary = path.join(
+ targetDirectory,
+ `rollout-cindy-preserved-empty-${path.basename(primaryCanonical)}`,
+ );
+ const nativeCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/post-preservation-winner' },
+ })}\n`;
+ fs.mkdirSync(targetDirectory, { recursive: true });
+ fs.writeFileSync(primaryCanonical, '');
+ markEmptyRolloutStable(primaryCanonical);
+
+ const realUnlinkSync = fs.unlinkSync.bind(fs);
+ let materialized = false;
+ const unlinkSpy = vi.spyOn(fs, 'unlinkSync').mockImplementation((candidate) => {
+ const result = realUnlinkSync(candidate);
+ if (
+ !materialized
+ && path.resolve(candidate.toString()) === path.resolve(primaryCanonical)
+ && fs.existsSync(preservedPrimary)
+ ) {
+ fs.writeFileSync(nativeCanonical, nativeContents);
+ materialized = true;
+ }
+ return result;
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /canonical rollout namespace changed during recovery handoff/,
+ );
+ } finally {
+ unlinkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(fs.existsSync(primaryCanonical)).toBe(false);
+ expect(fs.readFileSync(preservedPrimary, 'utf-8')).toBe('');
+ expect(fs.readFileSync(nativeCanonical, 'utf-8')).toBe(nativeContents);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(nativeCanonical);
+ });
+
+ it('fails closed when another canonical appears after the external canonical link commits', async () => {
+ createStateDb(desktopHome());
+ const targetDirectory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const primaryCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const preservedPrimary = path.join(
+ targetDirectory,
+ `rollout-cindy-preserved-empty-${path.basename(primaryCanonical)}`,
+ );
+ const nativeCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T13-00-00-${threadId}.jsonl`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/post-external-link' },
+ })}\n`;
+ fs.mkdirSync(targetDirectory, { recursive: true });
+ fs.writeFileSync(primaryCanonical, '');
+ markEmptyRolloutStable(primaryCanonical);
+
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const sourceContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/post-link' },
+ })}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, sourceContents);
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ let materialized = false;
+ const linkSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ const result = realLinkSync(source, target);
+ if (
+ !materialized
+ && path.resolve(target.toString()) === path.resolve(primaryCanonical)
+ && path.basename(source.toString()).startsWith('rollout-cindy-adopted')
+ ) {
+ fs.writeFileSync(nativeCanonical, nativeContents);
+ materialized = true;
+ }
+ return result;
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /namespace changed before completing the handoff/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(fs.readFileSync(primaryCanonical, 'utf-8')).toBe(sourceContents);
+ expect(fs.readFileSync(nativeCanonical, 'utf-8')).toBe(nativeContents);
+ expect(fs.readFileSync(preservedPrimary, 'utf-8')).toBe('');
+ expect(fs.readFileSync(sourceRollout, 'utf-8')).toBe(sourceContents);
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /multiple private canonical rollouts conflict/,
+ );
+ });
+
+ it('fails closed when another canonical appears after the synthetic canonical link commits', async () => {
+ createStateDb(desktopHome());
+ const sessionId = `local-post-synthetic-link-race-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'post-synthetic-link-race-c1',
+ 'user',
+ JSON.stringify({ text: 'retain both histories and stop' }),
+ 1_000,
+ );
+ const targetDirectory = path.join(desktopHome(), 'sessions', '2026', '08', '03');
+ const primaryCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ const preservedPrimary = path.join(
+ targetDirectory,
+ `rollout-cindy-preserved-empty-${path.basename(primaryCanonical)}`,
+ );
+ const nativeCanonical = path.join(
+ targetDirectory,
+ `rollout-2026-08-03T12-00-00-${threadId}.jsonl`,
+ );
+ const nativeContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/native/post-synthetic-link' },
+ })}\n`;
+ fs.mkdirSync(targetDirectory, { recursive: true });
+ fs.writeFileSync(primaryCanonical, '');
+ markEmptyRolloutStable(primaryCanonical);
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ let materialized = false;
+ const linkSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ const result = realLinkSync(source, target);
+ if (
+ !materialized
+ && path.resolve(target.toString()) === path.resolve(primaryCanonical)
+ && path.basename(source.toString()).startsWith('.cindy-state-less-recovery')
+ ) {
+ fs.writeFileSync(nativeCanonical, nativeContents);
+ materialized = true;
+ }
+ return result;
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /namespace changed before completing the handoff/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(materialized).toBe(true);
+ expect(fs.readFileSync(primaryCanonical, 'utf-8')).toContain(
+ 'retain both histories and stop',
+ );
+ expect(fs.readFileSync(nativeCanonical, 'utf-8')).toBe(nativeContents);
+ expect(fs.readFileSync(preservedPrimary, 'utf-8')).toBe('');
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /multiple private canonical rollouts conflict/,
+ );
+ });
+
+ it('retries external adoption without publishing a snapshot from an active copy', async () => {
+ const sourceRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ const firstLine = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/tmp/project' },
+ })}\n`;
+ const lateLine = `${rolloutLine('late', 'assistant', 'late external tail', '2026-08-03T12:00:00.000Z')}\n`;
+ fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });
+ fs.writeFileSync(sourceRollout, firstLine);
+ const sourceDbPath = createStateDb(externalHome);
+ insertThread(sourceDbPath, threadId, sourceRollout, { updatedAt: 2_000 });
+ const targetDbPath = createStateDb(desktopHome());
+ const preferred = path.join(desktopHome(), 'sessions', path.basename(sourceRollout));
+
+ const realCopy = fs.promises.copyFile.bind(fs.promises);
+ let appended = false;
+ const copySpy = vi.spyOn(fs.promises, 'copyFile').mockImplementation(async (...args) => {
+ await realCopy(...args);
+ if (!appended) {
+ appended = true;
+ fs.appendFileSync(sourceRollout, lateLine);
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /changed during private adoption/,
+ );
+ } finally {
+ copySpy.mockRestore();
+ }
+
+ expect(fs.existsSync(preferred)).toBe(false);
+ const recovered = await prepareExternalCodexSessionForResume(threadId);
+ expect(recovered).toBeTruthy();
+ expect(recovered).not.toBe(preferred);
+ expect(path.basename(recovered!)).toBe(
+ `rollout-cindy-adopted-${path.basename(sourceRollout)}`,
+ );
+ expect(fs.readFileSync(recovered!, 'utf-8')).toBe(firstLine + lateLine);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(recovered);
+ });
+
+ it('leaves an empty rollout pointer unchanged when no readable history can recover it', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const emptyRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(emptyRollout), { recursive: true });
+ fs.writeFileSync(emptyRollout, '');
+ markEmptyRolloutStable(emptyRollout);
+ insertThread(dbPath, threadId, emptyRollout, { updatedAt: 2_000 });
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /not safe to resume yet/,
+ );
+ expect(fs.readFileSync(emptyRollout, 'utf-8')).toBe('');
+ const stateDb = new Database(dbPath, { readonly: true });
+ const state = stateDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ stateDb.close();
+ expect(state.rolloutPath).toBe(emptyRollout);
+ });
+
+ it('recovers the reported external empty rollout into Cindy private storage (#1554)', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, '');
+ markEmptyRolloutStable(externalRollout);
+ const externalDbPath = createStateDb(externalHome);
+ insertThread(externalDbPath, threadId, externalRollout, { updatedAt: 2_000 });
+
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, externalRollout, {
+ updatedAt: 3_000,
+ title: 'Current Cindy title',
+ });
+ const sessionId = `local-external-empty-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'external-c1',
+ 'user',
+ JSON.stringify({ text: 'continue from the phone' }),
+ 1_000,
+ );
+ insertLocalMessage(sessionId, 'external-c2', 'assistant', 'private recovery', 1_100);
+
+ const prepared = await prepareExternalCodexSessionForResume(threadId);
+
+ expect(prepared).toBeTruthy();
+ expect(prepared).not.toBe(externalRollout);
+ expect(prepared!.startsWith(desktopHome())).toBe(true);
+ expect(fs.readFileSync(externalRollout, 'utf-8')).toBe('');
+ expect(fs.readFileSync(prepared!, 'utf-8')).toContain('continue from the phone');
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath, title FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string; title: string };
+ targetDb.close();
+ expect(targetRow).toEqual({ rolloutPath: prepared, title: 'Current Cindy title' });
+ });
+
+ it('converges external H1 to H2 before publishing the state handoff', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, '');
+ markEmptyRolloutStable(externalRollout);
+ const externalDbPath = createStateDb(externalHome);
+ insertThread(externalDbPath, threadId, externalRollout, { updatedAt: 2_000 });
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, externalRollout, { updatedAt: 3_000 });
+ const sessionId = `local-external-h1-h2-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'external-h1', 'user', JSON.stringify({ text: 'external H1' }), 1_000);
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let advanced = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (
+ !advanced
+ && path.basename(target.toString()).startsWith('rollout-cindy-empty-recovery')
+ ) {
+ advanced = true;
+ insertLocalMessage(sessionId, 'external-h2', 'assistant', 'external H2', 1_100);
+ }
+ });
+ let prepared: string | undefined;
+ try {
+ prepared = await prepareExternalCodexSessionForResume(threadId);
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(prepared).toBeTruthy();
+ expect(path.basename(prepared!)).toBe(
+ `rollout-cindy-empty-recovery-2-${path.basename(externalRollout)}`,
+ );
+ expect(fs.readFileSync(prepared!, 'utf-8')).toContain('external H2');
+ expect(fs.readFileSync(externalRollout, 'utf-8')).toBe('');
+ const stateDb = new Database(targetDbPath, { readonly: true });
+ const state = stateDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ stateDb.close();
+ expect(state.rolloutPath).toBe(prepared);
+ });
+
+ it('lets an external writer win before handoff and adopts it privately on retry', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, '');
+ markEmptyRolloutStable(externalRollout);
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, externalRollout, { updatedAt: 3_000 });
+ const sessionId = `local-external-late-writer-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'external-late-c1',
+ 'user',
+ JSON.stringify({ text: 'Cindy visible history' }),
+ 1_000,
+ );
+ const externalAuthoritative = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/project' },
+ })}\n`;
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let filled = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (!filled && target.toString().startsWith(desktopHome())) {
+ filled = true;
+ fs.writeFileSync(externalRollout, externalAuthoritative);
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /rollout pointer changed during recovery/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(filled).toBe(true);
+ expect(fs.readFileSync(externalRollout, 'utf-8')).toBe(externalAuthoritative);
+ let targetDb = new Database(targetDbPath, { readonly: true });
+ let targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(externalRollout);
+
+ const prepared = await prepareExternalCodexSessionForResume(threadId);
+ expect(prepared).toBeTruthy();
+ expect(prepared).not.toBe(externalRollout);
+ expect(prepared!.startsWith(desktopHome())).toBe(true);
+ expect(fs.readFileSync(prepared!, 'utf-8')).toBe(externalAuthoritative);
+ targetDb = new Database(targetDbPath, { readonly: true });
+ targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(prepared);
+ });
+
+ it('keeps an external empty pointer when no private recovery can be published', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, '');
+ markEmptyRolloutStable(externalRollout);
+ const externalDbPath = createStateDb(externalHome);
+ insertThread(externalDbPath, threadId, externalRollout, { updatedAt: 2_000 });
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, externalRollout, { updatedAt: 3_000 });
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /not safe to resume yet/,
+ );
+
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(externalRollout);
+ expect(fs.readFileSync(externalRollout, 'utf-8')).toBe('');
+ expect(fs.existsSync(path.join(desktopHome(), 'sessions'))).toBe(false);
+ });
+
+ it('waits for a recent empty rollout instead of forking a live writer', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const materializingRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(materializingRollout), { recursive: true });
+ fs.writeFileSync(materializingRollout, '');
+ insertThread(dbPath, threadId, materializingRollout, { updatedAt: 2_000 });
+ const sessionId = `local-materializing-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'live-c1', 'user', JSON.stringify({ text: 'queued' }), 1_000);
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /may still be materializing/,
+ );
+ expect(fs.readdirSync(path.dirname(materializingRollout))).toEqual([
+ path.basename(materializingRollout),
+ ]);
+
+ const authoritative = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/tmp/project' },
+ })}\n`;
+ fs.writeFileSync(materializingRollout, authoritative);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(materializingRollout);
+ const stateDb = new Database(dbPath, { readonly: true });
+ const state = stateDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ stateDb.close();
+ expect(state.rolloutPath).toBe(materializingRollout);
+ });
+
+ it('blocks a recent external rollout before target state has been imported', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, '');
+ const externalDbPath = createStateDb(externalHome);
+ insertThread(externalDbPath, threadId, externalRollout, { updatedAt: 2_000 });
+ const targetDbPath = createStateDb(desktopHome());
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /external rollout may still be materializing/,
+ );
+
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetCount = targetDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ targetDb.close();
+ expect(targetCount.count).toBe(0);
+ expect(fs.existsSync(path.join(desktopHome(), 'sessions'))).toBe(false);
+ });
+
+ it('recovers a stable external empty rollout before target state has been imported', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, '');
+ markEmptyRolloutStable(externalRollout);
+ const externalDbPath = createStateDb(externalHome);
+ insertThread(externalDbPath, threadId, externalRollout, {
+ updatedAt: 2_000,
+ title: 'External stable empty',
+ });
+ const targetDbPath = createStateDb(desktopHome());
+ const sessionId = `local-external-empty-no-target-state-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'external-no-state-c1',
+ 'user',
+ JSON.stringify({ text: 'recover from Cindy history' }),
+ 1_000,
+ );
+
+ const prepared = await prepareExternalCodexSessionForResume(threadId);
+
+ expect(prepared).toBeTruthy();
+ expect(prepared).not.toBe(externalRollout);
+ expect(prepared!.startsWith(desktopHome())).toBe(true);
+ expect(fs.readFileSync(externalRollout, 'utf-8')).toBe('');
+ expect(fs.readFileSync(prepared!, 'utf-8')).toContain('recover from Cindy history');
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath, title FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string; title: string };
+ targetDb.close();
+ expect(targetRow).toEqual({ rolloutPath: prepared, title: 'External stable empty' });
+ });
+
+ it('retains a committed no-row handoff when its path temporarily disappears afterward', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, '');
+ markEmptyRolloutStable(externalRollout);
+ const externalDbPath = createStateDb(externalHome);
+ insertThread(externalDbPath, threadId, externalRollout, { updatedAt: 2_000 });
+ const targetDbPath = createStateDb(desktopHome());
+ const sessionId = `local-no-row-post-commit-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'no-row-post-commit-c1',
+ 'user',
+ JSON.stringify({ text: 'retain the committed no-row state' }),
+ 1_000,
+ );
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ const realLstat = fs.lstatSync.bind(fs);
+ let candidate: string | null = null;
+ let backup: string | null = null;
+ let disappearedAfterCommit = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (path.basename(target.toString()).startsWith('rollout-cindy-empty-recovery')) {
+ candidate = path.resolve(target.toString());
+ }
+ });
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((file: fs.PathLike) => {
+ if (
+ candidate
+ && !disappearedAfterCommit
+ && path.resolve(file.toString()) === candidate
+ && fs.existsSync(candidate)
+ ) {
+ try {
+ const probe = new Database(targetDbPath, { readonly: true });
+ const row = probe
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath?: string } | undefined;
+ probe.close();
+ if (row?.rolloutPath === candidate) {
+ backup = `${candidate}.committed-inode`;
+ fs.renameSync(candidate, backup);
+ disappearedAfterCommit = true;
+ }
+ } catch {
+ // The IMMEDIATE copy transaction is still uncommitted; retry later.
+ }
+ }
+ return realLstat(file);
+ }) as typeof fs.lstatSync);
+
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /external state could not be copied after recovery/,
+ );
+ } finally {
+ lstatSpy.mockRestore();
+ linkSpy.mockRestore();
+ }
+
+ expect(disappearedAfterCommit).toBe(true);
+ expect(candidate).toBeTruthy();
+ expect(backup).toBeTruthy();
+ let targetDb = new Database(targetDbPath, { readonly: true });
+ let targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(candidate);
+
+ fs.renameSync(backup!, candidate!);
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(candidate);
+ targetDb = new Database(targetDbPath, { readonly: true });
+ targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(candidate);
+ expect(fs.readFileSync(candidate!, 'utf-8')).toContain('retain the committed no-row state');
+ });
+
+ it('blocks when a state-less external empty fills before handoff, then adopts it on retry', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, '');
+ markEmptyRolloutStable(externalRollout);
+ const externalDbPath = createStateDb(externalHome);
+ insertThread(externalDbPath, threadId, externalRollout, { updatedAt: 2_000 });
+ const targetDbPath = createStateDb(desktopHome());
+ const sessionId = `local-external-handoff-race-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'handoff-c1', 'user', JSON.stringify({ text: 'fallback H1' }), 1_000);
+ const authoritative = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/project' },
+ })}\n`;
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let filled = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (!filled && path.basename(target.toString()).startsWith('rollout-cindy-empty-recovery')) {
+ filled = true;
+ fs.writeFileSync(externalRollout, authoritative);
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /changed before private state handoff/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ const emptyTargetDb = new Database(targetDbPath, { readonly: true });
+ const targetCount = emptyTargetDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ emptyTargetDb.close();
+ expect(targetCount.count).toBe(0);
+
+ const adopted = await prepareExternalCodexSessionForResume(threadId);
+ expect(fs.readFileSync(adopted!, 'utf-8')).toBe(authoritative);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(adopted);
+ });
+
+ it('blocks a recent unindexed external empty, then recovers privately once stable', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, '');
+ const targetDbPath = createStateDb(desktopHome());
+ const sessionId = `local-unindexed-external-empty-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'unindexed-external-c1',
+ 'user',
+ JSON.stringify({ text: 'recover from Cindy history' }),
+ 1_000,
+ );
+
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /external rollout may still be materializing/,
+ );
+ markEmptyRolloutStable(externalRollout);
+
+ const prepared = await prepareExternalCodexSessionForResume(threadId);
+
+ expect(fs.readFileSync(externalRollout, 'utf-8')).toBe('');
+ expect(prepared).toBeTruthy();
+ expect(prepared).not.toBe(externalRollout);
+ expect(prepared!.startsWith(desktopHome())).toBe(true);
+ expect(fs.readFileSync(prepared!, 'utf-8')).toContain('recover from Cindy history');
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetCount = targetDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ targetDb.close();
+ expect(targetCount.count).toBe(0);
+ });
+
+ it('blocks when a stable unindexed external empty fills at handoff, then adopts it exactly', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ '2026',
+ '08',
+ '03',
+ `rollout-2026-08-03T11-56-18-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, '');
+ markEmptyRolloutStable(externalRollout);
+ const targetDbPath = createStateDb(desktopHome());
+ const sessionId = `local-unindexed-external-race-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'unindexed-race-c1',
+ 'user',
+ JSON.stringify({ text: 'local fallback must not win this race' }),
+ 1_000,
+ );
+ const authoritative = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/authoritative' },
+ })}\n${rolloutLine(
+ 'external-race-m1',
+ 'user',
+ 'full fidelity external history',
+ '2026-08-03T11:56:19.000Z',
+ )}\n`;
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ let filled = false;
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (!filled && path.basename(target.toString()).startsWith('.cindy-state-less-recovery')) {
+ filled = true;
+ fs.writeFileSync(externalRollout, authoritative);
+ }
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /external rollout changed before private recovery handoff/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ const canonical = path.join(
+ desktopHome(),
+ path.relative(externalHome, externalRollout),
+ );
+ expect(fs.existsSync(canonical)).toBe(false);
+ const adopted = await prepareExternalCodexSessionForResume(threadId);
+ expect(adopted).toBe(canonical);
+ expect(fs.readFileSync(adopted!, 'utf-8')).toBe(authoritative);
+ expect(fs.readFileSync(externalRollout, 'utf-8')).toBe(authoritative);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetCount = targetDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ targetDb.close();
+ expect(targetCount.count).toBe(0);
+ });
+
+ it('prefers an authoritative writer that fills the original during recovery publication', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const emptyRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(emptyRollout), { recursive: true });
+ fs.writeFileSync(emptyRollout, '');
+ markEmptyRolloutStable(emptyRollout);
+ insertThread(dbPath, threadId, emptyRollout, { updatedAt: 2_000 });
+ const sessionId = `local-late-writer-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'late-c1', 'user', JSON.stringify({ text: 'local copy' }), 1_000);
+ const authoritative = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/tmp/project' },
+ })}\n`;
+
+ const realLink = fs.promises.link.bind(fs.promises);
+ const linkSpy = vi.spyOn(fs.promises, 'link').mockImplementation(async (source, target) => {
+ await realLink(source, target);
+ if (path.basename(target.toString()).startsWith('rollout-cindy-empty-recovery')) {
+ fs.writeFileSync(emptyRollout, authoritative);
+ }
+ });
+ try {
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(emptyRollout);
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ const stateDb = new Database(dbPath, { readonly: true });
+ const state = stateDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ stateDb.close();
+ expect(state.rolloutPath).toBe(emptyRollout);
+ expect(fs.readFileSync(emptyRollout, 'utf-8')).toBe(authoritative);
+ });
+
+ it('keeps the published recovery authoritative when the original writes on a later preflight', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const emptyRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(emptyRollout), { recursive: true });
+ fs.writeFileSync(emptyRollout, '');
+ markEmptyRolloutStable(emptyRollout);
+ insertThread(dbPath, threadId, emptyRollout, { updatedAt: 2_000 });
+ const sessionId = `local-reconcile-writer-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'reconcile-c1', 'user', JSON.stringify({ text: 'fallback' }), 1_000);
+
+ const recovered = await prepareExternalCodexSessionForResume(threadId);
+ const authoritative = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/tmp/project' },
+ })}\n`;
+ fs.writeFileSync(emptyRollout, authoritative);
+ const future = new Date(Date.now() + 1_000);
+ fs.utimesSync(emptyRollout, future, future);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(recovered);
+ expect(fs.readFileSync(recovered!, 'utf-8')).toContain('fallback');
+ expect(fs.readFileSync(emptyRollout, 'utf-8')).toBe(authoritative);
+ const stateDb = new Database(dbPath, { readonly: true });
+ const state = stateDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ stateDb.close();
+ expect(state.rolloutPath).toBe(recovered);
+ });
+
+ it('does not reuse a published recovery after local history advances', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const emptyRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(emptyRollout), { recursive: true });
+ fs.writeFileSync(emptyRollout, '');
+ markEmptyRolloutStable(emptyRollout);
+ insertThread(dbPath, threadId, emptyRollout, { updatedAt: 2_000 });
+ const sessionId = `local-second-recovery-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'second-c1', 'user', JSON.stringify({ text: 'history H1' }), 1_000);
+
+ const firstRecovery = await prepareExternalCodexSessionForResume(threadId);
+ const firstContents = fs.readFileSync(firstRecovery!, 'utf-8');
+ const writableDb = new Database(dbPath);
+ writableDb
+ .prepare('UPDATE threads SET rollout_path = ? WHERE id = ?')
+ .run(emptyRollout, threadId);
+ writableDb.close();
+ insertLocalMessage(sessionId, 'second-c2', 'assistant', 'history H2', 1_100);
+
+ const prepared = await prepareExternalCodexSessionForResume(threadId);
+
+ expect(path.basename(prepared!)).toBe(
+ `rollout-cindy-empty-recovery-2-${path.basename(emptyRollout)}`,
+ );
+ expect(fs.readFileSync(emptyRollout, 'utf-8')).toBe('');
+ expect(fs.readFileSync(firstRecovery!, 'utf-8')).toBe(firstContents);
+ expect(fs.readFileSync(prepared!, 'utf-8')).toContain('history H2');
+ });
+
+ it('keeps a pointed recovery authoritative when local history advances after handoff', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const emptyRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(emptyRollout), { recursive: true });
+ fs.writeFileSync(emptyRollout, '');
+ markEmptyRolloutStable(emptyRollout);
+ insertThread(dbPath, threadId, emptyRollout, { updatedAt: 2_000 });
+ const sessionId = `local-pointed-refresh-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'pointed-c1', 'user', JSON.stringify({ text: 'pointed H1' }), 1_000);
+
+ const firstRecovery = await prepareExternalCodexSessionForResume(threadId);
+ insertLocalMessage(sessionId, 'pointed-c2', 'assistant', 'pointed H2', 1_100);
+ const prepared = await prepareExternalCodexSessionForResume(threadId);
+
+ expect(prepared).toBe(firstRecovery);
+ expect(fs.readFileSync(firstRecovery!, 'utf-8')).not.toContain('pointed H2');
+ expect(fs.readdirSync(path.dirname(firstRecovery!)).filter((name) => (
+ name.startsWith('rollout-cindy-empty-recovery')
+ ))).toEqual([path.basename(firstRecovery!)]);
+ const stateDb = new Database(dbPath, { readonly: true });
+ const state = stateDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ stateDb.close();
+ expect(state.rolloutPath).toBe(firstRecovery);
+ });
+
+ it('preserves a recovery after Codex has appended native records', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const emptyRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(emptyRollout), { recursive: true });
+ fs.writeFileSync(emptyRollout, '');
+ markEmptyRolloutStable(emptyRollout);
+ insertThread(dbPath, threadId, emptyRollout, { updatedAt: 2_000 });
+ const sessionId = `local-native-append-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'native-c1', 'user', JSON.stringify({ text: 'native H1' }), 1_000);
+
+ const recovered = await prepareExternalCodexSessionForResume(threadId);
+ const nativeLine = `${JSON.stringify({
+ timestamp: '2026-08-03T12:00:00.000Z',
+ type: 'turn_context',
+ payload: { turn_id: 'native-turn' },
+ })}\n`;
+ fs.appendFileSync(recovered!, nativeLine);
+ const authoritativeContents = fs.readFileSync(recovered!, 'utf-8');
+ insertLocalMessage(sessionId, 'native-c2', 'assistant', 'local H2', 1_100);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(recovered);
+ expect(fs.readFileSync(recovered!, 'utf-8')).toBe(authoritativeContents);
+ expect(fs.readdirSync(path.dirname(recovered!)).filter((name) => (
+ name.startsWith('rollout-cindy-empty-recovery')
+ ))).toEqual([path.basename(recovered!)]);
+ });
+
+ it('keeps a native-appended recovery authoritative when the original writes later', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const emptyRollout = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(emptyRollout), { recursive: true });
+ fs.writeFileSync(emptyRollout, '');
+ markEmptyRolloutStable(emptyRollout);
+ insertThread(dbPath, threadId, emptyRollout, { updatedAt: 2_000 });
+ const sessionId = `local-native-late-original-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'native-late-c1', 'user', JSON.stringify({ text: 'fallback H1' }), 1_000);
+
+ const recovered = await prepareExternalCodexSessionForResume(threadId);
+ const nativeLine = `${JSON.stringify({
+ timestamp: '2026-08-03T12:00:00.000Z',
+ type: 'turn_context',
+ payload: { turn_id: 'native-after-recovery' },
+ })}\n`;
+ fs.appendFileSync(recovered!, nativeLine);
+ const recoveredContents = fs.readFileSync(recovered!, 'utf-8');
+
+ const lateOriginal = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/late/original' },
+ })}\n`;
+ fs.writeFileSync(emptyRollout, lateOriginal);
+ const later = new Date(Date.now() + 1_000);
+ fs.utimesSync(emptyRollout, later, later);
+ expect(fs.statSync(emptyRollout).mtimeMs).toBeGreaterThan(fs.statSync(recovered!).mtimeMs);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(recovered);
+ expect(fs.readFileSync(recovered!, 'utf-8')).toBe(recoveredContents);
+ expect(fs.readFileSync(emptyRollout, 'utf-8')).toBe(lateOriginal);
+ const stateDb = new Database(dbPath, { readonly: true });
+ const state = stateDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ stateDb.close();
+ expect(state.rolloutPath).toBe(recovered);
+ });
+
+ it('adopts a non-legacy external pointer already stored in target state', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, 'EXTERNAL_CURRENT');
+ const externalDbPath = createStateDb(externalHome);
+ insertThread(externalDbPath, threadId, externalRollout, { updatedAt: 2_000 });
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, externalRollout, {
+ updatedAt: 3_000,
+ title: 'Keep target metadata',
+ });
+
+ const prepared = await prepareExternalCodexSessionForResume(threadId);
+
+ expect(prepared).toBeTruthy();
+ expect(prepared).not.toBe(externalRollout);
+ expect(prepared!.startsWith(desktopHome())).toBe(true);
+ expect(fs.readFileSync(prepared!, 'utf-8')).toBe('EXTERNAL_CURRENT');
+ expect(fs.readFileSync(externalRollout, 'utf-8')).toBe('EXTERNAL_CURRENT');
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath, title FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string; title: string };
+ targetDb.close();
+ expect(targetRow).toEqual({ rolloutPath: prepared, title: 'Keep target metadata' });
+ });
+
+ it('rejects a symlink-shaped external state pointer before copying it', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, 'EXTERNAL_CURRENT');
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, externalRollout, {
+ updatedAt: 3_000,
+ title: 'Keep target metadata',
+ });
+
+ // Model a final symlink without requiring Windows symlink privileges. The
+ // real file keeps statSync-compatible contents, while lstatSync exposes the
+ // no-follow shape that resume preparation must reject.
+ const realLstat = fs.lstatSync.bind(fs);
+ const copySpy = vi.spyOn(fs.promises, 'copyFile');
+ let copyCalls = 0;
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation(((candidate: fs.PathLike) => {
+ const observed = realLstat(candidate);
+ if (path.resolve(candidate.toString()) !== path.resolve(externalRollout)) return observed;
+ return new Proxy(observed, {
+ get(target, property, receiver) {
+ if (property === 'isFile') return () => false;
+ if (property === 'isSymbolicLink') return () => true;
+ return Reflect.get(target, property, receiver);
+ },
+ });
+ }) as typeof fs.lstatSync);
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /rollout path is not a stable regular file/,
+ );
+ } finally {
+ copyCalls = copySpy.mock.calls.length;
+ lstatSpy.mockRestore();
+ copySpy.mockRestore();
+ }
+
+ expect(copyCalls).toBe(0);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath, title FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string; title: string };
+ targetDb.close();
+ expect(targetRow).toEqual({
+ rolloutPath: externalRollout,
+ title: 'Keep target metadata',
+ });
+ const privateSessions = path.join(desktopHome(), 'sessions');
+ expect(fs.existsSync(privateSessions) ? fs.readdirSync(privateSessions) : []).toEqual([]);
+ });
+
+ it('fails closed when private adoption hits a filesystem error', async () => {
+ const externalRollout = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-2026-08-03-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(externalRollout), { recursive: true });
+ fs.writeFileSync(externalRollout, 'EXTERNAL_CURRENT');
+ const targetDbPath = createStateDb(desktopHome());
+ insertThread(targetDbPath, threadId, externalRollout, { updatedAt: 3_000 });
+ const copyError = Object.assign(new Error('disk full'), { code: 'ENOSPC' });
+ const copySpy = vi.spyOn(fs.promises, 'copyFile').mockRejectedValue(copyError);
+
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /external rollout adoption failed/,
+ );
+ } finally {
+ copySpy.mockRestore();
+ }
+
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(externalRollout);
+ expect(fs.readFileSync(externalRollout, 'utf-8')).toBe('EXTERNAL_CURRENT');
+ });
+
+ it('preserves a stable empty and publishes one discoverable canonical when state is missing', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const sessionId = `local-missing-state-empty-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(sessionId, 'missing-empty-c1', 'user', JSON.stringify({ text: 'recover' }), 1_000);
+ const canonical = path.join(
+ desktopHome(),
+ 'sessions',
+ '1970',
+ '01',
+ '01',
+ `rollout-1970-01-01T00-00-01-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(canonical), { recursive: true });
+ fs.writeFileSync(canonical, '');
+ markEmptyRolloutStable(canonical);
+
+ expect(await prepareExternalCodexSessionForResume(threadId)).toBe(canonical);
+ expect(fs.readFileSync(canonical, 'utf-8')).toContain('recover');
+ const names = fs.readdirSync(path.dirname(canonical));
+ expect(names.filter((name) => /^rollout-\d/.test(name))).toEqual([path.basename(canonical)]);
+ const preservedEmpty = names.find((name) => name.startsWith('rollout-cindy-preserved-empty'));
+ expect(preservedEmpty).toBeTruthy();
+ expect(fs.readFileSync(path.join(path.dirname(canonical), preservedEmpty!), 'utf-8')).toBe('');
+ const stateDb = new Database(dbPath, { readonly: true });
+ const stateCount = stateDb
+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?')
+ .get(threadId) as { count: number };
+ stateDb.close();
+ expect(stateCount.count).toBe(0);
+ });
+
+ it('does not overwrite an existing rollout file (happy path short-circuit)', async () => {
+ const dbPath = createStateDb(desktopHome());
+ const rolloutPath = path.join(
+ desktopHome(),
+ 'sessions',
+ `rollout-2026-06-15-${threadId}.jsonl`,
+ );
+ fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });
+ fs.writeFileSync(rolloutPath, 'ORIGINAL_CONTENT');
+ insertThread(dbPath, threadId, rolloutPath, { updatedAt: 2_000 });
+
+ const sessionId = `local-orphan-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'c1',
+ 'user',
JSON.stringify({ text: 'hi', images: [], files: [] }),
1000,
);
@@ -1676,6 +6035,61 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>
expect(fs.readFileSync(rolloutPath, 'utf-8')).toBe('ORIGINAL_CONTENT');
});
+ it('does not return a late external state row after a failed state-less synthesis', async () => {
+ const targetDbPath = createStateDb(desktopHome());
+ const sessionId = `local-late-external-state-${threadId}`;
+ insertLocalCodexSession(sessionId, threadId);
+ insertLocalMessage(
+ sessionId,
+ 'late-external-state-c1',
+ 'user',
+ JSON.stringify({ text: 'attempt state-less recovery first' }),
+ 1_000,
+ );
+ const lateExternal = path.join(
+ externalHome,
+ 'sessions',
+ `rollout-late-${threadId}.jsonl`,
+ );
+ const lateContents = `${JSON.stringify({
+ type: 'session_meta',
+ payload: { id: threadId, cwd: '/external/late-state' },
+ })}\n`;
+
+ const realLinkSync = fs.linkSync.bind(fs);
+ let stateInserted = false;
+ const linkSpy = vi.spyOn(fs, 'linkSync').mockImplementation((source, target) => {
+ if (
+ !stateInserted
+ && path.basename(source.toString()).startsWith('.cindy-state-less-recovery')
+ && path.basename(target.toString()).startsWith('rollout-')
+ ) {
+ fs.mkdirSync(path.dirname(lateExternal), { recursive: true });
+ fs.writeFileSync(lateExternal, lateContents);
+ insertThread(targetDbPath, threadId, lateExternal, { updatedAt: 3_000 });
+ stateInserted = true;
+ throw Object.assign(new Error('synthetic publication interrupted'), { code: 'EIO' });
+ }
+ return realLinkSync(source, target);
+ });
+ try {
+ await expect(prepareExternalCodexSessionForResume(threadId)).rejects.toThrow(
+ /late Codex state appeared outside a readable private recovery boundary/,
+ );
+ } finally {
+ linkSpy.mockRestore();
+ }
+
+ expect(stateInserted).toBe(true);
+ expect(fs.readFileSync(lateExternal, 'utf-8')).toBe(lateContents);
+ const targetDb = new Database(targetDbPath, { readonly: true });
+ const targetRow = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')
+ .get(threadId) as { rolloutPath: string };
+ targetDb.close();
+ expect(targetRow.rolloutPath).toBe(lateExternal);
+ });
+
it('does not synthesize when there is no readable localDb history', async () => {
const dbPath = createStateDb(desktopHome());
const missingRollout = path.join(
diff --git a/apps/desktop/src/main/__tests__/fork.test.ts b/apps/desktop/src/main/__tests__/fork.test.ts
index 397cb2f08a..b0b7d9c4ab 100644
--- a/apps/desktop/src/main/__tests__/fork.test.ts
+++ b/apps/desktop/src/main/__tests__/fork.test.ts
@@ -16,6 +16,8 @@ import os from 'node:os';
import path from 'node:path';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { CodexResumePreparationBlockedError } from '@cindy/maker-core';
+import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-input-projection';
const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
@@ -353,6 +355,27 @@ describe('forkSessionAtMessage', () => {
expect(txCalls).toHaveLength(0);
});
+ it('codex path: projects a blocked resume preparation without exposing diagnostics', async () => {
+ const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });
+ selectQueue.push([makeSourceRow({
+ agentKind: 'codex',
+ sdkSessionId: 'imported-codex-thread',
+ })]);
+ selectQueue.push([target]);
+ queryMock.mockResolvedValue([{ role: 'user', content: '"target"' }]);
+ forkSdkSessionMock.mockRejectedValueOnce(
+ new CodexResumePreparationBlockedError('live writer at /private/codex/rollout.jsonl'),
+ );
+
+ await expect(
+ forkSessionAtMessage('src-session', 'target-user'),
+ ).rejects.toMatchObject({
+ code: 'CODEX_FORK_STATE_UNAVAILABLE',
+ message: CODEX_RESUME_NOT_READY_WIRE_MESSAGE,
+ });
+ expect(txCalls).toHaveLength(0);
+ });
+
it('strip encrypted fork: codex-only path forks with strip flag and copies all messages', async () => {
const source = makeSourceRow({
agentKind: 'codex',
diff --git a/apps/desktop/src/main/maker-host/codex-local-sessions.ts b/apps/desktop/src/main/maker-host/codex-local-sessions.ts
index ffd0766645..6a9cca71f9 100644
--- a/apps/desktop/src/main/maker-host/codex-local-sessions.ts
+++ b/apps/desktop/src/main/maker-host/codex-local-sessions.ts
@@ -22,7 +22,10 @@ import {
} from '@cindy/maker-shared/brand-identity';
import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
-import { finalizeCodexCitationText } from '@cindy/maker-core';
+import {
+ CodexResumePreparationBlockedError,
+ finalizeCodexCitationText,
+} from '@cindy/maker-core';
import { getCurrentDbClientUserId, getDbClient } from '../localDb/client/current.js';
import { createBetterSqliteDatabase } from '../localDb/betterSqliteFactory.js';
@@ -42,8 +45,253 @@ const log = createLogger('codex-local-sessions');
const LOCAL_SESSION_ID_PREFIX = 'codex-';
const MAX_THREADS_PER_HOME = 1000;
const SQLITE_BUSY_TIMEOUT_MS = 3000;
+// Codex can create a rollout before writing session_meta and keep that file at
+// zero bytes for several minutes. Recovery must not fork a still-live writer.
+const EMPTY_ROLLOUT_RECOVERY_GRACE_MS = 15 * 60_000;
+const MAX_RECOVERY_PATH_ATTEMPTS = 8;
const codexMessageImportFileCache = new Map<string, ExternalImportFileCacheEntry>();
+function isNonEmptyRolloutFile(filePath: string, threadId: string): boolean {
+ const state = readRegularRolloutPathState(filePath);
+ if (state === 'unsafe') {
+ throw resumePreparationBlocked(threadId, 'the rollout path is not a stable regular file');
+ }
+ return state === 'non-empty-file';
+}
+
+interface EmptyRolloutSnapshot {
+ dev: number;
+ ino: number;
+ mtimeMs: number;
+ ctimeMs: number;
+ birthtimeMs: number | null;
+}
+
+interface NonEmptyRolloutSnapshot extends EmptyRolloutSnapshot {
+ size: number;
+}
+
+/** Capture an unchanged zero-byte file so recovery can fail closed around live writers. */
+function readEmptyRolloutSnapshot(filePath: string): EmptyRolloutSnapshot | null {
+ try {
+ const before = fs.lstatSync(filePath);
+ if (!before.isFile() || before.size !== 0) return null;
+ const stat = fs.lstatSync(filePath);
+ if (
+ !stat.isFile()
+ || stat.size !== 0
+ || before.dev !== stat.dev
+ || before.ino !== stat.ino
+ ) return null;
+ return {
+ dev: stat.dev,
+ ino: stat.ino,
+ mtimeMs: stat.mtimeMs,
+ ctimeMs: stat.ctimeMs,
+ birthtimeMs: usableBirthtimeMs(stat),
+ };
+ } catch {
+ return null;
+ }
+}
+
+function isStableEmptyRollout(snapshot: EmptyRolloutSnapshot): boolean {
+ const latestIdentityTime = Math.max(
+ snapshot.mtimeMs,
+ snapshot.ctimeMs,
+ snapshot.birthtimeMs ?? 0,
+ );
+ return Date.now() - latestIdentityTime >= EMPTY_ROLLOUT_RECOVERY_GRACE_MS;
+}
+
+function usableBirthtimeMs(stat: fs.Stats): number | null {
+ return Number.isFinite(stat.birthtimeMs) && stat.birthtimeMs > 0 ? stat.birthtimeMs : null;
+}
+
+function emptyRolloutStillMatches(
+ filePath: string,
+ expected: EmptyRolloutSnapshot,
+): boolean {
+ const current = readEmptyRolloutSnapshot(filePath);
+ return !!current
+ && current.dev === expected.dev
+ && current.ino === expected.ino
+ && current.mtimeMs === expected.mtimeMs
+ && current.ctimeMs === expected.ctimeMs
+ && current.birthtimeMs === expected.birthtimeMs;
+}
+
+/** Capture an external empty without following a symlink or accepting a replace race. */
+function readRegularEmptyRolloutSnapshot(filePath: string): EmptyRolloutSnapshot | null {
+ try {
+ const before = fs.lstatSync(filePath);
+ if (!before.isFile() || before.size !== 0) return null;
+ const after = fs.lstatSync(filePath);
+ if (
+ !after.isFile()
+ || after.size !== 0
+ || before.dev !== after.dev
+ || before.ino !== after.ino
+ ) return null;
+ return {
+ dev: after.dev,
+ ino: after.ino,
+ mtimeMs: after.mtimeMs,
+ ctimeMs: after.ctimeMs,
+ birthtimeMs: usableBirthtimeMs(after),
+ };
+ } catch {
+ return null;
+ }
+}
+
+function regularEmptyRolloutStillMatches(
+ filePath: string,
+ expected: EmptyRolloutSnapshot,
+): boolean {
+ const current = readRegularEmptyRolloutSnapshot(filePath);
+ return !!current
+ && current.dev === expected.dev
+ && current.ino === expected.ino
+ && current.mtimeMs === expected.mtimeMs
+ && current.ctimeMs === expected.ctimeMs
+ && current.birthtimeMs === expected.birthtimeMs;
+}
+
+function readNonEmptyRolloutSnapshot(filePath: string): NonEmptyRolloutSnapshot | null {
+ try {
+ const before = fs.lstatSync(filePath);
+ if (!before.isFile() || before.size <= 0) return null;
+ const stat = fs.lstatSync(filePath);
+ if (
+ !stat.isFile()
+ || stat.size <= 0
+ || before.dev !== stat.dev
+ || before.ino !== stat.ino
+ ) return null;
+ return {
+ dev: stat.dev,
+ ino: stat.ino,
+ size: stat.size,
+ mtimeMs: stat.mtimeMs,
+ ctimeMs: stat.ctimeMs,
+ birthtimeMs: usableBirthtimeMs(stat),
+ };
+ } catch {
+ return null;
+ }
+}
+
+function nonEmptyRolloutStillMatches(
+ filePath: string,
+ expected: NonEmptyRolloutSnapshot,
+): boolean {
+ const current = readNonEmptyRolloutSnapshot(filePath);
+ return !!current
+ && current.dev === expected.dev
+ && current.ino === expected.ino
+ && current.size === expected.size
+ && current.mtimeMs === expected.mtimeMs
+ && current.ctimeMs === expected.ctimeMs
+ && current.birthtimeMs === expected.birthtimeMs;
+}
+
+/** Bounded-memory equality check used only for Cindy-owned immutable candidates. */
+function filesHaveSameContents(leftPath: string, rightPath: string): 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;
+ 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);
+ if (leftRead !== rightRead) return false;
+ if (leftRead === 0) return true;
+ if (!left.subarray(0, leftRead).equals(right.subarray(0, rightRead))) return false;
+ }
+ } catch {
+ return false;
+ } finally {
+ if (leftFd !== null) {
+ try { fs.closeSync(leftFd); } catch { /* best effort */ }
+ }
+ if (rightFd !== null) {
+ try { fs.closeSync(rightFd); } catch { /* best effort */ }
+ }
+ }
+}
+
+/**
+ * Read an exact Cindy-owned rollout through a no-follow file descriptor and
+ * bind the bytes to one regular-file identity before it is persisted in state.
+ */
+function readPrivateExactRolloutSnapshot(
+ targetHome: string,
+ filePath: string,
+ contents: string,
+): NonEmptyRolloutSnapshot | null {
+ const expected = Buffer.from(contents, 'utf-8');
+ if (expected.length === 0 || !isPathInside(targetHome, filePath)) return null;
+
+ let fd: number | null = null;
+ try {
+ const before = fs.lstatSync(filePath);
+ if (!before.isFile() || before.size !== expected.length) return null;
+
+ const noFollow = typeof fs.constants.O_NOFOLLOW === 'number'
+ ? fs.constants.O_NOFOLLOW
+ : 0;
+ fd = fs.openSync(filePath, fs.constants.O_RDONLY | noFollow);
+ const opened = fs.fstatSync(fd);
+ if (
+ !opened.isFile()
+ || opened.size !== expected.length
+ || opened.dev !== before.dev
+ || opened.ino !== before.ino
+ ) return null;
+
+ const chunk = Buffer.allocUnsafe(64 * 1024);
+ let offset = 0;
+ while (offset < expected.length) {
+ const read = fs.readSync(fd, chunk, 0, Math.min(chunk.length, expected.length - offset), null);
+ if (read <= 0 || !chunk.subarray(0, read).equals(expected.subarray(offset, offset + read))) {
+ return null;
+ }
+ offset += read;
+ }
+ if (fs.readSync(fd, chunk, 0, 1, null) !== 0) return null;
+
+ const after = fs.lstatSync(filePath);
+ if (
+ !after.isFile()
+ || after.dev !== opened.dev
+ || after.ino !== opened.ino
+ || after.size !== opened.size
+ || !isPathInside(targetHome, filePath)
+ ) return null;
+ return {
+ dev: after.dev,
+ ino: after.ino,
+ size: after.size,
+ mtimeMs: after.mtimeMs,
+ ctimeMs: after.ctimeMs,
+ birthtimeMs: usableBirthtimeMs(after),
+ };
+ } catch {
+ return null;
+ } finally {
+ if (fd !== null) {
+ try { fs.closeSync(fd); } catch { /* best effort */ }
+ }
+ }
+}
+
type SqlScalar = string | number | bigint | Buffer | null;
type SqlRow = Record<string, SqlScalar | undefined>;
@@ -178,78 +426,693 @@ export async function prepareExternalCodexSessionForResume(threadId: string): Pr
}
let targetRollout = readThreadRolloutPath(targetDbPath, threadId);
- // rollout 文件真实存在 → resume 能直接读,无需任何处理(最热路径,优先短路)。
- // 注意: 这里必须校验文件**真的在磁盘上**, 不能只看 DB 里有没有 rollout_path ——
- // DB threads 行可能指向一个已被删除的 rollout 文件(孤儿), 那种情况要继续往下走恢复。
- if (
- targetRollout
- && fs.existsSync(targetRollout)
- && (
- isPathInside(targetHome, targetRollout)
- || !isLegacyBrandedCodexLocation(targetHome, targetRollout)
- )
- ) return targetRollout;
+ if (targetRollout) {
+ const recordedTargetRollout = targetRollout;
+ const targetIsPrivate = isPathInside(targetHome, targetRollout);
- // state 行可能已经丢失,但标准 sessions/ 下的 rollout 仍在。app-server 的
- // thread/resume 会自己扫描并重新 hydrate state;这里只需避免再合成一份重复文件。
- if (!targetRollout) {
- const currentHomeThread = findExternalThreadByIdFromRollouts(targetHome, threadId);
- if (currentHomeThread?.rolloutPath && fs.existsSync(currentHomeThread.rolloutPath)) return;
- }
-
- // 尝试从外部 CODEX_HOME(~/.codex、Codex.app、历史品牌 userData 等)导入这个 thread。
- // rollout 必须接管进当前 Cindy HOME,不能让新 state 长期指向可能被用户清理的老目录。
- // target row 已指向旧品牌 rollout 时,这个指针比外部 HOME 的 updatedAt 更权威。
- // 否则 ~/.codex / CODEX_HOME 中较新的同 id thread 会先胜出,linked 分支又因 target
- // row 已存在而跳过复制,导致旧品牌指针永远没有被接管。
- const legacyTargetThread = targetRollout
- && isLegacyBrandedCodexLocation(targetHome, targetRollout)
- ? findThreadByIdInHome(targetHome, threadId)
- : null;
- const found = legacyTargetThread
- ?? findExternalThreadById(threadId)
- ?? (targetRollout ? findThreadByIdInHome(targetHome, threadId) : null);
- if (found) {
- // 外部会话(~/.codex、Codex.app、历史品牌 HOME)一律**复制成 Cindy 私有副本**,
- // 不再链接源 rollout(#789 方案 A:Dash 定稿)。Cindy 的续聊只写进 desktop CODEX_HOME
- // 的这份副本,源会话零改动、也没有任何回写通道——彻底消除跨 runtime 版本回写污染源会话
- // 的风险。接管进当前 HOME 还避免 state 长期指向可能被用户清理的外部目录。
- const adoptedRolloutPath = targetRolloutPathForExternalThread(found, targetHome);
- const sourceRolloutExists = !!found.rolloutPath && fs.existsSync(found.rolloutPath);
- let adoptedRollout = false;
- if (sourceRolloutExists) {
+ // A state-pointed private rollout is an irreversible handoff boundary. It may
+ // already have native Codex records or a live writer, so later preflights must
+ // never replace it from timestamps or the lossy Cindy chat projection.
+ if (
+ targetIsPrivate
+ && readPrivateRolloutPathState(targetHome, targetRollout) === 'non-empty-file'
+ ) {
+ return targetRollout;
+ }
+
+ // Until state points at a private non-empty file, no recovery boundary has
+ // committed. Reconcile any native canonical/preserved inode first so a
+ // crash after preservation cannot hide that writer on the next retry.
+ const nativeWinner = restoreInterruptedNativeCanonicalWithoutState(
+ targetHome,
+ threadId,
+ { requireAllNativePrecursorsConverged: true },
+ );
+ if (nativeWinner) {
+ const snapshot = readPrivateNonEmptyRolloutSnapshot(targetHome, nativeWinner);
+ if (!snapshot) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'the native private rollout changed before state reconciliation',
+ );
+ }
+ const remainingEmptyGuard = observePendingInterruptedEmptyPreservations(
+ targetHome,
+ threadId,
+ );
+ const assertNativeCanonicalNamespaceUnchanged = () => {
+ assertNoUnexpectedCanonicalRollouts(
+ threadId,
+ targetHome,
+ [nativeWinner],
+ );
+ };
+ const assertNativeHandoffUnchanged = combineHandoffGuards(
+ remainingEmptyGuard,
+ assertNativeCanonicalNamespaceUnchanged,
+ );
+ if (handoffThreadToNativeRollout(
+ targetDbPath,
+ threadId,
+ targetHome,
+ targetRollout,
+ { path: nativeWinner, created: false, snapshot },
+ assertNativeHandoffUnchanged,
+ )) {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ nativeWinner,
+ { beforeReturn: assertNativeCanonicalNamespaceUnchanged },
+ );
+ }
+ const concurrentWinner = readPrivateNonEmptyRollout(
+ targetDbPath,
+ threadId,
+ targetHome,
+ );
+ if (concurrentWinner) {
+ if (!samePath(concurrentWinner, nativeWinner)) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'concurrent state selected a different private winner during native reconciliation',
+ );
+ }
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ concurrentWinner,
+ { beforeReturn: assertNativeCanonicalNamespaceUnchanged },
+ );
+ }
+ throw resumePreparationBlocked(
+ threadId,
+ 'state changed before native rollout reconciliation',
+ );
+ }
+
+ const localCanonicalSet = observeCurrentHomeCanonicalRollouts(targetHome, threadId);
+ // A full canonical found here appeared after the initial native preflight.
+ // Keep state unchanged so the next attempt can reconcile it through the
+ // native-winner CAS instead of letting an external/synthetic handoff hide it.
+ if (localCanonicalSet.nonEmpty.length > 0) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'a private canonical rollout materialized during recovery planning',
+ );
+ }
+ const canonicalEmptiesToPreserve = targetIsPrivate
+ ? localCanonicalSet.empties.filter(
+ (candidate) => !samePath(candidate.path, recordedTargetRollout),
+ )
+ : localCanonicalSet.empties;
+ const retainedCanonicalEmpties = targetIsPrivate
+ ? localCanonicalSet.empties.filter(
+ (candidate) => samePath(candidate.path, recordedTargetRollout),
+ )
+ : [];
+ const assertCanonicalEmptiesUnchanged = preserveAdditionalCanonicalEmptiesBeforeHandoff(
+ threadId,
+ targetHome,
+ canonicalEmptiesToPreserve,
+ );
+ const assertCanonicalNamespaceUnchanged = createCanonicalNamespaceGuard(
+ threadId,
+ targetHome,
+ retainedCanonicalEmpties,
+ );
+ assertCanonicalNamespaceUnchanged();
+ const assertInterruptedEmptiesUnchanged = observePendingInterruptedEmptyPreservations(
+ targetHome,
+ threadId,
+ );
+ const assertExistingStatePrecursorsUnchanged = combineHandoffGuards(
+ assertCanonicalEmptiesUnchanged,
+ assertInterruptedEmptiesUnchanged,
+ assertCanonicalNamespaceUnchanged,
+ );
+
+ // #1554: existence is not readability. Codex can create a zero-byte rollout
+ // several minutes before writing session_meta, so recent empties must fail
+ // closed and stable empties recover without modifying the original file.
+ if (readEmptyRolloutSnapshot(targetRollout)) {
try {
- adoptedRollout = await copyExternalRolloutAtomically(found.rolloutPath, adoptedRolloutPath);
- } catch (err) {
- log.warn('failed to adopt external Codex rollout into current home', {
+ return await recoverStableEmptyRollout(
+ threadId,
+ targetDbPath,
+ targetHome,
+ targetRollout,
+ assertExistingStatePrecursorsUnchanged,
+ assertCanonicalNamespaceUnchanged,
+ );
+ } catch (error) {
+ failClosedResumePreparation(threadId, 'empty rollout recovery', error);
+ }
+ }
+
+ // A non-empty external pointer is never a valid hot path: Codex resumes by
+ // appending directly to state.rollout_path. Publish a stable private copy,
+ // then move the existing row with CAS while preserving all current metadata.
+ if (!targetIsPrivate && isNonEmptyRolloutFile(targetRollout, threadId)) {
+ try {
+ const row = readRawThreadRow(targetDbPath, threadId);
+ const preferred = privateRolloutPathForStateRow(targetHome, targetRollout, row);
+ const adopted = await copyExternalRolloutAtomically(
+ targetRollout,
+ preferred,
+ threadId,
+ {
+ allowSibling: true,
+ // Keep every new filename Cindy-owned until the guarded state
+ // transaction verifies the complete canonical namespace.
+ skipPreferred: true,
+ },
+ );
+ if (!adopted) {
+ throw resumePreparationBlocked(threadId, 'external rollout changed during private adoption');
+ }
+ if (handoffThreadToCopiedRollout(
+ targetDbPath,
+ threadId,
+ targetHome,
+ targetRollout,
+ adopted,
+ assertExistingStatePrecursorsUnchanged,
+ )) {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ adopted.path,
+ { beforeReturn: assertCanonicalNamespaceUnchanged },
+ );
+ }
+ const winner = readPrivateNonEmptyRollout(targetDbPath, threadId, targetHome);
+ if (winner) {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ winner,
+ { beforeReturn: assertCanonicalNamespaceUnchanged },
+ );
+ }
+ throw resumePreparationBlocked(threadId, 'external rollout pointer changed during private adoption');
+ } catch (error) {
+ failClosedResumePreparation(threadId, 'external rollout adoption', error);
+ }
+ }
+
+ // The recorded file is missing. If the pointer is external, first publish a
+ // private synthetic fallback and only then move state; never recreate data in
+ // another runtime's CODEX_HOME. A private orphan keeps the established path.
+ if (!targetIsPrivate) {
+ try {
+ return await recoverMissingExternalRollout(
+ threadId,
+ targetDbPath,
+ targetHome,
+ targetRollout,
+ assertExistingStatePrecursorsUnchanged,
+ assertCanonicalNamespaceUnchanged,
+ );
+ } catch (error) {
+ failClosedResumePreparation(threadId, 'missing external rollout recovery', error);
+ }
+ }
+
+ const expectedMissingPrivateRollout = targetRollout;
+ const external = findExternalThreadById(threadId);
+ if (external && isNonEmptyRolloutFile(external.rolloutPath, threadId)) {
+ try {
+ const adopted = await copyExternalRolloutAtomically(
+ external.rolloutPath,
+ expectedMissingPrivateRollout,
+ threadId,
+ {
+ allowSibling: true,
+ // Linking directly at the state-pointed path is itself a commit.
+ // Always keep the copy hidden until the namespace-aware CAS.
+ skipPreferred: true,
+ },
+ );
+ if (!adopted) {
+ throw resumePreparationBlocked(threadId, 'external fallback changed during private adoption');
+ }
+ if (samePath(adopted.path, expectedMissingPrivateRollout)) {
+ if (privateRolloutPublicationOwnsPath(targetHome, adopted)) {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ adopted.path,
+ { allowedCanonicalPaths: [adopted.path] },
+ );
+ }
+ throw resumePreparationBlocked(threadId, 'private adoption target changed during publication');
+ }
+ const assertMissingPrivateHandoffUnchanged = () => {
+ assertExistingStatePrecursorsUnchanged?.();
+ if (
+ readPrivateRolloutPathState(targetHome, expectedMissingPrivateRollout) !== 'missing'
+ ) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'the missing private rollout materialized before state handoff',
+ );
+ }
+ };
+ if (handoffThreadToCopiedRollout(
+ targetDbPath,
+ threadId,
+ targetHome,
+ expectedMissingPrivateRollout,
+ adopted,
+ assertMissingPrivateHandoffUnchanged,
+ )) {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ adopted.path,
+ { beforeReturn: assertCanonicalNamespaceUnchanged },
+ );
+ }
+ const winner = readPrivateNonEmptyRollout(targetDbPath, threadId, targetHome);
+ if (winner) {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ winner,
+ { beforeReturn: assertCanonicalNamespaceUnchanged },
+ );
+ }
+ throw resumePreparationBlocked(threadId, 'private orphan pointer changed during adoption');
+ } catch (error) {
+ failClosedResumePreparation(threadId, 'external orphan adoption', error);
+ }
+ }
+
+ try {
+ return await recoverMissingPrivateRollout(
+ threadId,
+ targetDbPath,
+ targetHome,
+ targetRollout,
+ assertExistingStatePrecursorsUnchanged,
+ assertCanonicalNamespaceUnchanged,
+ );
+ } catch (error) {
+ failClosedResumePreparation(threadId, 'missing private rollout recovery', error);
+ }
+ }
+
+ // The state row may be gone while a valid private rollout remains. Codex can
+ // scan its own standard directories and hydrate current-schema state, but a
+ // Cindy recovery sibling is not discoverable when an empty canonical rollout
+ // for the same thread still shadows it. In that shape, continue into the
+ // state-backed import paths below or fail closed.
+ const interruptedNativeCanonical = restoreInterruptedNativeCanonicalWithoutState(
+ targetHome,
+ threadId,
+ );
+ if (interruptedNativeCanonical) return interruptedNativeCanonical;
+ const assertInterruptedPreservedEmptiesUnchanged =
+ observePendingInterruptedEmptyPreservations(targetHome, threadId);
+ const currentHomeCanonicalSet = observeCurrentHomeCanonicalRollouts(targetHome, threadId);
+ const recentCurrentHomeCanonicalEmpty = currentHomeCanonicalSet.empties.find(
+ (candidate) => !isStableEmptyRollout(candidate.snapshot),
+ );
+ if (recentCurrentHomeCanonicalEmpty) {
+ throw resumePreparationBlocked(threadId, 'private rollout may still be materializing');
+ }
+ if (currentHomeCanonicalSet.nonEmpty.length > 1) {
+ throw resumePreparationBlocked(threadId, 'multiple private canonical rollouts conflict');
+ }
+ if (currentHomeCanonicalSet.nonEmpty.length === 1) {
+ const existingWinner = currentHomeCanonicalSet.nonEmpty[0];
+ preserveStableCanonicalEmptiesBesideWinner(
+ threadId,
+ targetHome,
+ currentHomeCanonicalSet.empties,
+ );
+ const converged = observeCurrentHomeCanonicalRollouts(targetHome, threadId);
+ if (
+ converged.empties.length > 0
+ || converged.nonEmpty.length !== 1
+ || !samePath(converged.nonEmpty[0], existingWinner)
+ ) {
+ throw resumePreparationBlocked(threadId, 'the private canonical winner changed during handoff');
+ }
+ return existingWinner;
+ }
+ const [currentHomeCanonicalEmptyObservation, ...additionalCanonicalEmpties] =
+ currentHomeCanonicalSet.empties;
+ const assertAdditionalCanonicalEmptiesUnchanged = preserveAdditionalCanonicalEmptiesBeforeHandoff(
+ threadId,
+ targetHome,
+ additionalCanonicalEmpties,
+ );
+ const assertLocalCanonicalPrecursorsUnchanged = combineHandoffGuards(
+ assertInterruptedPreservedEmptiesUnchanged,
+ assertAdditionalCanonicalEmptiesUnchanged,
+ );
+ const currentHomeCanonicalEmpty = currentHomeCanonicalEmptyObservation?.path ?? null;
+ const currentHomeCanonicalEmptySnapshot = currentHomeCanonicalEmptyObservation?.snapshot ?? null;
+ const currentHomeThread = findExternalThreadByIdFromRollouts(targetHome, threadId);
+ if (
+ currentHomeThread?.rolloutPath
+ && isNonEmptyRolloutFile(currentHomeThread.rolloutPath, threadId)
+ && !currentHomeCanonicalEmpty
+ && isCanonicalCodexRolloutPath(currentHomeThread.rolloutPath, threadId)
+ ) {
+ const converged = observeCurrentHomeCanonicalRollouts(targetHome, threadId);
+ if (
+ converged.empties.length === 0
+ && converged.nonEmpty.length === 1
+ && samePath(converged.nonEmpty[0], currentHomeThread.rolloutPath)
+ ) return currentHomeThread.rolloutPath;
+ throw resumePreparationBlocked(
+ threadId,
+ 'the private canonical rollout namespace changed during native discovery',
+ );
+ }
+
+ // With no target row, a discovered external thread can still be adopted. A
+ // sibling is usable only when source state can be copied to point at it;
+ // rollout-only sources must publish at the standard preferred path.
+ const found = findExternalThreadById(threadId);
+ let stateBackedLocalHandoffGuard = assertLocalCanonicalPrecursorsUnchanged;
+ let stateBackedCanonicalNamespaceGuard: (() => void) | undefined;
+ if (
+ found?.sourceDbPath
+ && currentHomeCanonicalEmpty
+ && currentHomeCanonicalEmptySnapshot
+ ) {
+ // A state-backed sibling is not discoverable until its row commits. Move
+ // the primary empty inode aside first, then keep it in the same safety set
+ // as the publication for both transaction validations. A writer waking
+ // after commit remains preserved; one waking before commit wins on the
+ // next retry through interrupted-preservation restoration.
+ const preservation = preserveStableEmptyCanonical(
+ threadId,
+ targetHome,
+ currentHomeCanonicalEmpty,
+ currentHomeCanonicalEmptySnapshot,
+ );
+ if (preservation.kind === 'native-winner') {
+ return acceptSoleCanonicalNativeWinner(
+ threadId,
+ targetHome,
+ currentHomeCanonicalEmpty,
+ stateBackedLocalHandoffGuard,
+ );
+ }
+ const preservedState = readPrivateRolloutPathState(targetHome, preservation.path);
+ if (preservedState === 'non-empty-file') {
+ return restoreSoleCanonicalNativeWinner(
+ threadId,
+ targetHome,
+ preservation.path,
+ currentHomeCanonicalEmpty,
+ stateBackedLocalHandoffGuard,
+ );
+ }
+ const preservedSnapshot = readRegularEmptyRolloutSnapshot(preservation.path);
+ if (!preservedSnapshot) {
+ if (readPrivateRolloutPathState(targetHome, preservation.path) === 'non-empty-file') {
+ return restoreSoleCanonicalNativeWinner(
+ threadId,
+ targetHome,
+ preservation.path,
+ currentHomeCanonicalEmpty,
+ stateBackedLocalHandoffGuard,
+ );
+ }
+ throw resumePreparationBlocked(
+ threadId,
+ 'the primary private rollout changed before state-backed adoption',
+ );
+ }
+ const assertPrimaryCanonicalUnchanged = () => {
+ if (!regularEmptyRolloutStillMatches(preservation.path, preservedSnapshot)) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'the primary private rollout changed before state handoff',
+ );
+ }
+ };
+ stateBackedLocalHandoffGuard = combineHandoffGuards(
+ stateBackedLocalHandoffGuard,
+ assertPrimaryCanonicalUnchanged,
+ );
+ }
+ if (found?.sourceDbPath) {
+ stateBackedCanonicalNamespaceGuard = createCanonicalNamespaceGuard(
+ threadId,
+ targetHome,
+ [],
+ );
+ stateBackedCanonicalNamespaceGuard();
+ stateBackedLocalHandoffGuard = combineHandoffGuards(
+ stateBackedLocalHandoffGuard,
+ stateBackedCanonicalNamespaceGuard,
+ );
+ }
+ if (found && isNonEmptyRolloutFile(found.rolloutPath, threadId)) {
+ try {
+ const preferred = targetRolloutPathForExternalThread(found, targetHome);
+ const stateHandoffGuard = found.sourceDbPath
+ ? stateBackedLocalHandoffGuard
+ : assertLocalCanonicalPrecursorsUnchanged;
+ if (
+ !found.sourceDbPath
+ && currentHomeCanonicalEmpty
+ && currentHomeCanonicalEmptySnapshot
+ ) {
+ return await adoptExternalRolloutOverStableCanonicalWithoutState(
+ threadId,
+ targetHome,
+ found.rolloutPath,
+ currentHomeCanonicalEmpty,
+ currentHomeCanonicalEmptySnapshot,
+ assertLocalCanonicalPrecursorsUnchanged,
+ );
+ }
+ if (
+ !found.sourceDbPath
+ && isCanonicalCodexRolloutPath(preferred, threadId)
+ ) {
+ return await adoptExternalRolloutAfterPendingLocalHandoff(
+ threadId,
+ targetHome,
+ found.rolloutPath,
+ preferred,
+ assertLocalCanonicalPrecursorsUnchanged ?? (() => undefined),
+ );
+ }
+ const adopted = await copyExternalRolloutAtomically(
+ found.rolloutPath,
+ preferred,
+ threadId,
+ {
+ allowSibling: !!found.sourceDbPath,
+ skipPreferred: !!found.sourceDbPath && !!stateHandoffGuard,
+ },
+ );
+ if (!adopted) {
+ throw resumePreparationBlocked(threadId, 'external rollout changed during private adoption');
+ }
+
+ const copiedState = copyThreadStateToTarget(found, targetDbPath, {
+ rolloutPathOverride: adopted.path,
+ validateBeforeCopy: () => {
+ stateHandoffGuard?.();
+ return privateRolloutPublicationStillMatches(targetHome, adopted);
+ },
+ validateAfterCopy: () => {
+ stateHandoffGuard?.();
+ return privateRolloutPublicationStillMatches(targetHome, adopted);
+ },
+ });
+ targetRollout = readThreadRolloutPath(targetDbPath, threadId);
+ if (targetRollout) {
+ if (
+ isPathInside(targetHome, targetRollout)
+ && readPrivateRolloutPathState(targetHome, targetRollout) === 'non-empty-file'
+ ) {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ targetRollout,
+ { beforeReturn: stateBackedCanonicalNamespaceGuard },
+ );
+ }
+ if (!isPathInside(targetHome, targetRollout) && handoffThreadToCopiedRollout(
+ targetDbPath,
+ threadId,
+ targetHome,
+ targetRollout,
+ adopted,
+ stateHandoffGuard,
+ )) {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ adopted.path,
+ { beforeReturn: stateBackedCanonicalNamespaceGuard },
+ );
+ }
+ throw resumePreparationBlocked(threadId, 'concurrent state prevented safe private adoption');
+ }
+ if (
+ samePath(adopted.path, preferred)
+ && isCanonicalCodexRolloutPath(adopted.path, threadId)
+ && privateRolloutPublicationOwnsPath(targetHome, adopted)
+ ) {
+ assertSoleCanonicalPath(threadId, targetHome, adopted.path, true);
+ return adopted.path;
+ }
+ log.warn('external rollout copied to sibling but source state was not available', {
+ threadId,
+ copiedState,
+ adoptedRolloutPath: adopted.path,
+ });
+ throw resumePreparationBlocked(threadId, 'private rollout sibling is not discoverable without state');
+ } catch (error) {
+ failClosedResumePreparation(threadId, 'external rollout import', error);
+ }
+ }
+ const externalEmpty = found ? readEmptyRolloutSnapshot(found.rolloutPath) : null;
+ if (found && externalEmpty) {
+ try {
+ return await recoverStableExternalEmptyWithoutTargetState(
+ threadId,
+ targetDbPath,
+ targetHome,
+ found,
+ externalEmpty,
+ stateBackedLocalHandoffGuard,
+ stateBackedCanonicalNamespaceGuard,
+ );
+ } catch (error) {
+ failClosedResumePreparation(threadId, 'external empty rollout import', error);
+ }
+ }
+ if (found?.sourceDbPath && rolloutPathIsMissing(found.rolloutPath)) {
+ try {
+ const sourceRow = readRawThreadRow(found.sourceDbPath, threadId);
+ if (sourceRow) {
+ const preferred = targetRolloutPathForExternalThread(found, targetHome);
+ const published = await publishFreshSyntheticBeforeHandoff(
+ preferred,
threadId,
- sourceRolloutPath: found.rolloutPath,
- targetRolloutPath: adoptedRolloutPath,
- error: err instanceof Error ? err.message : String(err),
+ sourceRow,
+ { skipPreferred: true },
+ );
+ if (!published) {
+ throw resumePreparationBlocked(threadId, 'a private recovery file could not be published safely');
+ }
+ const assertMissingSourceAndLocalPrecursorsUnchanged = () => {
+ stateBackedLocalHandoffGuard?.();
+ if (!rolloutPathIsMissing(found.rolloutPath)) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'the missing external rollout materialized before state handoff',
+ );
+ }
+ };
+ copyThreadStateToTarget(found, targetDbPath, {
+ rolloutPathOverride: published.path,
+ validateBeforeCopy: () => {
+ assertMissingSourceAndLocalPrecursorsUnchanged();
+ return syntheticPublicationStillMatches(targetHome, published);
+ },
+ validateAfterCopy: () => {
+ assertMissingSourceAndLocalPrecursorsUnchanged();
+ return syntheticPublicationOwnsPath(targetHome, published);
+ },
});
+ const winner = readPrivateNonEmptyRollout(targetDbPath, threadId, targetHome);
+ if (isAcceptableSyntheticWinner(targetHome, winner, published)) {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ winner!,
+ { beforeReturn: stateBackedCanonicalNamespaceGuard },
+ );
+ }
+ throw resumePreparationBlocked(threadId, 'external state could not be copied after recovery');
}
+ } catch (error) {
+ failClosedResumePreparation(threadId, 'missing external thread import', error);
}
+ }
- // 原文件存在但接管失败时仍指回原文件,保证本次 resume 不因迁移 IO 故障被阻断(此时
- // app-server 仍以 CODEX_HOME=desktop 运行、新事件写进 desktop home,不改源);原文件
- // 本就缺失时把 state 指向当前 HOME,随后由 localDb 历史合成兜底 rollout。
- const preparedRolloutPath = adoptedRollout || !sourceRolloutExists
- ? adoptedRolloutPath
- : found.rolloutPath;
- const copiedState = copyThreadStateToTarget(found, targetDbPath, {
- rolloutPathOverride: preparedRolloutPath,
- });
- const pointedState = pointThreadAtRollout(targetDbPath, threadId, preparedRolloutPath);
- targetRollout = readThreadRolloutPath(targetDbPath, threadId);
- log.info('prepared private-copy external Codex thread for resume', {
+ // An unindexed external empty is outside the current Cindy HOME and therefore
+ // cannot shadow the app-server's scanner. A recent one may still have a live
+ // writer, but a stable one must not permanently poison recovery from Cindy's
+ // own persisted history.
+ const unindexedExternalEmpties = observeUnindexedExternalEmptyRolloutsById(threadId);
+ const recentUnindexedExternalEmpty = unindexedExternalEmpties.find(
+ (candidate) => !isStableEmptyRollout(candidate.snapshot),
+ );
+ if (recentUnindexedExternalEmpty) {
+ throw resumePreparationBlocked(threadId, 'external rollout may still be materializing');
+ }
+ const assertUnindexedExternalEmptiesUnchanged = unindexedExternalEmpties.length > 0
+ ? () => assertExternalEmptyObservationsUnchanged(threadId, unindexedExternalEmpties)
+ : undefined;
+ const assertPrivateRecoverySourcesUnchanged = combineHandoffGuards(
+ assertLocalCanonicalPrecursorsUnchanged,
+ assertUnindexedExternalEmptiesUnchanged,
+ );
+ if (unindexedExternalEmpties.length > 0) {
+ log.info('ignoring stable unindexed external empty during private recovery', {
threadId,
- sourceHome: found.sourceHome,
- copiedState,
- pointedState,
- adoptedRollout,
- rolloutPath: targetRollout,
+ externalRolloutPaths: unindexedExternalEmpties.map((candidate) => candidate.path),
});
- if (targetRollout && fs.existsSync(targetRollout)) return targetRollout;
+ }
+
+ // Prefer a full-fidelity external source above. Only when no state-backed
+ // source can win do we replace a stable local empty from Cindy's projection.
+ if (currentHomeCanonicalEmpty && currentHomeCanonicalEmptySnapshot) {
+ try {
+ const recovered = await recoverStableCanonicalEmptyWithoutTargetState(
+ threadId,
+ targetHome,
+ currentHomeCanonicalEmpty,
+ currentHomeCanonicalEmptySnapshot,
+ assertPrivateRecoverySourcesUnchanged,
+ );
+ if (recovered) return recovered;
+ } catch (error) {
+ failClosedResumePreparation(threadId, 'state-less empty rollout recovery', error);
+ }
+ }
+
+ if (
+ currentHomeThread?.rolloutPath
+ && isNonEmptyRolloutFile(currentHomeThread.rolloutPath, threadId)
+ && !isCanonicalCodexRolloutPath(currentHomeThread.rolloutPath, threadId)
+ ) {
+ throw resumePreparationBlocked(threadId, 'private rollout is not discoverable without state');
+ }
+
+ // An empty standard rollout is invisible to the parser but may still have a
+ // live writer. Do not synthesize a second same-thread file beside it.
+ const currentHomeEmpty = collectRolloutFiles(targetHome).find(
+ (candidate) => threadIdFromRolloutPath(candidate) === threadId
+ && !!readEmptyRolloutSnapshot(candidate),
+ );
+ if (currentHomeEmpty) {
+ throw resumePreparationBlocked(threadId, 'private rollout may still be materializing');
}
// 孤儿兜底: state DB 有 threads 行、但 rollout 文件已缺失(典型成因: 旧版 codex logout
@@ -257,33 +1120,57 @@ export async function prepareExternalCodexSessionForResume(threadId: string): Pr
// xdt-maker localDb 的可读消息历史, 合成一份最小 rollout, 让 thread/resume 能继续。
// 合成版只含 user/assistant 文本(丢 codex 内部 reasoning/tool 细节, 跨供应商时这些本就
// 失效), 是 best-effort 恢复, 失败不抛(让 maker-core 走清晰报错路径)。
- if (targetRollout && !fs.existsSync(targetRollout)) {
- try {
- await synthesizeRolloutForOrphanThread(threadId, targetDbPath, targetRollout);
- } catch (err) {
- log.warn('synthesize orphan rollout failed', {
- threadId,
- error: err instanceof Error ? err.message : String(err),
- });
- }
- } else if (!targetRollout) {
+ if (!targetRollout) {
// 更深一层的孤儿: Cindy localDb 仍保留 sdk_session_id 与可读聊天历史,但 Codex
// state 行和 rollout 同时丢失。不要伪造版本敏感的 threads 行;先在当前 HOME 的
// 标准目录重建 rollout,随后的 thread/resume 会让 app-server 按当前 schema hydrate。
try {
- const synthesizedPath = await synthesizeRolloutForMissingThreadState(threadId, targetHome);
+ const synthesizedPath = await synthesizeRolloutForMissingThreadState(
+ threadId,
+ targetHome,
+ assertPrivateRecoverySourcesUnchanged,
+ );
if (!synthesizedPath) {
+ if (unindexedExternalEmpties.length > 0) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'the stable external empty rollout has no readable private recovery history',
+ );
+ }
log.debug('prepare resume: no localDb recovery source for missing thread state', { threadId });
+ } else if (readEmptyRolloutSnapshot(synthesizedPath)) {
+ throw resumePreparationBlocked(threadId, 'a same-thread rollout began materializing during recovery');
+ } else {
+ return synthesizedPath;
}
} catch (err) {
+ if (err instanceof CodexResumePreparationBlockedError) throw err;
log.warn('synthesize rollout for missing Codex thread state failed', {
threadId,
error: err instanceof Error ? err.message : String(err),
});
}
}
- const preparedRollout = readThreadRolloutPath(targetDbPath, threadId);
- return preparedRollout && fs.existsSync(preparedRollout) ? preparedRollout : undefined;
+ const lateStatePath = readThreadRolloutPath(targetDbPath, threadId);
+ if (!lateStatePath) return undefined;
+ const preparedRollout = readPrivateNonEmptyRollout(targetDbPath, threadId, targetHome);
+ if (!preparedRollout) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'late Codex state appeared outside a readable private recovery boundary',
+ );
+ }
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ preparedRollout,
+ {
+ allowedCanonicalPaths: isCanonicalCodexRolloutPath(preparedRollout, threadId)
+ ? [preparedRollout]
+ : [],
+ },
+ );
}
/** 为外部 thread 派生当前 Codex HOME 内的稳定 rollout 路径。 */
@@ -302,15 +1189,193 @@ function targetRolloutPathForExternalThread(thread: CodexThreadSummary, targetHo
return path.join(targetHome, directory, filename);
}
-/** realpath 可用时先消除 macOS `/var` 等路径别名,再做目录边界判断。 */
-function isPathInside(parentDir: string, candidate: string): boolean {
- const parent = safeRealpathSync(parentDir) ?? path.resolve(parentDir);
- const child = safeRealpathSync(candidate) ?? path.resolve(candidate);
+/** Resolve a missing path through its nearest existing ancestor, including symlinks. */
+function resolvePathForBoundary(candidate: string): string {
+ let current = path.resolve(candidate);
+ const missingSegments: string[] = [];
+ for (;;) {
+ const resolved = safeRealpathSync(current);
+ if (resolved) return path.join(resolved, ...missingSegments);
+ const parent = path.dirname(current);
+ if (parent === current) return path.resolve(candidate);
+ missingSegments.unshift(path.basename(current));
+ current = parent;
+ }
+}
+
+/** 消除 macOS `/var` 别名与已存在的 symlink ancestor,再做目录边界判断。 */
+function isPathInside(parentDir: string, candidate: string): boolean {
+ const parent = resolvePathForBoundary(parentDir);
+ const child = resolvePathForBoundary(candidate);
const relative = path.relative(parent, child);
return relative === ''
|| (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
}
+type PrivateRolloutPathState = 'missing' | 'empty-file' | 'non-empty-file' | 'unsafe';
+
+/** Classify one rollout path without following its final symbolic link. */
+function readRegularRolloutPathState(candidate: string): PrivateRolloutPathState {
+ let before: fs.Stats;
+ try {
+ before = fs.lstatSync(candidate);
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'ENOENT' ? 'missing' : 'unsafe';
+ }
+ if (!before.isFile()) return 'unsafe';
+ try {
+ const after = fs.lstatSync(candidate);
+ if (!after.isFile() || before.dev !== after.dev || before.ino !== after.ino) {
+ return 'unsafe';
+ }
+ return after.size > 0 ? 'non-empty-file' : 'empty-file';
+ } catch {
+ return 'unsafe';
+ }
+}
+
+function rolloutPathIsMissing(candidate: string): boolean {
+ try {
+ fs.lstatSync(candidate);
+ return false;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'ENOENT';
+ }
+}
+
+/**
+ * Revalidate a path that was classified as private while it was absent or
+ * empty. lstat deliberately rejects symbolic links, and the second identity
+ * check closes ordinary replace-between-checks races before a state pointer is
+ * restored to the path.
+ */
+function readPrivateRolloutPathState(targetHome: string, candidate: string): PrivateRolloutPathState {
+ try {
+ const before = fs.lstatSync(candidate);
+ if (!before.isFile() || !isPathInside(targetHome, candidate)) return 'unsafe';
+ const after = fs.lstatSync(candidate);
+ if (!after.isFile() || before.dev !== after.dev || before.ino !== after.ino) return 'unsafe';
+ return after.size > 0 ? 'non-empty-file' : 'empty-file';
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'ENOENT' ? 'missing' : 'unsafe';
+ }
+}
+
+function sameRegularFileIdentity(leftPath: string, rightPath: string): boolean {
+ try {
+ const left = fs.lstatSync(leftPath);
+ const right = fs.lstatSync(rightPath);
+ return left.isFile()
+ && right.isFile()
+ && left.dev === right.dev
+ && left.ino === right.ino;
+ } catch {
+ return false;
+ }
+}
+
+function regularFileIdentityMatchesSnapshot(
+ filePath: string,
+ expected: EmptyRolloutSnapshot,
+): boolean {
+ try {
+ const current = fs.lstatSync(filePath);
+ return current.isFile()
+ && current.dev === expected.dev
+ && current.ino === expected.ino;
+ } catch {
+ return false;
+ }
+}
+
+function resumePreparationBlocked(
+ threadId: string,
+ reason: string,
+): CodexResumePreparationBlockedError {
+ return new CodexResumePreparationBlockedError(
+ `Codex thread ${threadId} is not safe to resume yet: ${reason}. Retry after the current write finishes.`,
+ );
+}
+
+function failClosedResumePreparation(
+ threadId: string,
+ operation: string,
+ error: unknown,
+): never {
+ if (error instanceof CodexResumePreparationBlockedError) throw error;
+ log.warn('Codex resume preparation failed after detecting unsafe state', {
+ threadId,
+ operation,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throw resumePreparationBlocked(threadId, `${operation} failed`);
+}
+
+function privateRolloutPathForStateRow(
+ targetHome: string,
+ recordedPath: string,
+ row: SqlRow | null,
+): string {
+ const directory = numberValue(row?.archived) > 0 ? 'archived_sessions' : 'sessions';
+ const filename = path.basename(recordedPath) || 'rollout-cindy-recovered.jsonl';
+ return path.join(targetHome, directory, filename);
+}
+
+function readPrivateNonEmptyRollout(
+ targetDbPath: string,
+ threadId: string,
+ targetHome: string,
+): string | null {
+ const current = readThreadRolloutPath(targetDbPath, threadId);
+ return current
+ && readPrivateRolloutPathState(targetHome, current) === 'non-empty-file'
+ ? current
+ : null;
+}
+
+/** Revalidate a winner selected during recovery before the caller resumes it. */
+function acceptStateBackedWinnerAfterRecovery(
+ targetDbPath: string,
+ threadId: string,
+ targetHome: string,
+ winner: string,
+ opts: {
+ beforeReturn?: () => void;
+ allowedCanonicalPaths?: readonly string[];
+ } = {},
+): string {
+ const validate = () => {
+ opts.beforeReturn?.();
+ if (opts.allowedCanonicalPaths) {
+ assertNoUnexpectedCanonicalRollouts(
+ threadId,
+ targetHome,
+ opts.allowedCanonicalPaths,
+ );
+ } else if (!opts.beforeReturn) {
+ assertNoUnexpectedCanonicalRollouts(
+ threadId,
+ targetHome,
+ isCanonicalCodexRolloutPath(winner, threadId) ? [winner] : [],
+ );
+ }
+ const stateWinner = readThreadRolloutPath(targetDbPath, threadId);
+ if (
+ !stateWinner
+ || !samePath(stateWinner, winner)
+ || readPrivateRolloutPathState(targetHome, winner) !== 'non-empty-file'
+ ) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'the private state winner changed before recovery could return',
+ );
+ }
+ };
+ validate();
+ validate();
+ return winner;
+}
+
/** 当前区域的全部历史品牌 Codex HOME;不包含当前 Cindy/CindyGlobal HOME。 */
function legacyBrandedCodexHomes(targetHome: string): string[] {
const userDataParent = path.dirname(path.dirname(targetHome));
@@ -319,32 +1384,131 @@ function legacyBrandedCodexHomes(targetHome: string): string[] {
.map((dirName) => path.join(userDataParent, dirName, 'codex-home'));
}
-function isLegacyBrandedCodexLocation(targetHome: string, candidate: string): boolean {
- return legacyBrandedCodexHomes(targetHome).some((legacyHome) => isPathInside(legacyHome, candidate));
-}
-
/**
- * 先复制到同目录临时文件,再用 hard-link 原子发布。并发迁移同一 thread 时只有首个
- * 发布者成功,其余调用复用已存在目标;删除临时 hard-link 不影响正式文件。
+ * Snapshot an external rollout into Cindy storage and atomically publish it.
+ * The source must remain byte/stat stable for the whole copy. Existing private
+ * candidates are reused only when byte-identical; different or empty files are
+ * preserved and, when state can point at one, bypassed with a deterministic sibling.
*/
-async function copyExternalRolloutAtomically(sourcePath: string, targetPath: string): Promise<boolean> {
- if (samePath(sourcePath, targetPath)) return fs.existsSync(sourcePath);
- if (!fs.existsSync(sourcePath)) return false;
- if (fs.existsSync(targetPath)) return true;
+interface PrivateRolloutPublication {
+ path: string;
+ created: boolean;
+ snapshot: NonEmptyRolloutSnapshot;
+}
- await fsp.mkdir(path.dirname(targetPath), { recursive: true });
+function readPrivateNonEmptyRolloutSnapshot(
+ targetHome: string,
+ candidate: string,
+): NonEmptyRolloutSnapshot | null {
+ if (!isPathInside(targetHome, candidate)) return null;
+ const snapshot = readNonEmptyRolloutSnapshot(candidate);
+ return snapshot
+ && nonEmptyRolloutStillMatches(candidate, snapshot)
+ && isPathInside(targetHome, candidate)
+ ? snapshot
+ : null;
+}
+
+function privateRolloutPublicationOwnsPath(
+ targetHome: string,
+ publication: PrivateRolloutPublication,
+ candidatePath = publication.path,
+): boolean {
+ const current = readPrivateNonEmptyRolloutSnapshot(targetHome, candidatePath);
+ return !!current
+ && current.dev === publication.snapshot.dev
+ && current.ino === publication.snapshot.ino;
+}
+
+function privateRolloutPublicationStillMatches(
+ targetHome: string,
+ publication: PrivateRolloutPublication,
+): boolean {
+ const current = readPrivateNonEmptyRolloutSnapshot(targetHome, publication.path);
+ return !!current
+ && current.dev === publication.snapshot.dev
+ && current.ino === publication.snapshot.ino
+ && current.size === publication.snapshot.size
+ // Removing the temporary hard-link after publication legitimately changes
+ // ctime/link-count on the same immutable inode; mtime still binds content.
+ && current.mtimeMs === publication.snapshot.mtimeMs;
+}
+
+async function copyExternalRolloutAtomically(
+ sourcePath: string,
+ preferredPath: string,
+ threadId: string,
+ opts: { allowSibling: boolean; skipPreferred?: boolean },
+): Promise<PrivateRolloutPublication | null> {
+ if (samePath(sourcePath, preferredPath)) return null;
+ const targetHome = getDesktopCodexHome();
+ if (!isPathInside(targetHome, preferredPath)) return null;
+ const sourceSnapshot = readNonEmptyRolloutSnapshot(sourcePath);
+ if (!sourceSnapshot) return null;
+
+ await fsp.mkdir(path.dirname(preferredPath), { recursive: true });
const tempPath = path.join(
- path.dirname(targetPath),
- `.${path.basename(targetPath)}.${randomUUID()}.migration-tmp`,
+ path.dirname(preferredPath),
+ `.${path.basename(preferredPath)}.${randomUUID()}.migration-tmp`,
);
try {
await fsp.copyFile(sourcePath, tempPath, fs.constants.COPYFILE_EXCL);
- try {
- await fsp.link(tempPath, targetPath);
- } catch (err) {
- if (!fs.existsSync(targetPath)) throw err;
+ const tempSnapshot = readNonEmptyRolloutSnapshot(tempPath);
+ if (
+ !tempSnapshot
+ || tempSnapshot.size !== sourceSnapshot.size
+ || !nonEmptyRolloutStillMatches(sourcePath, sourceSnapshot)
+ ) return null;
+
+ const attempts = opts.allowSibling ? MAX_RECOVERY_PATH_ATTEMPTS : 1;
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
+ if (!nonEmptyRolloutStillMatches(sourcePath, sourceSnapshot)) return null;
+ let candidate = preferredPath;
+ if (opts.skipPreferred) {
+ candidate = recoveredSiblingRolloutPath(preferredPath, threadId, attempt, 'adopted');
+ } else if (attempt > 0) {
+ candidate = recoveredSiblingRolloutPath(preferredPath, threadId, attempt - 1, 'adopted');
+ }
+ if (fs.existsSync(candidate)) {
+ const candidateSnapshot = readPrivateNonEmptyRolloutSnapshot(targetHome, candidate);
+ if (
+ candidateSnapshot
+ && filesHaveSameContents(candidate, tempPath)
+ && nonEmptyRolloutStillMatches(candidate, candidateSnapshot)
+ && nonEmptyRolloutStillMatches(sourcePath, sourceSnapshot)
+ ) return { path: candidate, created: false, snapshot: candidateSnapshot };
+ if (!nonEmptyRolloutStillMatches(sourcePath, sourceSnapshot)) return null;
+ continue;
+ }
+
+ // This is the snapshot boundary: the source was stable for the complete
+ // copy and immediately before atomic publication. Bytes appended after
+ // this check belong to the still-preserved external runtime, while Cindy
+ // intentionally continues from its isolated point-in-time copy (#789).
+ if (!nonEmptyRolloutStillMatches(sourcePath, sourceSnapshot)) return null;
+ try {
+ await fsp.link(tempPath, candidate);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;
+ const candidateSnapshot = readPrivateNonEmptyRolloutSnapshot(targetHome, candidate);
+ if (
+ candidateSnapshot
+ && filesHaveSameContents(candidate, tempPath)
+ && nonEmptyRolloutStillMatches(candidate, candidateSnapshot)
+ && nonEmptyRolloutStillMatches(sourcePath, sourceSnapshot)
+ ) return { path: candidate, created: false, snapshot: candidateSnapshot };
+ if (!nonEmptyRolloutStillMatches(sourcePath, sourceSnapshot)) return null;
+ continue;
+ }
+ const candidateSnapshot = readPrivateNonEmptyRolloutSnapshot(targetHome, candidate);
+ if (
+ !candidateSnapshot
+ || !sameRegularFileIdentity(tempPath, candidate)
+ || !nonEmptyRolloutStillMatches(sourcePath, sourceSnapshot)
+ ) return null;
+ return { path: candidate, created: true, snapshot: candidateSnapshot };
}
- return true;
+ return null;
} finally {
await fsp.rm(tempPath, { force: true }).catch(() => undefined);
}
@@ -664,158 +1828,1520 @@ function pickColumns(row: Record<string, SqlScalar>, columns: string[]): Record<
return out;
}
-/**
- * 孤儿恢复: 给 state DB 里有 threads 行、但磁盘 rollout 文件缺失的 thread, 用 localDb 里
- * 可读的消息历史合成一份最小 rollout 写回 `rolloutPath`, 让 codex thread/resume 能继续。
- * 仅在确有 threads 行(=曾真实存在过的会话)且 localDb 有可读历史时才写; 否则 no-op。
- */
-async function synthesizeRolloutForOrphanThread(
+/** Recover a missing private pointer without writing into the recorded path. */
+async function recoverMissingPrivateRollout(
threadId: string,
targetDbPath: string,
- rolloutPath: string,
-): Promise<void> {
+ targetHome: string,
+ recordedPath: string,
+ beforeHandoff?: () => void,
+ beforeReturn?: () => void,
+): Promise<string | undefined> {
const row = readRawThreadRow(targetDbPath, threadId);
- if (!row) {
- log.debug('orphan synth skipped: threads row missing', { threadId });
- return;
+ if (!row) throw resumePreparationBlocked(threadId, 'target state disappeared during recovery');
+
+ const published = await publishFreshSyntheticBeforeHandoff(
+ recordedPath,
+ threadId,
+ row,
+ { skipPreferred: true },
+ );
+ if (!published) {
+ if ((await readXdtMessagesByThreadId(threadId)).length === 0) {
+ log.debug('private orphan recovery skipped: no readable localDb messages', { threadId });
+ return undefined;
+ }
+ throw resumePreparationBlocked(threadId, 'a private recovery file could not be published safely');
}
- const messages = await readXdtMessagesByThreadId(threadId);
- if (messages.length === 0) {
- log.debug('orphan synth skipped: no readable localDb messages', { threadId });
- return;
+
+ // The absent path can still belong to a live Codex writer. It remains
+ // authoritative until the state pointer is handed to the synthetic sibling.
+ const materializedBeforeCas = readPrivateRolloutPathState(targetHome, recordedPath);
+ if (materializedBeforeCas === 'non-empty-file') {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ recordedPath,
+ { allowedCanonicalPaths: [recordedPath] },
+ );
+ }
+ if (materializedBeforeCas === 'empty-file') {
+ throw resumePreparationBlocked(threadId, 'the private orphan began materializing during recovery');
}
- const jsonl = buildSyntheticRollout(threadId, row, messages);
- await fsp.mkdir(path.dirname(rolloutPath), { recursive: true });
- await fsp.writeFile(rolloutPath, jsonl, 'utf-8');
- log.info('synthesized rollout for orphan Codex thread', {
+ if (materializedBeforeCas === 'unsafe') {
+ throw resumePreparationBlocked(
+ threadId,
+ 'the private orphan materialized outside Cindy storage or as a non-file',
+ );
+ }
+
+ handoffThreadToSyntheticRollout(
+ targetDbPath,
threadId,
- rolloutPath,
- messageCount: messages.length,
+ targetHome,
+ recordedPath,
+ published,
+ () => {
+ beforeHandoff?.();
+ return readPrivateRolloutPathState(targetHome, recordedPath) === 'missing';
+ },
+ );
+
+ // Missing-path validation ran inside the write transaction. Once that
+ // transaction commits, the synthetic path is irreversible; a writer that
+ // wakes afterward is preserved but cannot pull state away from a live winner.
+ const stateWinnerPath = readThreadRolloutPath(targetDbPath, threadId);
+ const materializedAfterCas = readPrivateRolloutPathState(targetHome, recordedPath);
+ if (stateWinnerPath === recordedPath) {
+ if (materializedAfterCas === 'non-empty-file') {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ recordedPath,
+ { allowedCanonicalPaths: [recordedPath] },
+ );
+ }
+ if (materializedAfterCas === 'empty-file') {
+ throw resumePreparationBlocked(threadId, 'the private orphan began materializing during recovery');
+ }
+ if (materializedAfterCas === 'unsafe') {
+ throw resumePreparationBlocked(
+ threadId,
+ 'the private orphan materialized outside Cindy storage or as a non-file',
+ );
+ }
+ } else if (materializedAfterCas !== 'missing') {
+ log.warn('late private orphan was preserved after committed recovery handoff', {
+ threadId,
+ originalRolloutPath: recordedPath,
+ recoveredRolloutPath: published.path,
+ });
+ }
+
+ const winner = readPrivateNonEmptyRollout(targetDbPath, threadId, targetHome);
+ if (!isAcceptableSyntheticWinner(targetHome, winner, published)) {
+ throw resumePreparationBlocked(threadId, 'target state changed during private orphan recovery');
+ }
+ log.info('recovered missing private Codex rollout from Cindy history', {
+ threadId,
+ originalRolloutPath: recordedPath,
+ recoveredRolloutPath: winner,
+ messageCount: published.messageCount,
+ created: published.created,
});
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ winner!,
+ { beforeReturn },
+ );
}
-/** Cindy 会话仍在、Codex state 与 rollout 都丢失时用于重建 session_meta 的最小元数据。 */
-interface LocalCodexRecoverySession {
- id: string;
- workingDir: string;
- model: string | null;
- createdAt: number;
- updatedAt: number;
-}
+/** Recover a missing external pointer without ever recreating data outside Cindy storage. */
+async function recoverMissingExternalRollout(
+ threadId: string,
+ targetDbPath: string,
+ targetHome: string,
+ recordedPath: string,
+ beforeHandoff?: () => void,
+ beforeReturn?: () => void,
+): Promise<string> {
+ const row = readRawThreadRow(targetDbPath, threadId);
+ if (!row) throw resumePreparationBlocked(threadId, 'target state disappeared during recovery');
-/** 一条可用于合成 rollout 的 Cindy 会话及其已过滤历史。 */
-interface LocalCodexRecoverySource {
- session: LocalCodexRecoverySession;
- messages: SyntheticRolloutMessage[];
- recoveryCreatedAt: number;
+ const preferred = privateRolloutPathForStateRow(targetHome, recordedPath, row);
+ const published = await publishFreshSyntheticBeforeHandoff(
+ preferred,
+ threadId,
+ row,
+ { skipPreferred: true },
+ );
+ if (!published) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'the external rollout is missing and no fresh readable history could be published safely',
+ );
+ }
+ handoffThreadToSyntheticRollout(
+ targetDbPath,
+ threadId,
+ targetHome,
+ recordedPath,
+ published,
+ () => {
+ beforeHandoff?.();
+ return rolloutPathIsMissing(recordedPath);
+ },
+ );
+ const winner = readPrivateNonEmptyRollout(targetDbPath, threadId, targetHome);
+ if (!isAcceptableSyntheticWinner(targetHome, winner, published)) {
+ throw resumePreparationBlocked(threadId, 'target state changed during missing-rollout recovery');
+ }
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ winner!,
+ { beforeReturn },
+ );
}
/**
- * 双缺失恢复:只重建标准位置的 rollout,让 app-server thread/resume 重新生成当前版本的
- * state 行。写入路径由原会话创建时间稳定派生,重复调用和并发调用都复用同一文件。
+ * No target row exists, but an external current-schema row still identifies a
+ * stably empty rollout. Publish a private synthetic history first, then copy the
+ * source row with its rollout pointer overridden. The external empty is never
+ * modified and an unindexed empty is intentionally not recoverable here.
*/
-async function synthesizeRolloutForMissingThreadState(
+async function recoverStableExternalEmptyWithoutTargetState(
threadId: string,
+ targetDbPath: string,
targetHome: string,
-): Promise<string | null> {
- const source = await readBestLocalCodexRecoverySource(threadId);
- if (!source) return null;
- const { session, messages, recoveryCreatedAt } = source;
+ external: CodexThreadSummary,
+ originalEmpty: EmptyRolloutSnapshot,
+ beforeHandoff?: () => void,
+ beforeReturn?: () => void,
+): Promise<string> {
+ if (!isStableEmptyRollout(originalEmpty)) {
+ throw resumePreparationBlocked(threadId, 'external rollout may still be materializing');
+ }
+ if (!external.sourceDbPath) {
+ throw resumePreparationBlocked(threadId, 'external empty rollout has no state metadata');
+ }
- const rolloutPath = recoveredRolloutPath(targetHome, threadId, recoveryCreatedAt);
- const row: SqlRow = {
- created_at_ms: recoveryCreatedAt,
- cwd: session.workingDir,
- originator: 'xdt-maker',
- source: 'cli',
- model: session.model,
+ const sourceRow = readRawThreadRow(external.sourceDbPath, threadId);
+ if (!sourceRow) {
+ throw resumePreparationBlocked(threadId, 'external thread state disappeared during recovery');
+ }
+
+ const preferred = targetRolloutPathForExternalThread(external, targetHome);
+ const published = await publishFreshSyntheticBeforeHandoff(
+ preferred,
+ threadId,
+ sourceRow,
+ // Keep an unpublished partial result visibly Cindy-owned. If the external
+ // writer wakes before state handoff, the next attempt must adopt that source
+ // instead of mistaking this orphan for a canonical Codex rollout.
+ { skipPreferred: true },
+ );
+ if (!published) {
+ throw resumePreparationBlocked(threadId, 'a private recovery file could not be published safely');
+ }
+
+ if (!emptyRolloutStillMatches(external.rolloutPath, originalEmpty)) {
+ throw resumePreparationBlocked(threadId, 'external rollout changed before private state handoff');
+ }
+
+ const assertRecoverySourcesUnchanged = () => {
+ beforeHandoff?.();
+ if (!emptyRolloutStillMatches(external.rolloutPath, originalEmpty)) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'external rollout changed before private state handoff',
+ );
+ }
};
- const jsonl = buildSyntheticRollout(threadId, row, messages);
- const created = await writeFileAtomicallyIfAbsent(rolloutPath, jsonl);
- log.info('synthesized rollout for missing Codex thread state', {
+ const copiedState = copyThreadStateToTarget(external, targetDbPath, {
+ rolloutPathOverride: published.path,
+ validateBeforeCopy: () => {
+ assertRecoverySourcesUnchanged();
+ return syntheticPublicationStillMatches(targetHome, published);
+ },
+ validateAfterCopy: () => {
+ assertRecoverySourcesUnchanged();
+ return syntheticPublicationOwnsPath(targetHome, published);
+ },
+ });
+ const winner = readPrivateNonEmptyRollout(targetDbPath, threadId, targetHome);
+ if (!winner) {
+ log.warn('external empty rollout recovery could not establish private state', {
+ threadId,
+ copiedState,
+ recoveredRolloutPath: published.path,
+ });
+ throw resumePreparationBlocked(threadId, 'external state could not be copied after recovery');
+ }
+ if (!isAcceptableSyntheticWinner(targetHome, winner, published)) {
+ throw resumePreparationBlocked(threadId, 'a concurrent state handoff selected a different recovery');
+ }
+
+ if (!emptyRolloutStillMatches(external.rolloutPath, originalEmpty)) {
+ log.warn('external rollout changed after private state handoff; preserved outside Cindy append boundary', {
+ threadId,
+ externalRolloutPath: external.rolloutPath,
+ recoveredRolloutPath: winner,
+ });
+ }
+ log.info('recovered stable external empty rollout with source state', {
threadId,
- rolloutPath,
- messageCount: messages.length,
- created,
+ externalRolloutPath: external.rolloutPath,
+ recoveredRolloutPath: winner,
+ messageCount: published.messageCount,
+ created: published.created,
});
- return rolloutPath;
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ winner,
+ { beforeReturn },
+ );
}
/**
- * 同一 Codex thread 可能被复制或 rewind 成多条 Cindy 会话。恢复时逐条读取可见历史,
- * 优先选择消息最完整的一条;其余字段只负责确定性打破平局,不合并可能分叉的历史。
+ * Repair the #1554 shape: an existing state row points at a stably empty
+ * rollout. The original is preserved, a private recovery is published first,
+ * and the state pointer moves transactionally. Private writers detected before
+ * commit remain authoritative; writers waking after commit are preserved but
+ * never pull state away from the recovered append target.
*/
-async function readBestLocalCodexRecoverySource(threadId: string): Promise<LocalCodexRecoverySource | null> {
- const sessions = await getDbClient().query<LocalCodexRecoverySession>(`
- SELECT
- id,
- working_dir AS workingDir,
- model,
- created_at AS createdAt,
- updated_at AS updatedAt
- FROM sessions
- WHERE agent_kind = 'codex' AND sdk_session_id = ? AND status <> 'deleted'
- `, [threadId]);
-
- let best: LocalCodexRecoverySource | null = null;
- for (const session of sessions) {
- const messages = await readXdtMessagesBySessionId(session.id);
- if (messages.length === 0) continue;
- const sessionCreatedAt = numberValue(session.createdAt);
- const firstPositiveMessageAt = messages.find((message) => message.createdAt > 0)?.createdAt ?? 0;
- const candidate: LocalCodexRecoverySource = {
- session,
- messages,
- recoveryCreatedAt: sessionCreatedAt > 0 ? sessionCreatedAt : firstPositiveMessageAt,
- };
- if (!best || isPreferredRecoverySource(candidate, best)) best = candidate;
+async function recoverStableEmptyRollout(
+ threadId: string,
+ targetDbPath: string,
+ targetHome: string,
+ rolloutPath: string,
+ beforeHandoff?: () => void,
+ beforeReturn?: () => void,
+): Promise<string | undefined> {
+ const originalEmpty = readEmptyRolloutSnapshot(rolloutPath);
+ if (!originalEmpty || !isStableEmptyRollout(originalEmpty)) {
+ log.debug('empty rollout recovery deferred: file may still be materializing', {
+ threadId,
+ rolloutPath,
+ });
+ throw resumePreparationBlocked(threadId, 'the rollout may still be materializing');
}
- return best;
-}
-function isPreferredRecoverySource(
- candidate: LocalCodexRecoverySource,
- current: LocalCodexRecoverySource,
-): boolean {
- if (candidate.messages.length !== current.messages.length) {
- return candidate.messages.length > current.messages.length;
+ const row = readRawThreadRow(targetDbPath, threadId);
+ if (!row) throw resumePreparationBlocked(threadId, 'target state disappeared during recovery');
+
+ const originalIsPrivate = isPathInside(targetHome, rolloutPath);
+ const preferredPrivatePath = originalIsPrivate
+ ? rolloutPath
+ : privateRolloutPathForStateRow(targetHome, rolloutPath, row);
+ const published = await publishFreshSyntheticBeforeHandoff(
+ preferredPrivatePath,
+ threadId,
+ row,
+ { skipPreferred: true },
+ );
+ if (!published) {
+ throw resumePreparationBlocked(threadId, 'a private recovery file could not be published safely');
}
- const candidateUpdatedAt = numberValue(candidate.session.updatedAt);
- const currentUpdatedAt = numberValue(current.session.updatedAt);
- if (candidateUpdatedAt !== currentUpdatedAt) return candidateUpdatedAt > currentUpdatedAt;
- const candidateCreatedAt = numberValue(candidate.session.createdAt);
- const currentCreatedAt = numberValue(current.session.createdAt);
- if (candidateCreatedAt !== currentCreatedAt) return candidateCreatedAt > currentCreatedAt;
+ const originalChangedBeforeCas = !emptyRolloutStillMatches(rolloutPath, originalEmpty);
+ if (originalChangedBeforeCas && originalIsPrivate) {
+ const current = readPrivateRolloutPathState(targetHome, rolloutPath);
+ if (current === 'non-empty-file') {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ rolloutPath,
+ { allowedCanonicalPaths: [rolloutPath] },
+ );
+ }
+ if (current === 'empty-file') {
+ throw resumePreparationBlocked(threadId, 'the private rollout changed during recovery');
+ }
+ throw resumePreparationBlocked(
+ threadId,
+ 'the private rollout changed outside its safe storage boundary during recovery',
+ );
+ }
+
+ handoffThreadToSyntheticRollout(
+ targetDbPath,
+ threadId,
+ targetHome,
+ rolloutPath,
+ published,
+ () => {
+ beforeHandoff?.();
+ return emptyRolloutStillMatches(rolloutPath, originalEmpty);
+ },
+ );
+ let recoveredWinner = readPrivateNonEmptyRollout(targetDbPath, threadId, targetHome);
+
+ const originalChangedAfterCas = !emptyRolloutStillMatches(rolloutPath, originalEmpty);
+ if (originalChangedAfterCas && originalIsPrivate) {
+ const current = readPrivateRolloutPathState(targetHome, rolloutPath);
+ const stateWinner = readThreadRolloutPath(targetDbPath, threadId);
+ if (stateWinner === rolloutPath) {
+ if (current === 'non-empty-file') {
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ rolloutPath,
+ { allowedCanonicalPaths: [rolloutPath] },
+ );
+ }
+ if (current === 'empty-file') {
+ throw resumePreparationBlocked(threadId, 'the private rollout began materializing during recovery');
+ }
+ throw resumePreparationBlocked(
+ threadId,
+ 'the private rollout changed outside its safe storage boundary during recovery',
+ );
+ } else {
+ log.warn('late private rollout was preserved after committed recovery handoff', {
+ threadId,
+ originalRolloutPath: rolloutPath,
+ recoveredRolloutPath: published.path,
+ });
+ }
+ }
+ if ((originalChangedBeforeCas || originalChangedAfterCas) && !originalIsPrivate) {
+ log.warn('external rollout changed during recovery; preserved outside Cindy append boundary', {
+ threadId,
+ externalRolloutPath: rolloutPath,
+ recoveredRolloutPath: published.path,
+ });
+ }
+ recoveredWinner = readPrivateNonEmptyRollout(targetDbPath, threadId, targetHome);
+ if (!recoveredWinner) {
+ throw resumePreparationBlocked(threadId, 'the rollout pointer changed during recovery');
+ }
+
+ // A concurrent recovery may win CAS with a different path. Accept it only
+ // when it is byte-identical to the snapshot verified immediately pre-handoff.
+ if (!isAcceptableSyntheticWinner(targetHome, recoveredWinner, published)) {
+ throw resumePreparationBlocked(threadId, 'a concurrent state handoff selected a different recovery');
+ }
+
+ log.info('recovered stable empty Codex rollout from Cindy history', {
+ threadId,
+ originalRolloutPath: rolloutPath,
+ recoveredRolloutPath: recoveredWinner,
+ messageCount: published.messageCount,
+ created: published.created,
+ });
+ return acceptStateBackedWinnerAfterRecovery(
+ targetDbPath,
+ threadId,
+ targetHome,
+ recoveredWinner,
+ { beforeReturn },
+ );
+}
+
+function syntheticPublicationStillMatches(
+ targetHome: string,
+ publication: FreshSyntheticPublication,
+): boolean {
+ const current = readPrivateExactRolloutSnapshot(
+ targetHome,
+ publication.path,
+ publication.contents,
+ );
+ return !!current
+ && current.dev === publication.snapshot.dev
+ && current.ino === publication.snapshot.ino
+ && current.size === publication.snapshot.size
+ && current.mtimeMs === publication.snapshot.mtimeMs
+ && current.ctimeMs === publication.snapshot.ctimeMs
+ && current.birthtimeMs === publication.snapshot.birthtimeMs;
+}
+
+/** Same published inode is still private and regular; native appends are valid. */
+function syntheticPublicationOwnsPath(
+ targetHome: string,
+ publication: FreshSyntheticPublication,
+ candidatePath: string = publication.path,
+): boolean {
+ if (!isPathInside(targetHome, candidatePath)) return false;
+ try {
+ const before = fs.lstatSync(candidatePath);
+ if (
+ !before.isFile()
+ || before.size <= 0
+ || before.dev !== publication.snapshot.dev
+ || before.ino !== publication.snapshot.ino
+ ) return false;
+ const after = fs.lstatSync(candidatePath);
+ return after.isFile()
+ && after.size > 0
+ && after.dev === before.dev
+ && after.ino === before.ino
+ && isPathInside(targetHome, candidatePath);
+ } catch {
+ return false;
+ }
+}
+
+function isAcceptableSyntheticWinner(
+ targetHome: string,
+ winner: string | null,
+ publication: FreshSyntheticPublication,
+): boolean {
+ if (!winner) return false;
+ if (samePath(winner, publication.path)) {
+ // Once a transaction commits this private regular path, native Codex may
+ // immediately append or another validated recovery may reuse the same name.
+ return readPrivateRolloutPathState(targetHome, winner) === 'non-empty-file';
+ }
+ return !!readPrivateExactRolloutSnapshot(targetHome, winner, publication.contents);
+}
+
+/**
+ * Reconcile an invalid external state pointer to an already-native private
+ * rollout. Identity, rather than size, is the boundary because Codex may keep
+ * appending to this inode while the IMMEDIATE transaction commits.
+ */
+function handoffThreadToNativeRollout(
+ targetDbPath: string,
+ threadId: string,
+ targetHome: string,
+ expectedRolloutPath: string,
+ publication: PrivateRolloutPublication,
+ expectedPathGuard?: () => void,
+): boolean {
+ let db: Database.Database | null = null;
+ const rollback = new Error('native rollout identity changed during state reconciliation');
+ try {
+ db = createBetterSqliteDatabase(targetDbPath);
+ db.pragma(`busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS}`);
+ if (!tableExists(db, 'threads')) return false;
+ const targetDb = db;
+ const handoff = targetDb.transaction(() => {
+ const current = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ? LIMIT 1')
+ .get(threadId) as { rolloutPath?: unknown } | undefined;
+ if (current?.rolloutPath === publication.path) {
+ return privateRolloutPublicationOwnsPath(targetHome, publication);
+ }
+ if (current?.rolloutPath !== expectedRolloutPath) return false;
+ expectedPathGuard?.();
+ if (!privateRolloutPublicationOwnsPath(targetHome, publication)) return false;
+ const updated = targetDb.prepare(
+ 'UPDATE threads SET rollout_path = ? WHERE id = ? AND rollout_path = ?',
+ ).run(publication.path, threadId, expectedRolloutPath);
+ if (updated.changes === 0) return false;
+ if (!privateRolloutPublicationOwnsPath(targetHome, publication)) throw rollback;
+ expectedPathGuard?.();
+ return true;
+ });
+ return handoff.immediate();
+ } catch (error) {
+ if (error !== rollback) {
+ log.warn('failed to reconcile Codex thread to native rollout', {
+ threadId,
+ rolloutPath: publication.path,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ return false;
+ } finally {
+ closeDbQuietly(db);
+ }
+}
+
+function handoffThreadToCopiedRollout(
+ targetDbPath: string,
+ threadId: string,
+ targetHome: string,
+ expectedRolloutPath: string,
+ publication: PrivateRolloutPublication,
+ expectedPathGuard?: () => void,
+): boolean {
+ let db: Database.Database | null = null;
+ const rollback = new Error('copied rollout identity changed during state handoff');
+ try {
+ db = createBetterSqliteDatabase(targetDbPath);
+ db.pragma(`busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS}`);
+ if (!tableExists(db, 'threads')) return false;
+ const targetDb = db;
+ const handoff = targetDb.transaction(() => {
+ const current = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ? LIMIT 1')
+ .get(threadId) as { rolloutPath?: unknown } | undefined;
+ if (current?.rolloutPath === publication.path) {
+ return readPrivateRolloutPathState(targetHome, publication.path) === 'non-empty-file';
+ }
+ if (current?.rolloutPath !== expectedRolloutPath) return false;
+ expectedPathGuard?.();
+ if (!privateRolloutPublicationStillMatches(targetHome, publication)) return false;
+ const updated = targetDb.prepare(
+ 'UPDATE threads SET rollout_path = ? WHERE id = ? AND rollout_path = ?',
+ ).run(publication.path, threadId, expectedRolloutPath);
+ if (updated.changes === 0) return false;
+ if (!privateRolloutPublicationStillMatches(targetHome, publication)) throw rollback;
+ expectedPathGuard?.();
+ return true;
+ });
+ return handoff.immediate();
+ } catch (error) {
+ if (error !== rollback) {
+ log.warn('failed to hand off Codex thread to copied rollout', {
+ threadId,
+ rolloutPath: publication.path,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ return false;
+ } finally {
+ closeDbQuietly(db);
+ }
+}
+
+/**
+ * Persist an existing-row handoff only while the exact staged snapshot is
+ * current. If the path is swapped during CAS, roll back only our pointer. A
+ * same-inode append after CAS is authoritative native progress and is retained.
+ */
+function handoffThreadToSyntheticRollout(
+ targetDbPath: string,
+ threadId: string,
+ targetHome: string,
+ expectedRolloutPath: string,
+ publication: FreshSyntheticPublication,
+ expectedPathStillOwns?: () => boolean,
+): boolean {
+ let db: Database.Database | null = null;
+ const rollback = new Error('synthetic rollout identity changed during state handoff');
+ try {
+ db = createBetterSqliteDatabase(targetDbPath);
+ db.pragma(`busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS}`);
+ if (!tableExists(db, 'threads')) return false;
+ const targetDb = db;
+ const handoff = targetDb.transaction(() => {
+ const current = targetDb
+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ? LIMIT 1')
+ .get(threadId) as { rolloutPath?: unknown } | undefined;
+ if (current?.rolloutPath === publication.path) {
+ return readPrivateRolloutPathState(targetHome, publication.path) === 'non-empty-file';
+ }
+ if (current?.rolloutPath !== expectedRolloutPath) return false;
+ if (expectedPathStillOwns && !expectedPathStillOwns()) return false;
+ if (!syntheticPublicationStillMatches(targetHome, publication)) return false;
+
+ const updated = targetDb.prepare(
+ 'UPDATE threads SET rollout_path = ? WHERE id = ? AND rollout_path = ?',
+ ).run(publication.path, threadId, expectedRolloutPath);
+ if (updated.changes === 0) return false;
+ // Throwing here rolls back the still-uncommitted pointer. No other
+ // recovery can commit a same-path handoff while this write tx is open.
+ if (
+ !syntheticPublicationOwnsPath(targetHome, publication)
+ || (expectedPathStillOwns && !expectedPathStillOwns())
+ ) throw rollback;
+ return true;
+ });
+ return handoff.immediate();
+ } catch (error) {
+ if (error !== rollback) {
+ log.warn('failed to hand off Codex thread to synthetic rollout', {
+ threadId,
+ rolloutPath: publication.path,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ return false;
+ } finally {
+ closeDbQuietly(db);
+ }
+}
+
+/** Cindy 会话仍在、Codex state 与 rollout 都丢失时用于重建 session_meta 的最小元数据。 */
+interface LocalCodexRecoverySession {
+ id: string;
+ workingDir: string;
+ model: string | null;
+ createdAt: number;
+ updatedAt: number;
+}
+
+/** 一条可用于合成 rollout 的 Cindy 会话及其已过滤历史。 */
+interface LocalCodexRecoverySource {
+ session: LocalCodexRecoverySession;
+ messages: SyntheticRolloutMessage[];
+ recoveryCreatedAt: number;
+}
+
+interface FreshLocalSyntheticPublication extends FreshSyntheticPublication {
+ source: LocalCodexRecoverySource;
+}
+
+/**
+ * Stage a state-less recovery under a Cindy-only filename. Codex's UUID lookup
+ * returns the first canonical filename yielded by read_dir, not the newest one,
+ * so H1/H2 convergence must finish before any canonical candidate is visible.
+ */
+async function publishFreshLocalSyntheticBeforeHandoff(
+ preferredPath: string,
+ threadId: string,
+): Promise<FreshLocalSyntheticPublication | null> {
+ for (let attempt = 0; attempt < MAX_RECOVERY_PATH_ATTEMPTS; attempt += 1) {
+ const source = await readBestLocalCodexRecoverySource(threadId);
+ if (!source) return null;
+ const contents = buildSyntheticRollout(
+ threadId,
+ syntheticRowForLocalRecoverySource(source),
+ source.messages,
+ );
+ const published = await publishSyntheticRollout(
+ preferredPath,
+ threadId,
+ contents,
+ { skipPreferred: true, siblingKind: 'state-less-stage' },
+ );
+ if (!published) return null;
+
+ const latestSource = await readBestLocalCodexRecoverySource(threadId);
+ if (!latestSource) {
+ throw resumePreparationBlocked(threadId, 'local recovery history disappeared before handoff');
+ }
+ const latestContents = buildSyntheticRollout(
+ threadId,
+ syntheticRowForLocalRecoverySource(latestSource),
+ latestSource.messages,
+ );
+ const latestSnapshot = readPrivateExactRolloutSnapshot(
+ getDesktopCodexHome(),
+ published.path,
+ latestContents,
+ );
+ if (latestSnapshot) {
+ return {
+ ...published,
+ snapshot: latestSnapshot,
+ contents: latestContents,
+ messageCount: latestSource.messages.length,
+ source: latestSource,
+ };
+ }
+ }
+ throw resumePreparationBlocked(threadId, 'local recovery history did not stabilize before handoff');
+}
+
+interface CanonicalSyntheticPublication {
+ path: string;
+ created: boolean;
+ synthetic: boolean;
+}
+
+/** Atomically expose one exact synthetic candidate under Codex's canonical filename. */
+function publishStagedSyntheticAtCanonical(
+ threadId: string,
+ targetHome: string,
+ staged: FreshLocalSyntheticPublication,
+ canonicalPath: string,
+ expectedCanonicalStillAvailable?: () => boolean,
+): CanonicalSyntheticPublication {
+ if (
+ !isCanonicalCodexRolloutPath(canonicalPath, threadId)
+ || !isPathInside(targetHome, canonicalPath)
+ ) {
+ throw resumePreparationBlocked(threadId, 'the recovery target is outside the canonical private layout');
+ }
+ if (!syntheticPublicationStillMatches(targetHome, staged)) {
+ throw resumePreparationBlocked(threadId, 'the staged recovery changed outside its safe boundary');
+ }
+ if (expectedCanonicalStillAvailable && !expectedCanonicalStillAvailable()) {
+ throw resumePreparationBlocked(threadId, 'the preserved rollout materialized before canonical handoff');
+ }
+ try {
+ fs.linkSync(staged.path, canonicalPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
+ const winner = readPrivateRolloutPathState(targetHome, canonicalPath);
+ if (
+ winner === 'non-empty-file'
+ && syntheticPublicationOwnsPath(targetHome, staged, canonicalPath)
+ ) {
+ assertSoleCanonicalPath(threadId, targetHome, canonicalPath, true);
+ return { path: canonicalPath, created: false, synthetic: true };
+ }
+ if (
+ winner === 'non-empty-file'
+ && syntheticPublicationStillMatches(targetHome, staged)
+ && readPrivateExactRolloutSnapshot(targetHome, canonicalPath, staged.contents)
+ ) {
+ assertSoleCanonicalPath(threadId, targetHome, canonicalPath, true);
+ return { path: canonicalPath, created: false, synthetic: true };
+ }
+ if (winner === 'non-empty-file') {
+ assertSoleCanonicalPath(threadId, targetHome, canonicalPath, true);
+ return { path: canonicalPath, created: false, synthetic: false };
+ }
+ if (winner === 'empty-file') {
+ throw resumePreparationBlocked(threadId, 'a same-thread rollout began materializing during recovery');
+ }
+ throw resumePreparationBlocked(threadId, 'the canonical recovery path changed outside its safe boundary');
+ }
+ if (syntheticPublicationOwnsPath(targetHome, staged, canonicalPath)) {
+ assertSoleCanonicalPath(threadId, targetHome, canonicalPath, true);
+ return { path: canonicalPath, created: true, synthetic: true };
+ }
+
+ // We created this name from a Cindy-only staging path. If that staging name
+ // was replaced with another inode during link(), remove only the hard-link
+ // we just created; a same-inode native append is accepted above and retained.
+ if (
+ readPrivateRolloutPathState(targetHome, staged.path) === 'non-empty-file'
+ && readPrivateRolloutPathState(targetHome, canonicalPath) === 'non-empty-file'
+ && sameRegularFileIdentity(staged.path, canonicalPath)
+ ) {
+ fs.unlinkSync(canonicalPath);
+ }
+ throw resumePreparationBlocked(threadId, 'the canonical recovery publication changed before handoff');
+}
+
+type EmptyCanonicalPreservation =
+ | { kind: 'native-winner' }
+ | { kind: 'preserved'; path: string };
+
+/**
+ * Move a stable empty canonical name aside without overwriting anything. A
+ * hard-link followed by unlink preserves the original inode even when a late
+ * Codex writer still has it open.
+ */
+function preserveStableEmptyCanonical(
+ threadId: string,
+ targetHome: string,
+ canonicalPath: string,
+ originalEmpty: EmptyRolloutSnapshot,
+ opts: { preserveLateNativeAsArtifact?: boolean } = {},
+): EmptyCanonicalPreservation {
+ const current = readPrivateRolloutPathState(targetHome, canonicalPath);
+ if (current === 'non-empty-file' && !opts.preserveLateNativeAsArtifact) {
+ return { kind: 'native-winner' };
+ }
+ const unchangedEmpty = current === 'empty-file'
+ && emptyRolloutStillMatches(canonicalPath, originalEmpty);
+ const sameInodeLateNative = current === 'non-empty-file'
+ && opts.preserveLateNativeAsArtifact
+ && regularFileIdentityMatchesSnapshot(canonicalPath, originalEmpty);
+ if (!unchangedEmpty && !sameInodeLateNative) {
+ throw resumePreparationBlocked(threadId, 'the stable empty canonical changed before preservation');
+ }
+
+ for (let attempt = 0; attempt < MAX_RECOVERY_PATH_ATTEMPTS; attempt += 1) {
+ const preservedPath = recoveredSiblingRolloutPath(
+ canonicalPath,
+ threadId,
+ attempt,
+ opts.preserveLateNativeAsArtifact ? 'retired-empty' : 'preserved-empty',
+ );
+ try {
+ fs.linkSync(canonicalPath, preservedPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
+ // A prior publication failure or process exit can leave both names linked
+ // to the same empty inode. Reuse that recoverable checkpoint instead of
+ // turning it into a permanent blocker.
+ if (!sameRegularFileIdentity(canonicalPath, preservedPath)) continue;
+ }
+
+ if (
+ !sameRegularFileIdentity(canonicalPath, preservedPath)
+ || readPrivateRolloutPathState(targetHome, preservedPath) === 'unsafe'
+ ) {
+ throw resumePreparationBlocked(threadId, 'the preserved empty rollout crossed its safe boundary');
+ }
+ const originalAfterLink = readPrivateRolloutPathState(targetHome, canonicalPath);
+ if (originalAfterLink === 'non-empty-file' && !opts.preserveLateNativeAsArtifact) {
+ try {
+ if (sameRegularFileIdentity(canonicalPath, preservedPath)) fs.unlinkSync(preservedPath);
+ } catch {
+ // The duplicate Cindy-only name is harmless; the canonical remains authoritative.
+ }
+ return { kind: 'native-winner' };
+ }
+ if (originalAfterLink !== 'empty-file' && originalAfterLink !== 'non-empty-file') {
+ throw resumePreparationBlocked(threadId, 'the canonical rollout changed during preservation');
+ }
+ try {
+ fs.unlinkSync(canonicalPath);
+ } catch (error) {
+ if (!opts.preserveLateNativeAsArtifact) {
+ try {
+ if (sameRegularFileIdentity(canonicalPath, preservedPath)) fs.unlinkSync(preservedPath);
+ } catch {
+ // Best effort rollback of the duplicate link; never remove the canonical.
+ }
+ }
+ throw resumePreparationBlocked(
+ threadId,
+ `the empty canonical could not be moved aside (${(error as NodeJS.ErrnoException).code ?? 'unknown'})`,
+ );
+ }
+ return { kind: 'preserved', path: preservedPath };
+ }
+ throw resumePreparationBlocked(threadId, 'no safe preservation path was available for the empty rollout');
+}
+
+function restorePreservedCanonical(
+ threadId: string,
+ targetHome: string,
+ preservedPath: string,
+ canonicalPath: string,
+): string {
+ const preserved = readPrivateRolloutPathState(targetHome, preservedPath);
+ if (preserved !== 'empty-file' && preserved !== 'non-empty-file') {
+ throw resumePreparationBlocked(threadId, 'the preserved rollout changed outside its safe boundary');
+ }
+ try {
+ fs.linkSync(preservedPath, canonicalPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
+ if (!sameRegularFileIdentity(preservedPath, canonicalPath)) {
+ throw resumePreparationBlocked(threadId, 'another writer occupied the canonical rollout path');
+ }
+ }
+ const restored = readPrivateRolloutPathState(targetHome, canonicalPath);
+ if (restored !== preserved || !sameRegularFileIdentity(preservedPath, canonicalPath)) {
+ throw resumePreparationBlocked(threadId, 'the preserved rollout could not be restored safely');
+ }
+ return canonicalPath;
+}
+
+/** Accept one native canonical only after every pre-handoff source still matches. */
+function acceptSoleCanonicalNativeWinner(
+ threadId: string,
+ targetHome: string,
+ canonicalPath: string,
+ beforeReturn?: () => void,
+): string {
+ beforeReturn?.();
+ assertSoleCanonicalPath(threadId, targetHome, canonicalPath, true);
+ return canonicalPath;
+}
+
+function assertSoleCanonicalPath(
+ threadId: string,
+ targetHome: string,
+ canonicalPath: string,
+ requireNonEmpty: boolean,
+): void {
+ const current = observeCurrentHomeCanonicalRollouts(targetHome, threadId);
+ const allCanonical = [
+ ...current.empties.map((candidate) => candidate.path),
+ ...current.nonEmpty,
+ ];
+ if (
+ allCanonical.length !== 1
+ || !samePath(allCanonical[0], canonicalPath)
+ || (requireNonEmpty && current.nonEmpty.length !== 1)
+ ) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'the private canonical rollout namespace changed before completing the handoff',
+ );
+ }
+}
+
+/** Restore a preserved native inode only while its canonical name is still unopposed. */
+function restoreSoleCanonicalNativeWinner(
+ threadId: string,
+ targetHome: string,
+ preservedPath: string,
+ canonicalPath: string,
+ beforeReturn?: () => void,
+): string {
+ beforeReturn?.();
+ assertNoUnexpectedCanonicalRollouts(threadId, targetHome, [canonicalPath]);
+ const restored = restorePreservedCanonical(
+ threadId,
+ targetHome,
+ preservedPath,
+ canonicalPath,
+ );
+ // The canonical link is an irreversible handoff: Codex may already have
+ // opened it or hydrated state even when this post-link check fails.
+ return acceptSoleCanonicalNativeWinner(
+ threadId,
+ targetHome,
+ restored,
+ beforeReturn,
+ );
+}
+
+/** Restore an empty/native precursor after a failed publication only if it remains the sole history. */
+function restorePreservedCanonicalAfterFailedHandoff(
+ threadId: string,
+ targetHome: string,
+ preservedPath: string,
+ canonicalPath: string,
+ beforeRestore?: () => void,
+): void {
+ beforeRestore?.();
+ assertNoUnexpectedCanonicalRollouts(threadId, targetHome, [canonicalPath]);
+ if (readPrivateRolloutPathState(targetHome, canonicalPath) !== 'missing') return;
+ restorePreservedCanonical(threadId, targetHome, preservedPath, canonicalPath);
+ beforeRestore?.();
+ assertSoleCanonicalPath(threadId, targetHome, canonicalPath, false);
+ if (sameRegularFileIdentity(preservedPath, canonicalPath)) {
+ fs.unlinkSync(preservedPath);
+ }
+}
+
+/**
+ * Recover a stable canonical empty when the Codex state row is gone. The empty
+ * inode is retained under a Cindy-only name and exactly one canonical filename
+ * is exposed, so Codex's unordered first-match UUID scan cannot pick the empty.
+ */
+async function recoverStableCanonicalEmptyWithoutTargetState(
+ threadId: string,
+ targetHome: string,
+ canonicalPath: string,
+ originalEmpty: EmptyRolloutSnapshot,
+ beforeHandoff?: () => void,
+): Promise<string | null> {
+ if (!isStableEmptyRollout(originalEmpty)) {
+ throw resumePreparationBlocked(threadId, 'private rollout may still be materializing');
+ }
+ if (
+ !isCanonicalCodexRolloutPath(canonicalPath, threadId)
+ || readPrivateRolloutPathState(targetHome, canonicalPath) !== 'empty-file'
+ ) {
+ throw resumePreparationBlocked(threadId, 'the empty rollout is not a regular private canonical file');
+ }
+
+ const staged = await publishFreshLocalSyntheticBeforeHandoff(canonicalPath, threadId);
+ if (!staged) return null;
+ const preservation = preserveStableEmptyCanonical(
+ threadId,
+ targetHome,
+ canonicalPath,
+ originalEmpty,
+ );
+ if (preservation.kind === 'native-winner') {
+ return acceptSoleCanonicalNativeWinner(
+ threadId,
+ targetHome,
+ canonicalPath,
+ beforeHandoff,
+ );
+ }
+
+ const preservedBeforePublication = readPrivateRolloutPathState(targetHome, preservation.path);
+ if (preservedBeforePublication === 'non-empty-file') {
+ return restoreSoleCanonicalNativeWinner(
+ threadId,
+ targetHome,
+ preservation.path,
+ canonicalPath,
+ beforeHandoff,
+ );
+ }
+ if (preservedBeforePublication !== 'empty-file') {
+ throw resumePreparationBlocked(threadId, 'the preserved empty rollout changed before handoff');
+ }
+
+ let published: CanonicalSyntheticPublication;
+ try {
+ published = publishStagedSyntheticAtCanonical(
+ threadId,
+ targetHome,
+ staged,
+ canonicalPath,
+ () => {
+ beforeHandoff?.();
+ assertNoUnexpectedCanonicalRollouts(threadId, targetHome, [canonicalPath]);
+ return readPrivateRolloutPathState(targetHome, preservation.path) === 'empty-file';
+ },
+ );
+ } catch (error) {
+ if (readPrivateRolloutPathState(targetHome, canonicalPath) === 'missing') {
+ try {
+ restorePreservedCanonicalAfterFailedHandoff(
+ threadId,
+ targetHome,
+ preservation.path,
+ canonicalPath,
+ beforeHandoff,
+ );
+ } catch {
+ // Preserve the original exception; both files remain inside Cindy storage.
+ }
+ }
+ throw error;
+ }
+ if (!published.synthetic) return published.path;
+
+ // link(canonical) is the no-state commit point: Codex's scanner may open it
+ // immediately. A retained writer waking afterward stays preserved under the
+ // Cindy-only name and must never pull canonical away from that live inode.
+ if (readPrivateRolloutPathState(targetHome, preservation.path) === 'non-empty-file') {
+ log.warn('late native rollout was preserved after canonical recovery handoff', {
+ threadId,
+ preservedRolloutPath: preservation.path,
+ recoveredRolloutPath: canonicalPath,
+ });
+ }
+
+ log.info('recovered stable canonical empty Codex rollout without target state', {
+ threadId,
+ originalRolloutPath: canonicalPath,
+ preservedRolloutPath: preservation.path,
+ recoveredRolloutPath: published.path,
+ messageCount: staged.messageCount,
+ created: published.created,
+ });
+ return published.path;
+}
+
+interface CanonicalFullRolloutPublication {
+ path: string;
+ created: boolean;
+ staged: boolean;
+}
+
+function publishStagedFullRolloutAtCanonical(
+ threadId: string,
+ targetHome: string,
+ staged: PrivateRolloutPublication,
+ canonicalPath: string,
+ expectedCanonicalStillAvailable?: () => boolean,
+): CanonicalFullRolloutPublication {
+ if (
+ !isCanonicalCodexRolloutPath(canonicalPath, threadId)
+ || !isPathInside(targetHome, canonicalPath)
+ ) {
+ throw resumePreparationBlocked(threadId, 'the external adoption target is outside private storage');
+ }
+ if (!privateRolloutPublicationStillMatches(targetHome, staged)) {
+ throw resumePreparationBlocked(threadId, 'the staged external rollout changed outside private storage');
+ }
+ if (expectedCanonicalStillAvailable && !expectedCanonicalStillAvailable()) {
+ throw resumePreparationBlocked(threadId, 'the preserved rollout materialized before external handoff');
+ }
+ try {
+ fs.linkSync(staged.path, canonicalPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
+ const winner = readPrivateRolloutPathState(targetHome, canonicalPath);
+ if (
+ winner === 'non-empty-file'
+ && privateRolloutPublicationOwnsPath(targetHome, staged, canonicalPath)
+ ) {
+ assertSoleCanonicalPath(threadId, targetHome, canonicalPath, true);
+ return { path: canonicalPath, created: false, staged: true };
+ }
+ if (winner === 'non-empty-file') {
+ assertSoleCanonicalPath(threadId, targetHome, canonicalPath, true);
+ return { path: canonicalPath, created: false, staged: false };
+ }
+ if (winner === 'empty-file') {
+ throw resumePreparationBlocked(threadId, 'a same-thread rollout began materializing during adoption');
+ }
+ throw resumePreparationBlocked(threadId, 'the external adoption target changed outside its safe boundary');
+ }
+ if (privateRolloutPublicationOwnsPath(targetHome, staged, canonicalPath)) {
+ assertSoleCanonicalPath(threadId, targetHome, canonicalPath, true);
+ return { path: canonicalPath, created: true, staged: true };
+ }
+
+ // We created this canonical name, but link() may have opened a swapped
+ // staging inode after the captured publication was validated. Remove only
+ // that just-linked current staging inode; never unlink an unrelated winner.
+ if (
+ readPrivateRolloutPathState(targetHome, staged.path) === 'non-empty-file'
+ && readPrivateRolloutPathState(targetHome, canonicalPath) === 'non-empty-file'
+ && sameRegularFileIdentity(staged.path, canonicalPath)
+ ) {
+ fs.unlinkSync(canonicalPath);
+ }
+ throw resumePreparationBlocked(threadId, 'the external rollout publication changed before handoff');
+}
+
+/**
+ * A rollout-only external source has no state row that can point at a sibling.
+ * Preserve a stable private empty, then atomically expose the verified external
+ * snapshot under its sole canonical name. A local native writer still wins up
+ * to that handoff; later external writes remain isolated in the source HOME.
+ */
+async function adoptExternalRolloutOverStableCanonicalWithoutState(
+ threadId: string,
+ targetHome: string,
+ sourcePath: string,
+ canonicalPath: string,
+ originalEmpty: EmptyRolloutSnapshot,
+ beforeHandoff?: () => void,
+): Promise<string> {
+ if (!isStableEmptyRollout(originalEmpty)) {
+ throw resumePreparationBlocked(threadId, 'private rollout may still be materializing');
+ }
+ const staged = await copyExternalRolloutAtomically(
+ sourcePath,
+ canonicalPath,
+ threadId,
+ { allowSibling: true, skipPreferred: true },
+ );
+ if (!staged) {
+ throw resumePreparationBlocked(threadId, 'external rollout changed during private adoption');
+ }
+ const preservation = preserveStableEmptyCanonical(
+ threadId,
+ targetHome,
+ canonicalPath,
+ originalEmpty,
+ );
+ if (preservation.kind === 'native-winner') {
+ return acceptSoleCanonicalNativeWinner(
+ threadId,
+ targetHome,
+ canonicalPath,
+ beforeHandoff,
+ );
+ }
+ const preservedBeforePublication = readPrivateRolloutPathState(targetHome, preservation.path);
+ if (preservedBeforePublication === 'non-empty-file') {
+ return restoreSoleCanonicalNativeWinner(
+ threadId,
+ targetHome,
+ preservation.path,
+ canonicalPath,
+ beforeHandoff,
+ );
+ }
+ if (preservedBeforePublication !== 'empty-file') {
+ throw resumePreparationBlocked(threadId, 'the preserved empty rollout changed before adoption');
+ }
+
+ let published: CanonicalFullRolloutPublication;
+ try {
+ published = publishStagedFullRolloutAtCanonical(
+ threadId,
+ targetHome,
+ staged,
+ canonicalPath,
+ () => {
+ beforeHandoff?.();
+ assertNoUnexpectedCanonicalRollouts(threadId, targetHome, [canonicalPath]);
+ return readPrivateRolloutPathState(targetHome, preservation.path) === 'empty-file';
+ },
+ );
+ } catch (error) {
+ if (readPrivateRolloutPathState(targetHome, canonicalPath) === 'missing') {
+ try {
+ restorePreservedCanonicalAfterFailedHandoff(
+ threadId,
+ targetHome,
+ preservation.path,
+ canonicalPath,
+ beforeHandoff,
+ );
+ } catch {
+ // Preserve the original error and every recoverable private artifact.
+ }
+ }
+ throw error;
+ }
+ if (!published.staged) return published.path;
+
+ if (readPrivateRolloutPathState(targetHome, preservation.path) === 'non-empty-file') {
+ log.warn('late native rollout was preserved after external canonical handoff', {
+ threadId,
+ preservedRolloutPath: preservation.path,
+ recoveredRolloutPath: canonicalPath,
+ });
+ }
+
+ log.info('adopted rollout-only external history over stable private empty', {
+ threadId,
+ sourceRolloutPath: sourcePath,
+ preservedRolloutPath: preservation.path,
+ recoveredRolloutPath: published.path,
+ created: published.created,
+ });
+ return published.path;
+}
+
+async function adoptExternalRolloutAfterPendingLocalHandoff(
+ threadId: string,
+ targetHome: string,
+ sourcePath: string,
+ canonicalPath: string,
+ beforeHandoff: () => void,
+): Promise<string> {
+ const staged = await copyExternalRolloutAtomically(
+ sourcePath,
+ canonicalPath,
+ threadId,
+ { allowSibling: true, skipPreferred: true },
+ );
+ if (!staged) {
+ throw resumePreparationBlocked(threadId, 'external rollout changed during guarded adoption');
+ }
+ const published = publishStagedFullRolloutAtCanonical(
+ threadId,
+ targetHome,
+ staged,
+ canonicalPath,
+ () => {
+ beforeHandoff();
+ assertNoUnexpectedCanonicalRollouts(threadId, targetHome, [canonicalPath]);
+ return true;
+ },
+ );
+ log.info('adopted rollout-only external history after pending local handoff', {
+ threadId,
+ sourceRolloutPath: sourcePath,
+ recoveredRolloutPath: published.path,
+ created: published.created,
+ });
+ return published.path;
+}
+
+/**
+ * 双缺失恢复:在标准目录发布 rollout,让 app-server thread/resume 重新生成当前版本的
+ * state 行。H1/H2 只发布到 Cindy staging sibling;历史稳定后才原子暴露唯一的
+ * canonical 文件。返回是无 state 场景的不可逆 handoff,此后不再跨调用替换它。
+ */
+async function synthesizeRolloutForMissingThreadState(
+ threadId: string,
+ targetHome: string,
+ beforeHandoff?: () => void,
+): Promise<string | null> {
+ const source = await readBestLocalCodexRecoverySource(threadId);
+ if (!source) return null;
+ const rolloutPath = recoveredRolloutPath(targetHome, threadId, source.recoveryCreatedAt);
+ const staged = await publishFreshLocalSyntheticBeforeHandoff(rolloutPath, threadId);
+ if (!staged) return null;
+ const published = publishStagedSyntheticAtCanonical(
+ threadId,
+ targetHome,
+ staged,
+ rolloutPath,
+ () => {
+ beforeHandoff?.();
+ assertNoUnexpectedCanonicalRollouts(threadId, targetHome, [rolloutPath]);
+ return true;
+ },
+ );
+ log.info('synthesized rollout for missing Codex thread state', {
+ threadId,
+ rolloutPath: published.path,
+ messageCount: staged.messageCount,
+ created: published.created,
+ });
+ return published.path;
+}
+
+function syntheticRowForLocalRecoverySource(source: LocalCodexRecoverySource): SqlRow {
+ return {
+ created_at_ms: source.recoveryCreatedAt,
+ cwd: source.session.workingDir,
+ originator: 'xdt-maker',
+ source: 'cli',
+ model: source.session.model,
+ };
+}
+
+/**
+ * 同一 Codex thread 可能被复制或 rewind 成多条 Cindy 会话。恢复时逐条读取可见历史,
+ * 优先选择消息最完整的一条;其余字段只负责确定性打破平局,不合并可能分叉的历史。
+ */
+async function readBestLocalCodexRecoverySource(threadId: string): Promise<LocalCodexRecoverySource | null> {
+ const sessions = await getDbClient().query<LocalCodexRecoverySession>(`
+ SELECT
+ id,
+ working_dir AS workingDir,
+ model,
+ created_at AS createdAt,
+ updated_at AS updatedAt
+ FROM sessions
+ WHERE agent_kind = 'codex' AND sdk_session_id = ? AND status <> 'deleted'
+ `, [threadId]);
+
+ let best: LocalCodexRecoverySource | null = null;
+ for (const session of sessions) {
+ const messages = await readXdtMessagesBySessionId(session.id);
+ if (messages.length === 0) continue;
+ const sessionCreatedAt = numberValue(session.createdAt);
+ const firstPositiveMessageAt = messages.find((message) => message.createdAt > 0)?.createdAt ?? 0;
+ const candidate: LocalCodexRecoverySource = {
+ session,
+ messages,
+ recoveryCreatedAt: sessionCreatedAt > 0 ? sessionCreatedAt : firstPositiveMessageAt,
+ };
+ if (!best || isPreferredRecoverySource(candidate, best)) best = candidate;
+ }
+ return best;
+}
+
+function isPreferredRecoverySource(
+ candidate: LocalCodexRecoverySource,
+ current: LocalCodexRecoverySource,
+): boolean {
+ if (candidate.messages.length !== current.messages.length) {
+ return candidate.messages.length > current.messages.length;
+ }
+ const candidateUpdatedAt = numberValue(candidate.session.updatedAt);
+ const currentUpdatedAt = numberValue(current.session.updatedAt);
+ if (candidateUpdatedAt !== currentUpdatedAt) return candidateUpdatedAt > currentUpdatedAt;
+
+ const candidateCreatedAt = numberValue(candidate.session.createdAt);
+ const currentCreatedAt = numberValue(current.session.createdAt);
+ if (candidateCreatedAt !== currentCreatedAt) return candidateCreatedAt > currentCreatedAt;
return candidate.session.id < current.session.id;
}
-function recoveredRolloutPath(targetHome: string, threadId: string, createdAt: number): string {
- const created = new Date(Number.isFinite(createdAt) && createdAt > 0 ? createdAt : 0);
- const year = String(created.getUTCFullYear()).padStart(4, '0');
- const month = String(created.getUTCMonth() + 1).padStart(2, '0');
- const day = String(created.getUTCDate()).padStart(2, '0');
- const timestamp = created.toISOString().slice(0, 19).replaceAll(':', '-');
- return path.join(
- targetHome,
- 'sessions',
- year,
- month,
- day,
- `rollout-${timestamp}-${threadId}.jsonl`,
- );
+function recoveredRolloutPath(targetHome: string, threadId: string, createdAt: number): string {
+ const created = new Date(Number.isFinite(createdAt) && createdAt > 0 ? createdAt : 0);
+ const year = String(created.getUTCFullYear()).padStart(4, '0');
+ const month = String(created.getUTCMonth() + 1).padStart(2, '0');
+ const day = String(created.getUTCDate()).padStart(2, '0');
+ const timestamp = created.toISOString().slice(0, 19).replaceAll(':', '-');
+ return path.join(
+ targetHome,
+ 'sessions',
+ year,
+ month,
+ day,
+ `rollout-${timestamp}-${threadId}.jsonl`,
+ );
+}
+
+/** Stable siblings used when an unreadable private rollout must be preserved. */
+function recoveredSiblingRolloutPath(
+ unreadablePath: string,
+ threadId: string,
+ attempt: number,
+ kind: 'adopted' | 'empty-recovery' | 'preserved-empty' | 'retired-empty' | 'state-less-stage' | 'synthetic',
+): string {
+ const suffix = attempt === 0 ? '' : `-${attempt + 1}`;
+ const originalName = path.basename(unreadablePath) || `rollout-${threadId}.jsonl`;
+ if (kind === 'state-less-stage') {
+ return path.join(
+ path.dirname(unreadablePath),
+ `.cindy-state-less-recovery${suffix}-${originalName}.stage`,
+ );
+ }
+ return path.join(
+ path.dirname(unreadablePath),
+ `rollout-cindy-${kind}${suffix}-${originalName}`,
+ );
+}
+
+type PublishedSyntheticRollout = PrivateRolloutPublication;
+
+interface FreshSyntheticPublication extends PublishedSyntheticRollout {
+ contents: string;
+ messageCount: number;
+}
+
+/**
+ * Publish a synthetic candidate while the old state pointer still owns the
+ * session, then verify it against one final localDb snapshot before handoff.
+ * If H1 advances to H2 during publication, preserve H1 and retry with H2.
+ */
+async function publishFreshSyntheticBeforeHandoff(
+ preferredPath: string,
+ threadId: string,
+ row: SqlRow,
+ opts: { skipPreferred: boolean },
+): Promise<FreshSyntheticPublication | null> {
+ for (let attempt = 0; attempt < MAX_RECOVERY_PATH_ATTEMPTS; attempt += 1) {
+ const messages = await readXdtMessagesByThreadId(threadId);
+ if (messages.length === 0) return null;
+ const contents = buildSyntheticRollout(threadId, row, messages);
+ const published = await publishSyntheticRollout(
+ preferredPath,
+ threadId,
+ contents,
+ opts,
+ );
+ if (!published) return null;
+
+ const latestMessages = await readXdtMessagesByThreadId(threadId);
+ if (latestMessages.length === 0) return null;
+ const latestContents = buildSyntheticRollout(threadId, row, latestMessages);
+ const latestSnapshot = readPrivateExactRolloutSnapshot(
+ getDesktopCodexHome(),
+ published.path,
+ latestContents,
+ );
+ if (latestSnapshot) {
+ return {
+ ...published,
+ snapshot: latestSnapshot,
+ contents: latestContents,
+ messageCount: latestMessages.length,
+ };
+ }
+ }
+ return null;
+}
+
+/** Atomically publish into the first usable deterministic private candidate. */
+async function publishSyntheticRollout(
+ preferredPath: string,
+ threadId: string,
+ contents: string,
+ opts: { skipPreferred: boolean; siblingKind?: 'empty-recovery' | 'state-less-stage' },
+): Promise<PublishedSyntheticRollout | null> {
+ const targetHome = getDesktopCodexHome();
+ if (!isPathInside(targetHome, preferredPath)) return null;
+
+ for (let attempt = 0; attempt < MAX_RECOVERY_PATH_ATTEMPTS; attempt += 1) {
+ const candidate = !opts.skipPreferred && attempt === 0
+ ? preferredPath
+ : recoveredSiblingRolloutPath(
+ preferredPath,
+ threadId,
+ opts.skipPreferred ? attempt : attempt - 1,
+ opts.skipPreferred ? (opts.siblingKind ?? 'empty-recovery') : 'synthetic',
+ );
+ // Resolve the boundary before every read or write. In particular, a
+ // symlinked sessions ancestor must not redirect recovery into another HOME.
+ if (!isPathInside(targetHome, candidate)) return null;
+ const candidateState = readPrivateRolloutPathState(targetHome, candidate);
+ if (candidateState === 'unsafe') return null;
+ if (candidateState === 'non-empty-file') {
+ // A prior crash may have published H1 before localDb advanced to H2. Reuse
+ // only the exact current synthetic history; otherwise preserve H1 and move on.
+ const snapshot = readPrivateExactRolloutSnapshot(targetHome, candidate, contents);
+ if (snapshot) {
+ return { path: candidate, created: false, snapshot };
+ }
+ continue;
+ }
+
+ if (candidateState === 'empty-file') {
+ const empty = readEmptyRolloutSnapshot(candidate);
+ if (!empty || !isStableEmptyRollout(empty)) return null;
+ continue;
+ }
+
+ const created = await writeFileAtomicallyIfAbsent(targetHome, candidate, contents);
+ const snapshot = readPrivateExactRolloutSnapshot(targetHome, candidate, contents);
+ if (snapshot) return { path: candidate, created, snapshot };
+ if (readPrivateRolloutPathState(targetHome, candidate) === 'unsafe') return null;
+ const racedEmpty = readEmptyRolloutSnapshot(candidate);
+ if (!racedEmpty || !isStableEmptyRollout(racedEmpty)) return null;
+ }
+ return null;
}
/** 同目录临时文件 + hard-link 发布:不覆盖既有 rollout,并避免并发 resume 读到半截文件。 */
-async function writeFileAtomicallyIfAbsent(targetPath: string, contents: string): Promise<boolean> {
+async function writeFileAtomicallyIfAbsent(
+ targetHome: string,
+ targetPath: string,
+ contents: string,
+): Promise<boolean> {
+ if (!isPathInside(targetHome, targetPath)) return false;
if (fs.existsSync(targetPath)) return false;
await fsp.mkdir(path.dirname(targetPath), { recursive: true });
const tempPath = path.join(
path.dirname(targetPath),
`.${path.basename(targetPath)}.${randomUUID()}.recovery-tmp`,
);
+ if (
+ !isPathInside(targetHome, targetPath)
+ || !isPathInside(targetHome, tempPath)
+ ) return false;
try {
await fsp.writeFile(tempPath, contents, { encoding: 'utf-8', flag: 'wx' });
+ if (
+ readPrivateRolloutPathState(targetHome, tempPath) !== 'non-empty-file'
+ || !isPathInside(targetHome, targetPath)
+ ) return false;
try {
await fsp.link(tempPath, targetPath);
return true;
@@ -825,7 +3351,9 @@ async function writeFileAtomicallyIfAbsent(targetPath: string, contents: string)
throw err;
}
} finally {
- await fsp.rm(tempPath, { force: true }).catch(() => undefined);
+ if (isPathInside(targetHome, tempPath)) {
+ await fsp.unlink(tempPath).catch(() => undefined);
+ }
}
}
@@ -1259,6 +3787,11 @@ async function appendSessionIndexEntry(home: string, thread: CodexThreadSummary)
}
}
+function isCindyRolloutArtifactFileName(name: string): boolean {
+ return name.startsWith('rollout-cindy-')
+ || name.startsWith('.cindy-state-less-recovery');
+}
+
function collectRolloutFiles(home: string): string[] {
const roots = [path.join(home, 'sessions'), path.join(home, 'archived_sessions')];
const files: Array<{ file: string; mtime: number }> = [];
@@ -1274,7 +3807,12 @@ function collectRolloutFiles(home: string): string[] {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
visit(full, depth + 1);
- } else if (entry.isFile() && entry.name.endsWith('.jsonl') && entry.name.includes('rollout-')) {
+ } else if (
+ entry.isFile()
+ && entry.name.endsWith('.jsonl')
+ && entry.name.includes('rollout-')
+ && !isCindyRolloutArtifactFileName(entry.name)
+ ) {
try {
files.push({ file: full, mtime: fs.statSync(full).mtimeMs });
} catch {
@@ -1304,7 +3842,12 @@ async function collectRolloutFilesAsync(home: string): Promise<Array<{ file: str
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
await visit(full, depth + 1);
- } else if (entry.isFile() && entry.name.endsWith('.jsonl') && entry.name.includes('rollout-')) {
+ } else if (
+ entry.isFile()
+ && entry.name.endsWith('.jsonl')
+ && entry.name.includes('rollout-')
+ && !isCindyRolloutArtifactFileName(entry.name)
+ ) {
try {
files.push({ file: full, mtime: (await fsp.stat(full)).mtimeMs });
} catch {
@@ -1435,6 +3978,430 @@ function threadIdFromRolloutPath(file: string): string {
return m?.[1] ?? '';
}
+/** Match the filename contract used by Codex's state-less rollout scanner. */
+function isCanonicalCodexRolloutPath(file: string, threadId: string): boolean {
+ return threadIdFromRolloutPath(file) === threadId
+ && /^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-[0-9a-fA-F-]{36}\.jsonl$/
+ .test(path.basename(file));
+}
+
+interface InterruptedEmptyPreservation {
+ preservedPath: string;
+ canonicalPath: string;
+}
+
+function collectInterruptedEmptyPreservations(
+ home: string,
+ threadId: string,
+): InterruptedEmptyPreservation[] {
+ const roots = [path.join(home, 'sessions'), path.join(home, 'archived_sessions')];
+ const found: InterruptedEmptyPreservation[] = [];
+ const visit = (dir: string, depth: number): void => {
+ if (depth > 6) return;
+ let entries: fs.Dirent[];
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const candidate = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ visit(candidate, depth + 1);
+ continue;
+ }
+ const match = entry.name.match(
+ /^rollout-cindy-preserved-empty(?:-\d+)?-(rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-[0-9a-fA-F-]{36}\.jsonl)$/,
+ );
+ if (!match) continue;
+ const canonicalPath = path.join(dir, match[1]);
+ if (!isCanonicalCodexRolloutPath(canonicalPath, threadId)) continue;
+ found.push({ preservedPath: candidate, canonicalPath });
+ }
+ };
+ for (const root of roots) visit(root, 0);
+ return found;
+}
+
+function observePendingInterruptedEmptyPreservations(
+ targetHome: string,
+ threadId: string,
+): (() => void) | undefined {
+ const pending: Array<{ path: string; snapshot: EmptyRolloutSnapshot }> = [];
+ for (const preservation of collectInterruptedEmptyPreservations(targetHome, threadId)) {
+ if (readPrivateRolloutPathState(targetHome, preservation.canonicalPath) !== 'missing') {
+ continue;
+ }
+ const snapshot = readRegularEmptyRolloutSnapshot(preservation.preservedPath);
+ if (!snapshot) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'an interrupted preserved rollout changed before recovery planning',
+ );
+ }
+ pending.push({ path: preservation.preservedPath, snapshot });
+ }
+ if (pending.length === 0) return undefined;
+ return () => {
+ for (const candidate of pending) {
+ if (!regularEmptyRolloutStillMatches(candidate.path, candidate.snapshot)) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'an interrupted preserved rollout changed before canonical handoff',
+ );
+ }
+ }
+ };
+}
+
+function collectInterruptedCanonicalRetirements(
+ home: string,
+ threadId: string,
+): InterruptedEmptyPreservation[] {
+ const roots = [path.join(home, 'sessions'), path.join(home, 'archived_sessions')];
+ const found: InterruptedEmptyPreservation[] = [];
+ const visit = (dir: string, depth: number): void => {
+ if (depth > 6) return;
+ let entries: fs.Dirent[];
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const candidate = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ visit(candidate, depth + 1);
+ continue;
+ }
+ const match = entry.name.match(
+ /^rollout-cindy-retired-empty(?:-\d+)?-(rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-[0-9a-fA-F-]{36}\.jsonl)$/,
+ );
+ if (!match) continue;
+ const canonicalPath = path.join(dir, match[1]);
+ if (!isCanonicalCodexRolloutPath(canonicalPath, threadId)) continue;
+ found.push({ preservedPath: candidate, canonicalPath });
+ }
+ };
+ for (const root of roots) visit(root, 0);
+ return found;
+}
+
+function reconcileInterruptedCanonicalRetirements(
+ targetHome: string,
+ threadId: string,
+ canonicalSet: { empties: CanonicalEmptyObservation[]; nonEmpty: string[] },
+): { empties: CanonicalEmptyObservation[]; nonEmpty: string[] } {
+ if (canonicalSet.nonEmpty.length <= 1) return canonicalSet;
+ const retirements = collectInterruptedCanonicalRetirements(targetHome, threadId);
+ const checkpointByCanonical = new Map<string, string>();
+ for (const canonicalPath of canonicalSet.nonEmpty) {
+ const checkpoint = retirements.find((candidate) => (
+ samePath(candidate.canonicalPath, canonicalPath)
+ && readPrivateRolloutPathState(targetHome, candidate.preservedPath) === 'non-empty-file'
+ && sameRegularFileIdentity(candidate.preservedPath, canonicalPath)
+ ));
+ if (checkpoint) checkpointByCanonical.set(canonicalPath, checkpoint.preservedPath);
+ }
+ const establishedWinners = canonicalSet.nonEmpty.filter(
+ (canonicalPath) => !checkpointByCanonical.has(canonicalPath),
+ );
+ if (establishedWinners.length !== 1) return canonicalSet;
+ const establishedWinner = establishedWinners[0];
+
+ for (const [canonicalPath, checkpointPath] of checkpointByCanonical) {
+ if (
+ readPrivateRolloutPathState(targetHome, canonicalPath) !== 'non-empty-file'
+ || readPrivateRolloutPathState(targetHome, checkpointPath) !== 'non-empty-file'
+ || !sameRegularFileIdentity(canonicalPath, checkpointPath)
+ ) {
+ throw resumePreparationBlocked(threadId, 'an interrupted canonical retirement changed');
+ }
+ try {
+ fs.unlinkSync(canonicalPath);
+ } catch (error) {
+ throw resumePreparationBlocked(
+ threadId,
+ `an interrupted canonical could not be retired (${(error as NodeJS.ErrnoException).code ?? 'unknown'})`,
+ );
+ }
+ }
+
+ const converged = observeCurrentHomeCanonicalRollouts(targetHome, threadId);
+ if (
+ converged.nonEmpty.length !== 1
+ || !samePath(converged.nonEmpty[0], establishedWinner)
+ ) {
+ throw resumePreparationBlocked(threadId, 'interrupted canonical retirement did not converge');
+ }
+ log.info('completed interrupted canonical rollout retirement', {
+ threadId,
+ retainedRolloutPath: establishedWinner,
+ retiredRolloutPaths: [...checkpointByCanonical.keys()],
+ });
+ return converged;
+}
+
+/**
+ * A process exit can happen after the empty canonical name is moved aside but
+ * before a synthetic handoff. If the retained native writer then appends to
+ * that preserved inode, restore it as the authoritative canonical history.
+ */
+function restoreInterruptedNativeCanonicalWithoutState(
+ targetHome: string,
+ threadId: string,
+ opts: { requireAllNativePrecursorsConverged?: boolean } = {},
+): string | null {
+ let canonicalSet = observeCurrentHomeCanonicalRollouts(targetHome, threadId);
+ canonicalSet = reconcileInterruptedCanonicalRetirements(targetHome, threadId, canonicalSet);
+ if (canonicalSet.empties.some((candidate) => !isStableEmptyRollout(candidate.snapshot))) {
+ throw resumePreparationBlocked(threadId, 'private rollout may still be materializing');
+ }
+ if (canonicalSet.nonEmpty.length > 1) {
+ throw resumePreparationBlocked(threadId, 'multiple private canonical rollouts conflict');
+ }
+ if (canonicalSet.nonEmpty.length === 1) {
+ const existingWinner = canonicalSet.nonEmpty[0];
+ if (opts.requireAllNativePrecursorsConverged) {
+ for (const preservation of collectInterruptedEmptyPreservations(targetHome, threadId)) {
+ if (readPrivateRolloutPathState(targetHome, preservation.preservedPath) !== 'non-empty-file') {
+ continue;
+ }
+ if (
+ !samePath(preservation.canonicalPath, existingWinner)
+ || !sameRegularFileIdentity(preservation.preservedPath, existingWinner)
+ ) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'multiple native private rollouts conflict before state handoff',
+ );
+ }
+ }
+ }
+ preserveStableCanonicalEmptiesBesideWinner(
+ threadId,
+ targetHome,
+ canonicalSet.empties,
+ );
+ const converged = observeCurrentHomeCanonicalRollouts(targetHome, threadId);
+ if (
+ converged.empties.length > 0
+ || converged.nonEmpty.length !== 1
+ || !samePath(converged.nonEmpty[0], existingWinner)
+ ) {
+ throw resumePreparationBlocked(threadId, 'the private canonical winner changed during handoff');
+ }
+ return existingWinner;
+ }
+
+ let nativeWinner: InterruptedEmptyPreservation | null = null;
+ for (const preservation of collectInterruptedEmptyPreservations(targetHome, threadId)) {
+ const canonicalState = readPrivateRolloutPathState(targetHome, preservation.canonicalPath);
+ if (canonicalState === 'non-empty-file') continue;
+ const preservedState = readPrivateRolloutPathState(targetHome, preservation.preservedPath);
+ if (preservedState === 'empty-file') continue;
+ if (preservedState !== 'non-empty-file') {
+ throw resumePreparationBlocked(threadId, 'an interrupted preserved rollout became unsafe');
+ }
+ if (canonicalState !== 'missing') {
+ throw resumePreparationBlocked(
+ threadId,
+ 'an interrupted native rollout conflicts with the canonical path',
+ );
+ }
+ if (nativeWinner) {
+ if (
+ !samePath(nativeWinner.canonicalPath, preservation.canonicalPath)
+ || !sameRegularFileIdentity(nativeWinner.preservedPath, preservation.preservedPath)
+ ) {
+ throw resumePreparationBlocked(threadId, 'multiple interrupted native rollouts conflict');
+ }
+ continue;
+ }
+ nativeWinner = preservation;
+ }
+ if (!nativeWinner) return null;
+ preserveStableCanonicalEmptiesBesideWinner(
+ threadId,
+ targetHome,
+ canonicalSet.empties,
+ );
+ const restored = restorePreservedCanonical(
+ threadId,
+ targetHome,
+ nativeWinner.preservedPath,
+ nativeWinner.canonicalPath,
+ );
+ const restoredSet = observeCurrentHomeCanonicalRollouts(targetHome, threadId);
+ if (
+ restoredSet.empties.length > 0
+ || restoredSet.nonEmpty.length !== 1
+ || !samePath(restoredSet.nonEmpty[0], restored)
+ ) {
+ throw resumePreparationBlocked(threadId, 'interrupted native recovery did not converge');
+ }
+ log.info('restored native Codex rollout after interrupted state-less recovery', {
+ threadId,
+ preservedRolloutPath: nativeWinner.preservedPath,
+ restoredRolloutPath: restored,
+ });
+ return restored;
+}
+
+interface CanonicalEmptyObservation {
+ path: string;
+ snapshot: EmptyRolloutSnapshot;
+}
+
+function observeCurrentHomeCanonicalRollouts(
+ targetHome: string,
+ threadId: string,
+): { empties: CanonicalEmptyObservation[]; nonEmpty: string[] } {
+ const empties: CanonicalEmptyObservation[] = [];
+ const nonEmpty: string[] = [];
+ const candidates = collectNamedRolloutPaths(targetHome, threadId)
+ .filter((candidate) => isCanonicalCodexRolloutPath(candidate, threadId))
+ .sort();
+ for (const candidate of candidates) {
+ const state = readPrivateRolloutPathState(targetHome, candidate);
+ if (state === 'non-empty-file') {
+ nonEmpty.push(candidate);
+ continue;
+ }
+ if (state === 'empty-file') {
+ const snapshot = readEmptyRolloutSnapshot(candidate);
+ if (!snapshot) {
+ throw resumePreparationBlocked(threadId, 'a private canonical rollout changed during discovery');
+ }
+ empties.push({ path: candidate, snapshot });
+ continue;
+ }
+ throw resumePreparationBlocked(threadId, 'a private canonical rollout crossed its safe boundary');
+ }
+ return { empties, nonEmpty };
+}
+
+function createCanonicalNamespaceGuard(
+ threadId: string,
+ targetHome: string,
+ retainedEmpties: readonly CanonicalEmptyObservation[],
+): () => void {
+ return () => {
+ const current = observeCurrentHomeCanonicalRollouts(targetHome, threadId);
+ const matchesPlan = current.nonEmpty.length === 0
+ && current.empties.length === retainedEmpties.length
+ && retainedEmpties.every((expected) => current.empties.some((candidate) => (
+ samePath(candidate.path, expected.path)
+ && emptyRolloutStillMatches(candidate.path, expected.snapshot)
+ )));
+ if (!matchesPlan) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'the private canonical rollout namespace changed during recovery handoff',
+ );
+ }
+ };
+}
+
+/** Fail closed if a same-thread canonical name appeared after recovery planning. */
+function assertNoUnexpectedCanonicalRollouts(
+ threadId: string,
+ targetHome: string,
+ allowedPaths: readonly string[],
+): void {
+ const current = observeCurrentHomeCanonicalRollouts(targetHome, threadId);
+ const unexpected = [
+ ...current.empties.map((candidate) => candidate.path),
+ ...current.nonEmpty,
+ ].find((candidate) => !allowedPaths.some((allowed) => samePath(candidate, allowed)));
+ if (unexpected) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'the private canonical rollout namespace changed during recovery handoff',
+ );
+ }
+}
+
+function preserveStableCanonicalEmptiesBesideWinner(
+ threadId: string,
+ targetHome: string,
+ empties: readonly CanonicalEmptyObservation[],
+): void {
+ for (const empty of empties) {
+ const preservation = preserveStableEmptyCanonical(
+ threadId,
+ targetHome,
+ empty.path,
+ empty.snapshot,
+ { preserveLateNativeAsArtifact: true },
+ );
+ if (preservation.kind === 'native-winner') {
+ throw resumePreparationBlocked(
+ threadId,
+ 'a private empty canonical materialized beside another winner',
+ );
+ }
+ }
+}
+
+function preserveAdditionalCanonicalEmptiesBeforeHandoff(
+ threadId: string,
+ targetHome: string,
+ empties: readonly CanonicalEmptyObservation[],
+): (() => void) | undefined {
+ // This batch can come from a second scan after the initial recovery preflight.
+ // Validate every candidate before moving any canonical name so a newly opened
+ // Codex writer keeps its discoverable path and a later recent candidate cannot
+ // leave earlier stable candidates partially preserved.
+ if (empties.some((candidate) => !isStableEmptyRollout(candidate.snapshot))) {
+ throw resumePreparationBlocked(threadId, 'private rollout may still be materializing');
+ }
+ const preserved: Array<{ path: string; snapshot: EmptyRolloutSnapshot }> = [];
+ for (const empty of empties) {
+ const preservation = preserveStableEmptyCanonical(
+ threadId,
+ targetHome,
+ empty.path,
+ empty.snapshot,
+ );
+ if (preservation.kind === 'native-winner') {
+ throw resumePreparationBlocked(
+ threadId,
+ 'an additional private empty canonical materialized before handoff',
+ );
+ }
+ const snapshot = readRegularEmptyRolloutSnapshot(preservation.path);
+ if (!snapshot) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'an additional private empty canonical changed before handoff',
+ );
+ }
+ preserved.push({ path: preservation.path, snapshot });
+ }
+ if (preserved.length === 0) return undefined;
+ return () => {
+ for (const candidate of preserved) {
+ if (!regularEmptyRolloutStillMatches(candidate.path, candidate.snapshot)) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'an additional private rollout changed before canonical handoff',
+ );
+ }
+ }
+ };
+}
+
+function combineHandoffGuards(
+ ...guards: Array<(() => void) | undefined>
+): (() => void) | undefined {
+ const active = guards.filter((guard): guard is () => void => !!guard);
+ if (active.length === 0) return undefined;
+ return () => {
+ for (const guard of active) guard();
+ };
+}
+
function isArchivedRolloutPath(file: string): boolean {
return file.includes(`${path.sep}archived_sessions${path.sep}`);
}
@@ -1457,6 +4424,79 @@ function findExternalThreadById(threadId: string): CodexThreadSummary | null {
return best;
}
+interface ExternalEmptyObservation {
+ path: string;
+ snapshot: EmptyRolloutSnapshot;
+}
+
+/**
+ * Enumerate same-thread rollout names without following file symlinks. This is
+ * intentionally separate from the normal parser scan: a zero-byte rollout has
+ * no session_meta yet, while a replaced symlink/non-file must fail closed.
+ */
+function collectNamedRolloutPaths(home: string, threadId: string): string[] {
+ const roots = [path.join(home, 'sessions'), path.join(home, 'archived_sessions')];
+ const found: string[] = [];
+ const visit = (dir: string, depth: number): void => {
+ if (depth > 6) return;
+ let entries: fs.Dirent[];
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const candidate = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ visit(candidate, depth + 1);
+ } else if (
+ entry.name.endsWith('.jsonl')
+ && entry.name.includes('rollout-')
+ && !isCindyRolloutArtifactFileName(entry.name)
+ && threadIdFromRolloutPath(candidate) === threadId
+ ) {
+ found.push(candidate);
+ }
+ }
+ };
+ for (const root of roots) visit(root, 0);
+ return found;
+}
+
+/** Capture raw external empties that cannot be normalized without session_meta/state. */
+function observeUnindexedExternalEmptyRolloutsById(
+ threadId: string,
+): ExternalEmptyObservation[] {
+ const observations: ExternalEmptyObservation[] = [];
+ for (const home of discoverExternalCodexHomesSync()) {
+ for (const candidate of collectNamedRolloutPaths(home, threadId)) {
+ const snapshot = readRegularEmptyRolloutSnapshot(candidate);
+ if (!snapshot) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'an external rollout changed during recovery discovery',
+ );
+ }
+ observations.push({ path: candidate, snapshot });
+ }
+ }
+ return observations;
+}
+
+function assertExternalEmptyObservationsUnchanged(
+ threadId: string,
+ observations: readonly ExternalEmptyObservation[],
+): void {
+ for (const observation of observations) {
+ if (!regularEmptyRolloutStillMatches(observation.path, observation.snapshot)) {
+ throw resumePreparationBlocked(
+ threadId,
+ 'an external rollout changed before private recovery handoff',
+ );
+ }
+ }
+}
+
function findThreadByIdInHome(home: string, threadId: string): CodexThreadSummary | null {
const dbPath = findLatestStateDb(home);
const projectlessThreadIds = readProjectlessThreadIds(home);
@@ -1696,6 +4736,8 @@ async function upsertLocalSession(thread: CodexThreadSummary): Promise<'inserted
interface CopyThreadStateOptions {
replaceExisting?: boolean;
rolloutPathOverride?: string;
+ validateBeforeCopy?: () => boolean;
+ validateAfterCopy?: () => boolean;
}
function copyThreadStateToTarget(
@@ -1711,11 +4753,16 @@ function copyThreadStateToTarget(
target = createBetterSqliteDatabase(targetDbPath);
target.pragma(`busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS}`);
if (!tableExists(source, 'threads') || !tableExists(target, 'threads')) return false;
- const existing = target.prepare('SELECT id FROM threads WHERE id = ? LIMIT 1').get(thread.threadId);
- if (existing && !opts.replaceExisting) return false;
const sourceDb = source;
const targetDb = target;
const copy = targetDb.transaction(() => {
+ const existing = targetDb
+ .prepare('SELECT id FROM threads WHERE id = ? LIMIT 1')
+ .get(thread.threadId);
+ if (existing && !opts.replaceExisting) return false;
+ if (opts.validateBeforeCopy && !opts.validateBeforeCopy()) {
+ throw new Error('rollout handoff validation failed before state copy');
+ }
if (opts.replaceExisting) {
upsertRowsByColumn(sourceDb, targetDb, 'threads', 'id', thread.threadId, {
...(opts.rolloutPathOverride ? { rollout_path: opts.rolloutPathOverride } : {}),
@@ -1729,10 +4776,14 @@ function copyThreadStateToTarget(
copyRowsByColumn(sourceDb, targetDb, 'thread_dynamic_tools', 'thread_id', thread.threadId);
copyRowsByColumn(sourceDb, targetDb, 'thread_spawn_edges', 'parent_thread_id', thread.threadId);
}
+ if (opts.validateAfterCopy && !opts.validateAfterCopy()) {
+ throw new Error('rollout handoff validation failed after state copy');
+ }
+ return true;
});
- copy();
- return true;
+ return copy.immediate();
} catch (err) {
+ if (err instanceof CodexResumePreparationBlockedError) throw err;
log.warn('failed to copy Codex thread state', {
threadId: thread.threadId,
targetDbPath,
@@ -1825,28 +4876,6 @@ function readThreadRolloutPath(dbPath: string, threadId: string): string | null
}
}
-/** 已有 target row 只改 rollout_path,不拿较旧外部元数据覆盖当前状态。 */
-function pointThreadAtRollout(dbPath: string, threadId: string, rolloutPath: string): boolean {
- let db: Database.Database | null = null;
- try {
- db = createBetterSqliteDatabase(dbPath);
- db.pragma(`busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS}`);
- if (!tableExists(db, 'threads')) return false;
- const result = db.prepare('UPDATE threads SET rollout_path = ? WHERE id = ?')
- .run(rolloutPath, threadId);
- return result.changes > 0;
- } catch (err) {
- log.warn('failed to point Codex thread at adopted rollout', {
- threadId,
- rolloutPath,
- error: err instanceof Error ? err.message : String(err),
- });
- return false;
- } finally {
- closeDbQuietly(db);
- }
-}
-
function resolveRolloutPath(threadId: string): string | null {
const targetDb = findLatestStateDb(getDesktopCodexHome());
if (targetDb) {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index 68060e8d55..e72048bf18 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -1,4 +1,11 @@
-import type { AgentKind, SessionSendOptions, SessionSendResult, UserMessage } from '@cindy/maker-core';
+import {
+ CodexResumePreparationBlockedError,
+ type AgentKind,
+ type SessionSendOptions,
+ type SessionSendResult,
+ type UserMessage,
+} from '@cindy/maker-core';
+import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-input-projection';
import { describe, expect, it, vi } from 'vitest';
import {
createMakerSendTransaction,
@@ -840,6 +847,39 @@ describe('maker SEND transaction', () => {
expect(deps.broadcastSessionCreated).not.toHaveBeenCalled();
});
+ it('projects a stable marker with a safe fallback when lazy-create Codex resume preparation is blocked', async () => {
+ const diagnostic = 'Codex thread private-id is not safe to resume yet';
+ const { deps } = createDeps({
+ getSession: vi.fn(() => undefined),
+ bootstrapSession: vi.fn(async () => {
+ throw new CodexResumePreparationBlockedError(diagnostic);
+ }),
+ });
+ const transaction = createMakerSendTransaction(deps);
+
+ await expect(
+ transaction.sendToAgentAccepted('lazy-session', 'hello', {
+ id: 'lazy-session',
+ agentKind: 'codex',
+ workingDir: 'D:\\lazy',
+ model: 'gpt-5.4',
+ }),
+ ).resolves.toEqual({
+ accepted: false,
+ reason: 'LAZY_CREATE_FAILED',
+ outcome: {
+ kind: 'host-send',
+ accepted: false,
+ code: 'LAZY_CREATE_FAILED',
+ message: CODEX_RESUME_NOT_READY_WIRE_MESSAGE,
+ },
+ });
+ expect(deps.log.warn).toHaveBeenCalledWith(
+ 'send: Codex resume preparation blocked during lazy create',
+ { sessionId: 'lazy-session', error: diagnostic },
+ );
+ });
+
it('maps lazy-create credential busy to CREDENTIAL_SWITCH_BUSY without dispatching', async () => {
const { deps } = createDeps({
getSession: vi.fn(() => undefined),
@@ -938,6 +978,43 @@ describe('maker SEND transaction', () => {
expect(oldSession.send).not.toHaveBeenCalled();
});
+ it('projects a stable marker with a safe fallback when rehydrate Codex resume preparation is blocked', async () => {
+ const diagnostic = 'Codex thread private-id still has a live rollout writer';
+ const oldSession = createSession({ id: 'orca-session', workDir: 'C:\\repo' });
+ const { deps } = createDeps({
+ getSession: vi.fn(() => oldSession),
+ isOrcaMcpHydrated: vi.fn(() => false),
+ synthesizeOrcaVendorOptionsFromDb: vi.fn(async () => true),
+ withRehydrateCloseSuppressed: vi.fn(async () => {
+ throw new CodexResumePreparationBlockedError(diagnostic);
+ }),
+ });
+ const transaction = createMakerSendTransaction(deps);
+
+ await expect(
+ transaction.sendToAgentAccepted('orca-session', 'hello', {
+ id: 'orca-session',
+ agentKind: 'codex',
+ workingDir: 'C:\\repo',
+ model: 'gpt-5.4',
+ }),
+ ).resolves.toEqual({
+ accepted: false,
+ reason: 'REHYDRATE_FAILED',
+ outcome: {
+ kind: 'host-send',
+ accepted: false,
+ code: 'REHYDRATE_FAILED',
+ message: CODEX_RESUME_NOT_READY_WIRE_MESSAGE,
+ },
+ });
+ expect(deps.log.warn).toHaveBeenCalledWith(
+ 'send: Codex resume preparation blocked during rehydrate',
+ { sessionId: 'orca-session', error: diagnostic },
+ );
+ expect(oldSession.send).not.toHaveBeenCalled();
+ });
+
it('maps rehydrate credential busy to CREDENTIAL_SWITCH_BUSY without sending', async () => {
const oldSession = createSession({ id: 'orca-session', workDir: 'C:\\repo' });
const { deps } = createDeps({
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index 155958aae9..9050e07a74 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -1,9 +1,13 @@
-import type {
- AgentKind,
- SessionSendOptions,
- SessionSendResult,
- UserMessage,
+import {
+ CodexResumePreparationBlockedError,
+ type AgentKind,
+ type SessionSendOptions,
+ type SessionSendResult,
+ type UserMessage,
} from '@cindy/maker-core';
+import {
+ CODEX_RESUME_NOT_READY_WIRE_MESSAGE,
+} from '@cindy/maker-shared/agent-input-projection';
import {
createHostSendFailure,
@@ -399,6 +403,18 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
),
};
}
+ if (err instanceof CodexResumePreparationBlockedError) {
+ deps.log.warn('send: Codex resume preparation blocked during rehydrate', {
+ sessionId,
+ error: err.message,
+ });
+ return {
+ kind: 'failure',
+ result: toCompatibleMakerSendResult(
+ createHostSendFailure('REHYDRATE_FAILED', CODEX_RESUME_NOT_READY_WIRE_MESSAGE),
+ ),
+ };
+ }
return {
kind: 'failure',
result: toCompatibleMakerSendResult(
@@ -452,6 +468,18 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
),
};
}
+ if (err instanceof CodexResumePreparationBlockedError) {
+ deps.log.warn('send: Codex resume preparation blocked during lazy create', {
+ sessionId,
+ error: err.message,
+ });
+ return {
+ kind: 'failure',
+ result: toCompatibleMakerSendResult(
+ createHostSendFailure('LAZY_CREATE_FAILED', CODEX_RESUME_NOT_READY_WIRE_MESSAGE),
+ ),
+ };
+ }
return {
kind: 'failure',
result: toCompatibleMakerSendResult(
diff --git a/apps/desktop/src/main/maker-orchestration/fork.ts b/apps/desktop/src/main/maker-orchestration/fork.ts
index b62e0ebb10..4a0a41bdb7 100644
--- a/apps/desktop/src/main/maker-orchestration/fork.ts
+++ b/apps/desktop/src/main/maker-orchestration/fork.ts
@@ -10,6 +10,8 @@
import { eq, and, lt, gt, asc, isNull, or, sql } from 'drizzle-orm';
import { createId } from '@paralleldrive/cuid2';
+import { CodexResumePreparationBlockedError } from '@cindy/maker-core';
+import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-input-projection';
import { getDbClient } from '../localDb/client/current';
import { sessions, messages } from '../localDb/schema';
@@ -43,6 +45,13 @@ function forkError(code: ForkErrorCode, message: string): Error {
return err;
}
+function codexForkFailureDetail(err: unknown): string {
+ if (err instanceof CodexResumePreparationBlockedError) {
+ return CODEX_RESUME_NOT_READY_WIRE_MESSAGE;
+ }
+ return err instanceof Error ? err.message : String(err);
+}
+
function normalizePositiveInt(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value) && value > 0
? Math.floor(value)
@@ -568,7 +577,7 @@ export async function forkSessionAtMessage(
// 错误码 + 文案,只有真 codex 失败才包装。pi 与 cc 一样裸抛原始错误(不会拿到指名道姓
// 错对象的 "Codex 状态不可用" 提示)。改成 usesTailTurnFork 会让 pi 误报成 codex 错误。
if (!isCodex) throw err;
- const detail = err instanceof Error ? err.message : String(err);
+ const detail = codexForkFailureDetail(err);
throw forkError(
'CODEX_FORK_STATE_UNAVAILABLE',
detail,
@@ -700,7 +709,7 @@ export async function forkSessionStripEncrypted(sourceSessionId: string): Promis
workingDir: source.workingDir ?? undefined,
stripEncryptedReasoning: true,
}).catch((err: unknown) => {
- const detail = err instanceof Error ? err.message : String(err);
+ const detail = codexForkFailureDetail(err);
throw forkError(
'CODEX_FORK_STATE_UNAVAILABLE',
detail,
diff --git a/apps/desktop/src/renderer/__tests__/useForkAtMessage.test.ts b/apps/desktop/src/renderer/__tests__/useForkAtMessage.test.ts
index d9011736b8..56b4662d34 100644
--- a/apps/desktop/src/renderer/__tests__/useForkAtMessage.test.ts
+++ b/apps/desktop/src/renderer/__tests__/useForkAtMessage.test.ts
@@ -7,6 +7,7 @@
import { act, renderHook } from '@testing-library/react';
import { createElement, type ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-input-projection';
const navigate = vi.hoisted(() => vi.fn());
const forkAtMessage = vi.hoisted(() => vi.fn());
@@ -250,4 +251,26 @@ describe('useForkAtMessage', () => {
expect(toastError).toHaveBeenCalledWith('chat.userMessage.forkErrors.codexStateUnavailable');
expect(navigate).not.toHaveBeenCalled();
});
+
+ it('shows the localized retry message when safe fork preparation is blocked', async () => {
+ forkAtMessage.mockRejectedValueOnce(
+ new ApiError('CODEX_FORK_STATE_UNAVAILABLE', 0, CODEX_RESUME_NOT_READY_WIRE_MESSAGE),
+ );
+ const { result } = renderHook(() =>
+ useForkAtMessage({
+ sessionId: 'source-session',
+ messageClientId: 'message-1',
+ }),
+ );
+
+ await act(async () => {
+ await expect(result.current()).rejects.toThrow(CODEX_RESUME_NOT_READY_WIRE_MESSAGE);
+ });
+
+ expect(toastError).toHaveBeenCalledWith('chat.errorBanner.codexResumeNotReady');
+ expect(toastError).not.toHaveBeenCalledWith(
+ 'chat.userMessage.forkErrors.codexStateUnavailable',
+ );
+ expect(navigate).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index dc11ab8566..e1fc4033e3 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -13,6 +13,7 @@
*/
import { useEffect, useState } from 'react';
+import { isCodexResumeNotReadyProjectionError } from '@cindy/maker-shared/agent-input-projection';
import {
AlertCircle,
Check,
@@ -289,7 +290,9 @@ export function ErrorBanner({
// 加 else if, 标志自动保持 true, 折扣版提示不会误叠加 (无需记得同步维护条件表)。
let displayError: string;
let hasSpecialGuidance = true;
- if (isPiImageInputUnsupportedError(error)) {
+ if (isCodexResumeNotReadyProjectionError(error)) {
+ displayError = t('chat.errorBanner.codexResumeNotReady');
+ } else if (isPiImageInputUnsupportedError(error)) {
displayError = t('ipcError.PI_IMAGE_INPUT_UNSUPPORTED');
} else if (isCredentialSwitchBusy) {
displayError = t('chat.errorBanner.credentialSwitchBusy');
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
index 3d394eeb86..080b1b7cfa 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
@@ -2,6 +2,7 @@
import { act, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-input-projection';
import { ErrorBanner } from '../ErrorBanner';
import { useCodexAuth } from '@/hooks/useCodexAuth';
@@ -132,6 +133,21 @@ describe('ErrorBanner OpenAI connection recovery', () => {
};
});
+ it('localizes the Codex resume preflight marker without exposing the host envelope', () => {
+ const error = `LAZY_CREATE_FAILED: ${CODEX_RESUME_NOT_READY_WIRE_MESSAGE}`;
+ render(
+ <ErrorBanner
+ error={error}
+ retryText="retry this turn"
+ onRetry={vi.fn()}
+ agentKind="codex"
+ />,
+ );
+
+ expect(screen.getByText('chat.errorBanner.codexResumeNotReady')).toBeTruthy();
+ expect(screen.queryByText(error)).toBeNull();
+ });
+
it('opens the ChatGPT App for an invalidated system-shared login', async () => {
mocks.getState.mockResolvedValue({
authenticated: false,
diff --git a/apps/desktop/src/renderer/components/chat/useForkAtMessage.ts b/apps/desktop/src/renderer/components/chat/useForkAtMessage.ts
index 8aedc195ea..d092acd62d 100644
--- a/apps/desktop/src/renderer/components/chat/useForkAtMessage.ts
+++ b/apps/desktop/src/renderer/components/chat/useForkAtMessage.ts
@@ -25,6 +25,7 @@ import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';
import { refreshRemoteDeviceSessions } from '@/features/device-link/refreshRemoteSessions';
import { useSessionNavigationMode } from '@/features/cc-agent/embeddedSessionNavigation';
import { createLogger } from '@/lib/logger';
+import { isCodexResumeNotReadyProjectionError } from '@cindy/maker-shared/agent-input-projection';
const log = createLogger('useForkAtMessage');
@@ -117,6 +118,7 @@ export function useForkAtMessage({
navigate(`/cc-agent/${newSession.id}`);
} catch (err) {
const code = err instanceof ApiError ? err.code : 'UNKNOWN';
+ const detail = err instanceof Error ? err.message : String(err);
const msg =
code === 'FORK_UNSUPPORTED_HISTORY'
? t('chat.userMessage.forkErrors.unsupportedHistory')
@@ -125,9 +127,9 @@ export function useForkAtMessage({
: code === 'SOURCE_NEVER_RAN'
? t('chat.userMessage.forkErrors.sourceNeverRan')
: code === 'CODEX_FORK_STATE_UNAVAILABLE'
- ? t('chat.userMessage.forkErrors.codexStateUnavailable', {
- detail: err instanceof Error ? err.message : String(err),
- })
+ ? isCodexResumeNotReadyProjectionError(detail)
+ ? t('chat.errorBanner.codexResumeNotReady')
+ : t('chat.userMessage.forkErrors.codexStateUnavailable', { detail })
: t('chat.userMessage.forkErrors.generic');
toast.error(msg);
// Re-throw so MessageActionBar's `forking` state knows to clear via
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index e19b0dad8b..d32baba000 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -26,7 +26,10 @@ import type { CSSProperties, ReactNode } from 'react';
import { useLocation, useNavigate, useOutletContext, useParams } from 'react-router-dom';
import { dbToMakerAgentKind, normalizeDbAgentKind } from '../../../shared/agentKindConversion';
import { useTranslation } from 'react-i18next';
-import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
+import {
+ isCodexResumeNotReadyProjectionError,
+ type AgentInputReference,
+} from '@cindy/maker-shared/agent-input-projection';
import {
connectedProvidersForAgent,
providerOffersModel,
@@ -2737,10 +2740,13 @@ export function CCAgentSessionView({
navigate(`/cc-agent/${newSession.id}`);
} catch (err) {
const ipcError = extractIpcError(err);
+ const detail = ipcError?.message || (err instanceof Error ? err.message : String(err));
toast.error(
- ipcError?.code === 'FORK_UNSUPPORTED_HISTORY'
+ isCodexResumeNotReadyProjectionError(detail)
+ ? t('chat.errorBanner.codexResumeNotReady')
+ : ipcError?.code === 'FORK_UNSUPPORTED_HISTORY'
? t('chat.userMessage.forkErrors.unsupportedHistory')
- : ipcError?.message || (err instanceof Error ? err.message : String(err)),
+ : detail,
);
} finally {
setForkStripEncryptedRunning(false);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 664affaa88..7993bc56c9 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5575,6 +5575,7 @@
"viewBalanceTitle": "Open Usage & Billing to check your balance and add funds",
"credentialSwitchBusy": "Another Codex task is still running, so the provider for this session can't be applied yet (the shared Codex process needs a restart). Retry after those tasks finish.",
"codexThreadStale": "Codex auth mode changed — this session can't continue. Start a new session to apply it.",
+ "codexResumeNotReady": "Codex can't resume this task right now. Try again in a little while.",
"claudeGatewayOpusPlanMismatch": "This Opus request went through XD Gateway, not your Claude.ai subscription. That gateway route rejected the model. Switch to your Claude.ai subscription and retry, or choose another model.",
"claudeSubscriptionOpusPlanMismatch": "Opus isn't available on the connected Claude Pro plan. Switch to a model included in your plan. If you recently upgraded, reconnect Anthropic in Settings, then retry.",
"switchClaudeSubscription": "Switch to Claude.ai & Retry",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 40d6f80b4d..79496e5b59 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5573,6 +5573,7 @@
"viewBalanceTitle": "「使用量と請求」を開いて残高を確認・チャージ",
"credentialSwitchBusy": "他の Codex タスクが実行中のため、このセッションで選択したプロバイダーへまだ切り替えられません(共有 Codex プロセスの再起動が必要です)。他のタスクの終了後に「再試行」を押してください。",
"codexThreadStale": "Codex の認証モードが切り替わりました。このセッションは続行できません。新しいセッションを開始してください。",
+ "codexResumeNotReady": "Codex は現在このタスクを再開できません。しばらくしてからもう一度お試しください。",
"claudeGatewayOpusPlanMismatch": "この Opus リクエストは Claude.ai サブスクリプションではなく、XD Gateway 経由で送信され、このモデルが拒否されました。Claude.ai サブスクリプションに切り替えて再試行するか、別のモデルを選択してください。",
"claudeSubscriptionOpusPlanMismatch": "接続中の Claude Pro プランでは Opus を利用できません。プランに含まれるモデルに切り替えてください。最近プランを変更した場合は、設定で Anthropic を再接続してから再試行してください。",
"switchClaudeSubscription": "Claude.ai に切り替えて再試行",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index d69fea01a7..86680755d4 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5573,6 +5573,7 @@
"viewBalanceTitle": "「사용량 및 청구」를 열어 잔액을 확인하고 충전",
"credentialSwitchBusy": "다른 Codex 작업이 실행 중이어서 이 세션에서 선택한 제공자로 아직 전환할 수 없습니다(공유 Codex 프로세스 재시작 필요). 다른 작업이 끝난 후 ‘재시도’를 눌러 주세요.",
"codexThreadStale": "Codex 인증 모드가 변경되었습니다. 이 세션은 계속할 수 없습니다. 새 세션을 시작하세요.",
+ "codexResumeNotReady": "Codex에서 현재 이 작업을 재개할 수 없습니다. 잠시 후 다시 시도해 주세요.",
"claudeGatewayOpusPlanMismatch": "이 Opus 요청은 Claude.ai 구독이 아니라 XD Gateway를 통해 전송되었고, 해당 게이트웨이 경로에서 모델을 거부했습니다. Claude.ai 구독으로 전환해 다시 시도하거나 다른 모델을 선택하세요.",
"claudeSubscriptionOpusPlanMismatch": "현재 연결된 Claude Pro 요금제에서는 Opus를 사용할 수 없습니다. 요금제에 포함된 모델로 전환하세요. 최근 요금제를 업그레이드했다면 설정에서 Anthropic을 다시 연결한 후 재시도하세요.",
"switchClaudeSubscription": "Claude.ai로 전환 후 재시도",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 8a37bacdd8..5492f65493 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5573,6 +5573,7 @@
"viewBalanceTitle": "打开「用量和计费」查看余额并充值",
"credentialSwitchBusy": "Codex 正在其它任务中运行,暂时无法按本任务选择的模型来源切换(需要重启共享的 Codex 后台进程)。等它结束后点「重试」即可。",
"codexThreadStale": "Codex 鉴权模式已切换,当前任务无法继续 —— 请新建任务后生效。",
+ "codexResumeNotReady": "Codex 暂时无法恢复这个任务,请稍后重试",
"claudeGatewayOpusPlanMismatch": "这次 Opus 请求实际走的是 XD Gateway,不是你的 Claude.ai 订阅;该网关路由拒绝了此模型。可切换到 Claude.ai 订阅后重试,或换一个模型。",
"claudeSubscriptionOpusPlanMismatch": "当前连接的 Claude Pro 套餐不支持 Opus。请切换到套餐支持的模型;如果刚升级套餐,请在设置中重新连接 Anthropic 后重试。",
"switchClaudeSubscription": "切换到 Claude.ai 并重试",
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 81b80ff35e..51c96090d1 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -89,6 +89,7 @@ import { InteractionPanel, type MobilePlanViewerState } from '@/session/Interact
import { MessageRenderer, type MobileMessageDraft } from '@/session/MessageRenderer';
import { ComposerRichInput, type ComposerRichInputHandle } from '@/session/ComposerRichInput';
import { InlineQueueSection } from '@/session/InlineQueueSection';
+import { inputProjectionErrorI18nKey } from '@/session/inputProjectionError';
import { RewindPreviewPanel } from '@/session/RewindPreviewPanel';
import { BlurBackdrop } from '@/session/BlurBackdrop';
import { SheetModal } from '@/session/SheetModal';
@@ -7438,11 +7439,13 @@ export default function SessionScreen() {
params: { sessionId: forked.id, deviceId, deviceName },
});
} catch (err) {
- setError(formatRemoteError(err));
+ const detail = formatRemoteError(err);
+ const projectionKey = inputProjectionErrorI18nKey(detail);
+ setError(projectionKey ? t(projectionKey) : detail);
} finally {
setMessageActionBusy(null);
}
- }, [deviceId, deviceName, maker, messageActionBusy, router, sessionId]);
+ }, [deviceId, deviceName, maker, messageActionBusy, router, sessionId, t]);
const forkAtMessage = useCallback((clientId: string, draft?: MobileMessageDraft) => {
if (!deviceId || messageActionBusy) return;
diff --git a/apps/mobile/src/__tests__/inputProjectionError.test.ts b/apps/mobile/src/__tests__/inputProjectionError.test.ts
index a76a435763..c59adea30e 100644
--- a/apps/mobile/src/__tests__/inputProjectionError.test.ts
+++ b/apps/mobile/src/__tests__/inputProjectionError.test.ts
@@ -1,17 +1,33 @@
import { describe, expect, it } from 'vitest';
+import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-input-projection';
-import { isPiImageInputUnsupportedProjectionError } from '@/session/inputProjectionError';
+import {
+ inputProjectionErrorI18nKey,
+ isPiImageInputUnsupportedProjectionError,
+} from '@/session/inputProjectionError';
describe('isPiImageInputUnsupportedProjectionError', () => {
it('recognizes the Desktop projection marker without depending on host locale', () => {
- expect(
- isPiImageInputUnsupportedProjectionError(
- '[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled',
- ),
- ).toBe(true);
+ const error = '[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled';
+ expect(isPiImageInputUnsupportedProjectionError(error)).toBe(true);
+ expect(inputProjectionErrorI18nKey(error)).toBe('message.queue.piImageInputUnsupported');
});
it('leaves ordinary remote errors untouched', () => {
expect(isPiImageInputUnsupportedProjectionError('provider unavailable')).toBe(false);
});
+
+ it('maps the shared Codex resume marker to a locale key without exposing host diagnostics', () => {
+ expect(
+ inputProjectionErrorI18nKey(
+ `LAZY_CREATE_FAILED: ${CODEX_RESUME_NOT_READY_WIRE_MESSAGE}`,
+ ),
+ ).toBe('message.queue.codexResumeNotReady');
+ expect(
+ inputProjectionErrorI18nKey(
+ `[CODEX_FORK_STATE_UNAVAILABLE] ${CODEX_RESUME_NOT_READY_WIRE_MESSAGE}`,
+ ),
+ ).toBe('message.queue.codexResumeNotReady');
+ expect(inputProjectionErrorI18nKey('provider unavailable')).toBeNull();
+ });
});
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index 6b38120c5e..ee8f79d708 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -148,6 +148,7 @@
"retrySend": "Retry Send",
"clearError": "Clear Error",
"piImageInputUnsupported": "Image input is not enabled for the current Pi model. Switch to a model that supports images. For a custom model, enable “Supports image input” in provider settings, then start a new Pi task.",
+ "codexResumeNotReady": "Codex can't resume this task right now. Try again in a little while.",
"credentialSwitchWait": "Waiting for another Codex task to finish; it will send automatically once done",
"aborting": "Stopping; queued messages will stay here",
"paused": "Queue paused; queued messages won't send automatically",
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index 9d155a6fe3..efff14859a 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -148,6 +148,7 @@
"retrySend": "送信を再試行",
"clearError": "エラーをクリア",
"piImageInputUnsupported": "現在の Pi モデルでは画像入力が有効になっていません。画像に対応するモデルへ切り替えてください。カスタムモデルの場合は、プロバイダー設定で「画像入力に対応」を有効にしてから、新しい Pi タスクを開始してください。",
+ "codexResumeNotReady": "Codex は現在このタスクを再開できません。しばらくしてからもう一度お試しください。",
"credentialSwitchWait": "他の Codex タスクの終了を待っています。終了後に自動で送信します",
"aborting": "停止中です。キュー内のメッセージはここに保持されます",
"paused": "キューを一時停止しました。キュー内のメッセージは自動送信されません",
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index fd1bcb6382..88b28ed794 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -148,6 +148,7 @@
"retrySend": "전송 재시도",
"clearError": "오류 지우기",
"piImageInputUnsupported": "현재 Pi 모델에는 이미지 입력이 활성화되어 있지 않습니다. 이미지를 지원하는 모델로 전환하세요. 사용자 지정 모델이라면 제공자 설정에서 ‘이미지 입력 지원’을 켠 다음 새 Pi 작업을 시작하세요.",
+ "codexResumeNotReady": "Codex에서 현재 이 작업을 재개할 수 없습니다. 잠시 후 다시 시도해 주세요.",
"credentialSwitchWait": "다른 Codex 작업이 끝나기를 기다리는 중입니다. 끝나면 자동으로 전송합니다",
"aborting": "중지 중입니다. 대기 중인 메시지는 여기에 유지됩니다",
"paused": "큐가 일시정지되었습니다. 대기 중인 메시지는 자동으로 전송되지 않습니다",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index a5d7b0809a..f8143ac60c 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -148,6 +148,7 @@
"retrySend": "重试发送",
"clearError": "清除错误",
"piImageInputUnsupported": "当前 Pi 模型未启用图片输入。请切换到支持图片的模型;如果这是自定义模型,请在供应商设置中开启“支持图片输入”,然后新建 Pi 任务。",
+ "codexResumeNotReady": "Codex 暂时无法恢复这个任务,请稍后重试",
"credentialSwitchWait": "正在等待其它 Codex 任务结束,结束后自动发送",
"aborting": "正在停止,排队消息会保留在这里",
"paused": "队列已暂停,排队消息不会自动发送",
diff --git a/apps/mobile/src/session/InlineQueueSection.tsx b/apps/mobile/src/session/InlineQueueSection.tsx
index c7495f9765..a79658d603 100644
--- a/apps/mobile/src/session/InlineQueueSection.tsx
+++ b/apps/mobile/src/session/InlineQueueSection.tsx
@@ -24,7 +24,7 @@ import { Text } from '@/components/AppText';
import { Pause, Play } from 'lucide-react-native';
import { describeAgentAuthError } from '@/device-link/remoteStatus';
import type { InputProjection } from '@/session/types';
-import { isPiImageInputUnsupportedProjectionError } from '@/session/inputProjectionError';
+import { inputProjectionErrorI18nKey } from '@/session/inputProjectionError';
import {
fontWeight,
iconSize,
@@ -64,9 +64,12 @@ export function InlineQueueSection({
if (!hasBanner) return null;
const controlsDisabled = busy || !!readOnlyReason;
+ const projectionErrorKey = projection.error
+ ? inputProjectionErrorI18nKey(projection.error)
+ : null;
const projectionError = projection.error
- ? isPiImageInputUnsupportedProjectionError(projection.error)
- ? t('message.queue.piImageInputUnsupported')
+ ? projectionErrorKey
+ ? t(projectionErrorKey)
: (describeAgentAuthError(projection.error) ?? projection.error)
: null;
diff --git a/apps/mobile/src/session/inputProjectionError.ts b/apps/mobile/src/session/inputProjectionError.ts
index 608be51d05..8442c025f3 100644
--- a/apps/mobile/src/session/inputProjectionError.ts
+++ b/apps/mobile/src/session/inputProjectionError.ts
@@ -1,5 +1,18 @@
+import { isCodexResumeNotReadyProjectionError } from '@cindy/maker-shared/agent-input-projection';
+
export const PI_IMAGE_INPUT_UNSUPPORTED_MARKER = '[PI_IMAGE_INPUT_UNSUPPORTED]';
export function isPiImageInputUnsupportedProjectionError(error: string): boolean {
return error.includes(PI_IMAGE_INPUT_UNSUPPORTED_MARKER);
}
+
+export type InputProjectionErrorI18nKey =
+ | 'message.queue.codexResumeNotReady'
+ | 'message.queue.piImageInputUnsupported';
+
+/** Resolve stable host markers without freezing the current Mobile locale. */
+export function inputProjectionErrorI18nKey(error: string): InputProjectionErrorI18nKey | null {
+ if (isCodexResumeNotReadyProjectionError(error)) return 'message.queue.codexResumeNotReady';
+ if (isPiImageInputUnsupportedProjectionError(error)) return 'message.queue.piImageInputUnsupported';
+ return null;
+}
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 6856685566..b238034623 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -263,6 +263,19 @@ export interface ClaudeSubagentTaskUsage {
totalTokens: number;
}
+/**
+ * The host has positively identified a resume state that must not be handed to
+ * Codex yet (for example, a rollout file that may still have a live writer).
+ * Unlike an incidental preparation failure, this error deliberately blocks
+ * thread/resume so Codex cannot append to an unsafe path.
+ */
+export class CodexResumePreparationBlockedError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'CodexResumePreparationBlockedError';
+ }
+}
+
export interface AgentDeps {
auth: AuthAdapter;
runtimeConfig: AgentRuntimeConfig;
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 32d043ea70..77f541f8ef 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -6,7 +6,12 @@ import { promises as fs } from 'node:fs';
import { CodexAgent } from './index.js';
import { Method } from './app-server/protocol.js';
import type { ThreadEventHandlers } from './app-server/host.js';
-import type { AgentDeps, AgentSessionHandle, TurnPermissionPolicy } from '../base-agent.js';
+import {
+ CodexResumePreparationBlockedError,
+ type AgentDeps,
+ type AgentSessionHandle,
+ type TurnPermissionPolicy,
+} from '../base-agent.js';
import type { AuthAdapter } from '../../interfaces/auth-adapter.js';
import type { AgentEvent, InteractionDecision, InteractionRequest } from '../../types/events.js';
import type { Logger } from '../../interfaces/logger.js';
@@ -12395,6 +12400,68 @@ describe('CodexAgent steer', () => {
});
});
+describe('CodexAgent resume preparation', () => {
+ const resumeSessionId = '123e4567-e89b-12d3-a456-426614174000';
+
+ it('does not call thread/resume when the host identifies an unsafe rollout', async () => {
+ const prepareCodexResumeSession = vi.fn(async () => {
+ throw new CodexResumePreparationBlockedError('rollout may still have a live writer');
+ });
+ const agent = new CodexAgent(createDeps({}, { prepareCodexResumeSession }));
+ const host = installFakeHost(agent);
+
+ await expect(agent.startSession({
+ sessionId: 'session-blocked-resume-preparation',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ resumeSessionId,
+ })).rejects.toThrow('rollout may still have a live writer');
+
+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadResume)).toHaveLength(0);
+ expect((
+ agent as unknown as { hostSessionBindingLeases: Map<string, number> }
+ ).hostSessionBindingLeases.size).toBe(0);
+ });
+
+ it('preserves the existing best-effort resume behavior for incidental preparation errors', async () => {
+ const prepareCodexResumeSession = vi.fn(async () => {
+ throw new Error('diagnostic read failed');
+ });
+ const agent = new CodexAgent(createDeps({}, { prepareCodexResumeSession }));
+ const host = installFakeHost(agent);
+
+ const handle = await agent.startSession({
+ sessionId: 'session-best-effort-resume-preparation',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ resumeSessionId,
+ });
+
+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadResume)).toHaveLength(1);
+ await handle.close();
+ });
+
+ it('does not apply local rollout preparation to a remote Codex resume', async () => {
+ const prepareCodexResumeSession = vi.fn(async () => {
+ throw new CodexResumePreparationBlockedError('local rollout is empty');
+ });
+ const agent = new CodexAgent(createDeps({}, { prepareCodexResumeSession }));
+ const host = installFakeHost(agent);
+
+ const handle = await agent.startSession({
+ sessionId: 'session-remote-resume-preparation',
+ model: 'gpt-5.4',
+ workingDir: '/remote/repo',
+ remoteHostId: 'remote-host',
+ resumeSessionId,
+ });
+
+ expect(prepareCodexResumeSession).not.toHaveBeenCalled();
+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadResume)).toHaveLength(1);
+ await handle.close();
+ });
+});
+
describe('CodexAgent.forkSdkSession', () => {
it('prepares an imported source thread before thread/fork', async () => {
const order: string[] = [];
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 5e82dde722..d423bab253 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -26,6 +26,7 @@ import { promises as fs } from 'node:fs';
import {
BaseAgent,
+ CodexResumePreparationBlockedError,
OneShotError,
AgentNotAuthenticatedError,
TurnPermissionPolicyUnsupportedError,
@@ -3601,10 +3602,14 @@ export class CodexAgent extends BaseAgent {
};
if (opts.resumeSessionId && isLikelyValidThreadId(opts.resumeSessionId)) {
// Phase 3: thread/resume 真接通, 不再 fallback 到 thread/start
- if (this.deps.prepareCodexResumeSession) {
+ if (this.deps.prepareCodexResumeSession && !opts.remoteHostId) {
try {
await this.deps.prepareCodexResumeSession(opts.resumeSessionId);
} catch (e) {
+ if (e instanceof CodexResumePreparationBlockedError) {
+ releaseHostBindingLeaseIfNeeded();
+ throw e;
+ }
log.warn('prepareCodexResumeSession failed, continuing to thread/resume', {
resumeSessionId: opts.resumeSessionId,
error: e instanceof Error ? e.message : String(e),
diff --git a/packages/maker-shared/src/__tests__/agentInputProjection.test.ts b/packages/maker-shared/src/__tests__/agentInputProjection.test.ts
index 49209b136b..7c3d27991f 100644
--- a/packages/maker-shared/src/__tests__/agentInputProjection.test.ts
+++ b/packages/maker-shared/src/__tests__/agentInputProjection.test.ts
@@ -2,7 +2,10 @@ import { describe, expect, it } from 'vitest';
import {
AGENT_MESSAGE_REFERENCE_MAX_CHARS,
+ CODEX_RESUME_NOT_READY_MARKER,
+ CODEX_RESUME_NOT_READY_WIRE_MESSAGE,
buildPluginResourceReferenceHref,
+ isCodexResumeNotReadyProjectionError,
parsePluginResourceReferenceHref,
projectAgentFacingText,
projectPersistedAgentFacingUserText,
@@ -12,6 +15,25 @@ import {
const QUOTE_MARKER = '> <!-- cindy-composer-quote -->';
+describe('Codex resume projection marker', () => {
+ it('recognizes the marker inside the existing host-send failure envelope', () => {
+ expect(
+ isCodexResumeNotReadyProjectionError(
+ `LAZY_CREATE_FAILED: ${CODEX_RESUME_NOT_READY_WIRE_MESSAGE}`,
+ ),
+ ).toBe(true);
+ expect(
+ isCodexResumeNotReadyProjectionError(
+ `REHYDRATE_FAILED: ${CODEX_RESUME_NOT_READY_WIRE_MESSAGE}`,
+ ),
+ ).toBe(true);
+ expect(CODEX_RESUME_NOT_READY_WIRE_MESSAGE).toBe(
+ `${CODEX_RESUME_NOT_READY_MARKER} Codex can't resume this task right now. Try again shortly.`,
+ );
+ expect(isCodexResumeNotReadyProjectionError('LAZY_CREATE_FAILED: bootstrap failed')).toBe(false);
+ });
+});
+
function rangeFor<T extends Omit<AgentInputReference, 'start' | 'end'>>(
text: string,
href: string,
diff --git a/packages/maker-shared/src/agentInputProjection.ts b/packages/maker-shared/src/agentInputProjection.ts
index e5f39452ed..8131a14364 100644
--- a/packages/maker-shared/src/agentInputProjection.ts
+++ b/packages/maker-shared/src/agentInputProjection.ts
@@ -1,6 +1,18 @@
import { stripChatQuoteMarkerLines } from './chatQuotes.js';
import { allDeepLinkSchemes } from './brandIdentity.js';
+/** Stable cross-client marker for a retryable local Codex resume preflight. */
+export const CODEX_RESUME_NOT_READY_MARKER = '[CODEX_RESUME_NOT_READY]';
+
+/** Readable fallback for older clients that do not yet localize the marker. */
+export const CODEX_RESUME_NOT_READY_WIRE_MESSAGE =
+ `${CODEX_RESUME_NOT_READY_MARKER} Codex can't resume this task right now. Try again shortly.`;
+
+/** Keep host diagnostics out of projections while letting each client localize the error. */
+export function isCodexResumeNotReadyProjectionError(error: string): boolean {
+ return error.includes(CODEX_RESUME_NOT_READY_MARKER);
+}
+
/** Maximum copied target-message text kept in one Composer reference. */
export const AGENT_MESSAGE_REFERENCE_MAX_CHARS = 12_000;