Skip to content
Merged
Show file tree
Hide file tree
Changes from 31 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
95de52f
fix(codex): legacy migration never overwrites transcripts or drops hi…
brennanb2025 Nov 20, 2026
cb03fef
fix(codex): import legacy prompt history only while no Codex thread i…
brennanb2025 Nov 20, 2026
e5b7009
fix(codex): never write a live shared history during the legacy migra…
brennanb2025 Nov 20, 2026
e29d179
fix(codex): keep legacy prompt history aside before anything else in …
brennanb2025 Nov 20, 2026
614be27
fix(codex): retry the legacy history import from Orca's kept copies
brennanb2025 Nov 20, 2026
c62e27c
fix(codex): run the kept legacy history import independently of sessi…
brennanb2025 Nov 20, 2026
acedce5
fix(codex): keep one real copy of each legacy history, published by r…
brennanb2025 Nov 20, 2026
1e35b8b
fix(codex): refresh the kept legacy history and refuse linked kept fo…
brennanb2025 Nov 20, 2026
1148b24
fix(codex): set the earlier kept history aside when Codex trimmed the…
brennanb2025 Nov 20, 2026
190d347
fix(codex): account removal keeps prompt history; import reads accoun…
brennanb2025 Nov 20, 2026
6e2f608
fix(codex): skip the history import where hard links are refused; say…
brennanb2025 Nov 20, 2026
048ae71
fix(codex): retry on unreadable account histories; classify only link…
brennanb2025 Nov 20, 2026
c08949a
fix(codex): mark the migration after the session copies; retry only a…
brennanb2025 Nov 20, 2026
392a18f
fix(codex): read linked account histories; ignore account folders wit…
brennanb2025 Nov 20, 2026
75dee20
fix(codex): mark the migration done only once history settles; keep a…
brennanb2025 Nov 20, 2026
7caad8a
fix(codex): keep every entry a linked prompt history passes through; …
brennanb2025 Nov 20, 2026
351c00f
fix(codex): follow a linked prompt history one component at a time; s…
brennanb2025 Nov 20, 2026
deddf1f
fix(codex): preserve each account history in the runtime home, then m…
brennanb2025 Nov 20, 2026
0c1abd9
fix(codex): preserve account histories off the main thread, before ma…
brennanb2025 Nov 20, 2026
653270d
fix(codex): delete only the logins from a home whose history is a lin…
brennanb2025 Nov 20, 2026
c184003
fix(codex): run the session pass after the history copies, and write …
brennanb2025 Nov 20, 2026
6ce1919
Merge remote-tracking branch 'origin/main' into brennanb2025/codex-le…
brennanb2025 Nov 20, 2026
9361342
fix(codex): copy histories, sessions and the marker in one synchronou…
brennanb2025 Nov 20, 2026
f53e6d6
fix(codex): remove only listed login files beside a linked history; m…
brennanb2025 Nov 20, 2026
3cc96ac
fix(codex): leave a linked secrets folder's files alone; reuse one te…
brennanb2025 Nov 20, 2026
96cf8ec
fix(codex): remove nothing from a home whose history is a link; copy …
brennanb2025 Nov 20, 2026
0c37e1d
refactor(codex): main's migration marker, capped session retries, Win…
brennanb2025 Nov 20, 2026
b5e6170
fix(codex): keep session conflict copies only from a session pass tha…
brennanb2025 Nov 20, 2026
2e64257
fix(codex): a failing session pass removes the conflict copies it made
brennanb2025 Nov 20, 2026
29ca9ef
test(codex): skip the linked account history test on Windows
brennanb2025 Nov 23, 2026
441e1c0
Merge origin/main into brennanb2025/codex-legacy-migration-no-overwrite
brennanb2025 Nov 23, 2026
992489f
test(codex): check session copies and the shared history right after …
brennanb2025 Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion config/main-blocking-helper-baseline.txt
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@
4 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts
19 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts
2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-config-compatibility.ts
3 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts
2 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts
11 src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts # Codex launch prep from #43365 already merged; unblocks main, async follow-up owed
9 src/main/codex-accounts/runtime-home/routing/runtime-home-service-launch.ts
8 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts
Expand Down
2 changes: 1 addition & 1 deletion config/main-sync-fs-baseline.txt
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@
23 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-auth-sync.ts
2 src/main/codex-accounts/runtime-home/credentials/runtime-home-service-wsl-core.ts
2 src/main/codex-accounts/runtime-home/legacy-host/legacy-shared-auth-migration.ts
19 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts
18 src/main/codex-accounts/runtime-home/legacy-host/runtime-home-service-legacy-migration.ts
1 src/main/codex-accounts/runtime-home/routing/runtime-home-service-managed-home.ts
14 src/main/codex-accounts/runtime-home/runtime-home-service-paths.ts
1 src/main/codex-accounts/runtime-home/runtime-home-service-sync.ts
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ const WSL_MANAGED_HOME_TIMEOUT_MS = 5_000
// that was busy at every launch may still hold its only copy, and a merge keeps conflicting
// copies (and set-aside rollout forms, listed in the cleanup manifest) beside the links; all of
// it outlives the login. A home that was shared (it has the manifest) keeps its own databases
// too: deleting them waits for a later release that has seen the shared store work.
// too: deleting them waits for a later release that has seen the shared store work. The prompt
// history stays as well: it may be the only copy of prompts never merged into the shared history.
const KEPT_HISTORY = [
'history.jsonl',
'sessions',
'archived_sessions',
SET_ASIDE_ROLLOUTS_DIR,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import { readFile, rename, rm, writeFile } from 'node:fs/promises'
import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code'
import {
importLegacyHistoriesIfSharedAbsent,
legacyHistoryInputsKey
} from './legacy-prompt-history-import'

/** Failed launches before the import waits for the account histories to change. */
export const MAX_HISTORY_IMPORT_ATTEMPTS = 3
/** How long a given-up import waits before trying again with unchanged account histories. */
export const HISTORY_IMPORT_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000

export type LegacyHistoryState = {
/** Failed session passes; after a few, the pass waits a day between tries. */
sessionPassAttempts?: number
sessionPassFailedAt?: number
/** The shared history was created, or already existed, so nothing is owed. */
historyImportSettled?: boolean
historyImportAttempts?: number
/** The account histories' sizes and times when the import last gave up. */
historyImportInputs?: string
historyImportGaveUpAt?: number
}

/** Like the import: a few tries, then once a day, so a lasting failure isn't redone every launch. */
export function legacySessionPassDue(state: LegacyHistoryState): boolean {
return (
(state.sessionPassAttempts ?? 0) < MAX_HISTORY_IMPORT_ATTEMPTS ||
Date.now() - (state.sessionPassFailedAt ?? 0) >= HISTORY_IMPORT_RETRY_INTERVAL_MS
)
}

export function recordLegacySessionPassFailure(state: LegacyHistoryState): LegacyHistoryState {
return {
...state,
sessionPassAttempts: (state.sessionPassAttempts ?? 0) + 1,
sessionPassFailedAt: Date.now()
}
}

/** Where the shared history import reads and records its attempts. */
export type LegacyHistoryImportPaths = {
accountsRoot: string
runtimeHistoryPath: string
statePath: string
}

export function parseLegacyHistoryState(text: string): LegacyHistoryState {
const parsed: unknown = JSON.parse(text)
const state: LegacyHistoryState = {}
if (!parsed || typeof parsed !== 'object') {
return state
}
if ('sessionPassAttempts' in parsed && typeof parsed.sessionPassAttempts === 'number') {
state.sessionPassAttempts = parsed.sessionPassAttempts
}
if ('sessionPassFailedAt' in parsed && typeof parsed.sessionPassFailedAt === 'number') {
state.sessionPassFailedAt = parsed.sessionPassFailedAt
}
if ('historyImportSettled' in parsed && parsed.historyImportSettled === true) {
state.historyImportSettled = true
}
if ('historyImportAttempts' in parsed && typeof parsed.historyImportAttempts === 'number') {
state.historyImportAttempts = parsed.historyImportAttempts
}
if ('historyImportInputs' in parsed && typeof parsed.historyImportInputs === 'string') {
state.historyImportInputs = parsed.historyImportInputs
}
if ('historyImportGaveUpAt' in parsed && typeof parsed.historyImportGaveUpAt === 'number') {
state.historyImportGaveUpAt = parsed.historyImportGaveUpAt
}
return state
}

async function readTextIfPresent(path: string): Promise<string | null> {
try {
return await readFile(path, 'utf-8')
} catch (error) {
if (errnoCodeOrUnknown(error) === 'ENOENT') {
return null
}
throw error
}
}

async function writeTextAtomically(path: string, text: string): Promise<void> {
// One fixed name, cleared first, so a quit mid-write leaves nothing behind for good.
const tmpPath = `${path}.tmp`
await rm(tmpPath, { force: true })
try {
await writeFile(tmpPath, text, { encoding: 'utf-8', flag: 'wx' })
await rename(tmpPath, path)
} finally {
await rm(tmpPath, { force: true })
}
}

/**
* After a few failed launches, a change to the account histories or a day's wait earns another
* attempt, so a failure that clears (permissions, a mount) still imports.
*/
async function retryLegacyHistoryImport(
paths: LegacyHistoryImportPaths,
state: LegacyHistoryState
): Promise<void> {
if ((state.historyImportAttempts ?? 0) >= MAX_HISTORY_IMPORT_ATTEMPTS) {
const inputs = await legacyHistoryInputsKey(paths.accountsRoot).catch(() => null)
if (inputs !== null && inputs !== state.historyImportInputs) {
state = { ...state, historyImportAttempts: 0 }
} else if (Date.now() - (state.historyImportGaveUpAt ?? 0) < HISTORY_IMPORT_RETRY_INTERVAL_MS) {
return
} else {
state = { ...state, historyImportAttempts: MAX_HISTORY_IMPORT_ATTEMPTS - 1 }
}
}
try {
await importLegacyHistoriesIfSharedAbsent(paths.accountsRoot, paths.runtimeHistoryPath)
state = { ...state, historyImportSettled: true }
} catch (error) {
console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error)
const attempts = (state.historyImportAttempts ?? 0) + 1
const gaveUp = attempts >= MAX_HISTORY_IMPORT_ATTEMPTS
state = {
...state,
historyImportAttempts: attempts,
historyImportInputs: gaveUp
? await legacyHistoryInputsKey(paths.accountsRoot).catch(() => undefined)
: undefined,
historyImportGaveUpAt: gaveUp ? Date.now() : undefined
}
}
await writeTextAtomically(paths.statePath, `${JSON.stringify(state)}\n`)
}

/**
* Off the startup path: imports the shared history until it settles, retrying on later launches.
* Never rejects.
*/
export async function settleLegacyHistoryImport(paths: LegacyHistoryImportPaths): Promise<void> {
try {
const text = await readTextIfPresent(paths.statePath)
const state = text === null ? {} : parseLegacyHistoryState(text)
if (!state.historyImportSettled) {
await retryLegacyHistoryImport(paths, state)
}
} catch (error) {
console.warn('[codex-runtime-home] Failed to import legacy Codex prompt history:', error)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import { randomUUID } from 'node:crypto'
import { link, lstat, open, readFile, readdir, rm, stat } from 'node:fs/promises'
import { basename, dirname, join } from 'node:path'
import { errnoCodeOrUnknown } from '../../../../shared/errors/errno-code'
import { track } from '../../../telemetry/client'
import { isHardLinkUnsupportedError } from '../../../codex/history/rollouts/codex-rollout-copy'
import type { CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES } from '../../../../shared/telemetry/schemas/telemetry-codex-legacy-history-event-schemas'

type LegacyHistoryImportOutcome = (typeof CODEX_LEGACY_HISTORY_IMPORT_OUTCOMES)[number]

/** Stats only: cheap enough to ask at every launch whether the account histories changed. */
export async function legacyHistoryInputsKey(accountsRoot: string): Promise<string> {
const parts: string[] = []
for (const historyPath of await listAccountHistories(accountsRoot)) {
const stats = await stat(historyPath)
parts.push(`${historyPath}:${stats.size}:${stats.mtimeMs}`)
}
return parts.join('|')
}

async function pathExists(path: string): Promise<boolean> {
try {
await lstat(path)
return true
} catch (error) {
if (errnoCodeOrUnknown(error) === 'ENOENT') {
return false
}
throw error
}
}

// Every account's own history file, ownership marker or not: a removed or shared home keeps it.
async function listAccountHistories(accountsRoot: string): Promise<string[]> {
const accounts = await readdir(accountsRoot, { withFileTypes: true }).catch((error: unknown) => {
if (errnoCodeOrUnknown(error) === 'ENOENT') {
return []
}
throw error
})
const paths: string[] = []
for (const account of accounts.filter((entry) => entry.isDirectory())) {
const historyPath = join(accountsRoot, account.name, 'home', 'history.jsonl')
// Followed through a link, as Codex reads it. Only an absent file, no home folder or a link loop
// means no history; any other error retries rather than skip an account.
const stats = await stat(historyPath).catch((error: unknown) => {
const code = errnoCodeOrUnknown(error)
if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'ELOOP') {
return null
}
throw error
})
if (stats?.isFile()) {
paths.push(historyPath)
}
}
return paths.sort()
}

/**
* Codex may be appending to or trimming a shared history.jsonl that exists, so only a missing one
* is created from the account histories, which are only read, and never over one Codex creates
* meanwhile. Rejects on failure, so the migration retries on the next launch.
*/
export async function importLegacyHistoriesIfSharedAbsent(
accountsRoot: string,
runtimeHistoryPath: string
): Promise<void> {
const accountHistoryPaths = await listAccountHistories(accountsRoot)
if (accountHistoryPaths.length === 0) {
return
}
let outcome: LegacyHistoryImportOutcome = 'failed'
try {
outcome = await publishLegacyHistoriesIfAbsent(accountHistoryPaths, runtimeHistoryPath)
} finally {
trackLegacyHistoryImport(outcome)
}
}

async function publishLegacyHistoriesIfAbsent(
accountHistoryPaths: readonly string[],
runtimeHistoryPath: string
): Promise<LegacyHistoryImportOutcome> {
if (await pathExists(runtimeHistoryPath)) {
return 'skipped_existing'
}
const seenLines = new Set<string>()
for (const accountHistoryPath of accountHistoryPaths) {
for (const line of (await readFile(accountHistoryPath, 'utf-8')).split('\n')) {
if (line) {
seenLines.add(line)
}
}
}
if (seenLines.size === 0) {
return 'nothing_to_import'
}
return publishWithoutOverwrite(`${[...seenLines].join('\n')}\n`, runtimeHistoryPath)
}

async function publishWithoutOverwrite(
contents: string,
targetPath: string
): Promise<LegacyHistoryImportOutcome> {
await removeStaleImportCopies(targetPath)
const tmpPath = `${targetPath}.${process.pid}.${randomUUID()}${IMPORT_COPY_SUFFIX}`
try {
const handle = await open(tmpPath, 'wx', 0o600)
try {
await handle.writeFile(contents, 'utf-8')
await handle.sync()
} finally {
await handle.close()
}
return await linkIntoFreeName(tmpPath, targetPath)
} finally {
await rm(tmpPath, { force: true })
}
}

const IMPORT_COPY_SUFFIX = '.orca-import.tmp'

// Copies an attempt a quit cut short left behind. Only regular files: removing one only drops that
// name, even when it is a hard link to the published history.
async function removeStaleImportCopies(targetPath: string): Promise<void> {
const prefix = `${basename(targetPath)}.`
for (const entry of await readdir(dirname(targetPath), { withFileTypes: true })) {
if (
entry.isFile() &&
entry.name.startsWith(prefix) &&
entry.name.endsWith(IMPORT_COPY_SUFFIX)
) {
await rm(join(dirname(targetPath), entry.name), { force: true })
}
}
}

// A hard link publishes only into a free name: one Codex created meanwhile stays as it is.
async function linkIntoFreeName(
tmpPath: string,
targetPath: string
): Promise<LegacyHistoryImportOutcome> {
try {
await link(tmpPath, targetPath)
return 'imported'
} catch (error) {
const code = errnoCodeOrUnknown(error)
if (code === 'EEXIST') {
return 'skipped_existing'
}
// No safe way to publish without replacing: every other way leaves a name Codex can append
// into mid-write. The account histories stay in their homes, so nothing is lost, and the import
// settles rather than retry on a filesystem that won't change.
if (isHardLinkUnsupportedError(error)) {
return 'skipped_no_hard_links'
}
throw error
}
}

function trackLegacyHistoryImport(outcome: LegacyHistoryImportOutcome): void {
try {
track('codex_legacy_history_import', {
outcome,
platform:
process.platform === 'win32' || process.platform === 'linux' ? process.platform : 'darwin'
})
} catch {
// Telemetry never costs the migration.
}
}
Loading
Loading