feat(workspace-cleanup): delete Codex chat history with the workspace (#43000)

The sweep now also deletes Codex rollouts whose workspace folder is gone,
under the same folder rule. A rollout is deleted under every name it has
across the host's Codex homes (sessions and archived_sessions, .jsonl and
.jsonl.zst), only when every copy is idle, its last turn ran in the gone
folder and Codex holds no writer lock for the thread. History link passes,
backfill and resume skip a rollout while it is being deleted, and no longer
leave a dangling symlink when the source is gone.

Fixes #16776

Co-authored-by: Max Hsu <maxmilian@gmail.com>
This commit is contained in:
Kelvin Amoaba
2026-11-16 23:10:41 +00:00
committed by GitHub
co-authored by Max Hsu
parent 58d5656097
commit 11403c1475
18 changed files with 935 additions and 56 deletions
+1 -1
View File
@@ -161,7 +161,7 @@ orca workspace cleanup run --json
orca workspace cleanup report --json
```
`preview` shows what your cleanup rules would remove now and why every other workspace stays. `run` applies the rules now: each workspace is checked again right before removal and nothing is forced. `report` lists recent runs and when the next one is due. With no rule on, nothing is removed. With **Delete chat history with the workspace** on, `run` also deletes Claude Code chats from workspaces that no longer exist. Rules are set in Orca settings; these commands never change them. Add `--environment <id>` to run them on a paired server.
`preview` shows what your cleanup rules would remove now and why every other workspace stays. `run` applies the rules now: each workspace is checked again right before removal and nothing is forced. `report` lists recent runs and when the next one is due. With no rule on, nothing is removed. With **Delete chat history with the workspace** on, `run` also deletes Claude Code and Codex chats from workspaces that no longer exist. Rules are set in Orca settings; these commands never change them. Add `--environment <id>` to run them on a paired server.
## Ports
@@ -123,17 +123,25 @@ export async function deleteHostAiVaultSessionsPermanently(
failed += 1
}
}
if (deletedPaths.length > 0) {
remoteDeleteDeps.invalidateMultiHostListCache?.()
invalidateAiVaultSessionListCache()
for (const path of deletedPaths) {
invalidateSessionParseCacheEntry(path)
}
await (remoteDeleteDeps.invalidateBackgroundCache ?? invalidateAiVaultBackgroundCache)(
deletedPaths
).catch((error) => {
console.warn('[ai-vault] background cache invalidation failed:', error)
})
}
await invalidateDeletedAiVaultSessionPaths(deletedPaths)
return { deleted: deletedPaths.length, failed, freedBytes }
}
/** After a permanent delete: every list and parse cache, so deleted rows cannot resurrect. */
export async function invalidateDeletedAiVaultSessionPaths(
deletedPaths: readonly string[]
): Promise<void> {
if (deletedPaths.length === 0) {
return
}
remoteDeleteDeps.invalidateMultiHostListCache?.()
invalidateAiVaultSessionListCache()
for (const path of deletedPaths) {
invalidateSessionParseCacheEntry(path)
}
await (remoteDeleteDeps.invalidateBackgroundCache ?? invalidateAiVaultBackgroundCache)([
...deletedPaths
]).catch((error) => {
console.warn('[ai-vault] background cache invalidation failed:', error)
})
}
@@ -31,6 +31,7 @@ import type {
CodexSessionBackfillPaths,
CodexSessionBackfillSummary
} from './codex-session-backfill-types'
import { linkCodexRolloutUnlessHeld } from '../rollouts/codex-rollout-deletion-guard'
let backgroundBackfillTask: Promise<CodexSessionBackfillSummary | null> | null = null
@@ -240,7 +241,14 @@ async function backfillOneManagedSessionFile(
ensuredTargetDirectories.add(targetDirectory)
}
linkAttempted = true
await link(managedSessionFilePath, systemSessionFilePath)
const linked = await linkCodexRolloutUnlessHeld(managedSessionFilePath, () =>
link(managedSessionFilePath, systemSessionFilePath)
)
if (linked === 'held') {
// Being deleted with its workspace; left uncertified so a kept rollout is retried.
summary.failedFiles += 1
return
}
summary.linkedFiles += 1
await auditPass.recordPublished(
summary,
@@ -0,0 +1,89 @@
import { readdir } from 'node:fs/promises'
import { homedir } from 'node:os'
import { dirname, isAbsolute, join } from 'node:path'
import type { GlobalSettings } from '../../../../shared/settings/global-settings-types'
import { normalizeRuntimePathForComparison } from '../../../../shared/file-access/cross-platform-path'
import { isDefinitiveAbsence } from '../../../../shared/errors/definitive-filesystem-absence'
import { parseWslUncPath } from '../../../../shared/file-access/wsl-paths'
import { configuredAdditionalCodexHomePaths } from '../../../ai-vault/discovery/ai-vault-scan-roots'
import { codexHomeSessionsDir } from '../../../ai-vault/discovery/session-scanner-roots'
import {
assertOwnedHostCodexManagedHomePath,
UntrustedManagedCodexHomeError
} from '../../../codex-accounts/managed-homes/host-codex-managed-home-ownership'
import { GUEST_CODEX_ACCOUNTS_ROOT_SEGMENTS } from '../../../codex-accounts/managed-homes/guest-codex-account-homes'
import {
getOrcaUserDataPath,
getSystemCodexHomePath,
resolveOrcaManagedCodexHomePath
} from '../../configuration/homes/codex-home-paths'
import { resolveHostCodexSessionSourceHome } from '../rollouts/codex-session-source-home'
/** Every Orca account home in a root; throws while one can't be read, since its copy may be in use. */
async function listAccountHomes(accountsRoot: string): Promise<string[]> {
let entries
try {
entries = await readdir(accountsRoot, { withFileTypes: true })
} catch (error) {
if (isDefinitiveAbsence(error)) {
return []
}
throw error
}
const homes: string[] = []
for (const entry of entries) {
if (!entry.isDirectory()) {
continue
}
const home = join(accountsRoot, entry.name, 'home')
try {
assertOwnedHostCodexManagedHomePath({
candidatePath: home,
managedAccountsRoot: accountsRoot,
systemCodexHomePath: getSystemCodexHomePath(),
expectedAccountId: entry.name
})
} catch (error) {
// Not Orca's (redirected or never set up): Orca neither launches nor links into it.
if (error instanceof UntrustedManagedCodexHomeError) {
continue
}
throw error
}
homes.push(home)
}
return homes
}
/**
* Every host Codex home a rollout can have a name in, since history passes link it across all of
* them: the user's, a custom history source, Orca's shared home and each account's. A WSL distro
* keeps its own homes, and reading them can boot it.
*/
export async function listHostCodexRolloutHomes(
settings: Pick<GlobalSettings, 'codexSessionSourceHome'>
): Promise<string[]> {
const candidates = [
dirname(codexHomeSessionsDir()),
getSystemCodexHomePath(),
resolveHostCodexSessionSourceHome(settings),
resolveOrcaManagedCodexHomePath(),
...(await listAccountHomes(join(getOrcaUserDataPath(), 'codex-accounts'))),
// A headless host keeps its own accounts under the user's home.
...(await listAccountHomes(join(homedir(), ...GUEST_CODEX_ACCOUNTS_ROOT_SEGMENTS))),
...configuredAdditionalCodexHomePaths()
]
const seen = new Set<string>()
const homes: string[] = []
for (const home of candidates) {
if (!home || !isAbsolute(home) || parseWslUncPath(home)) {
continue
}
const key = normalizeRuntimePathForComparison(home)
if (!seen.has(key)) {
seen.add(key)
homes.push(home)
}
}
return homes
}
@@ -0,0 +1,279 @@
import { lstat, realpath, rm, stat, unlink } from 'node:fs/promises'
import { basename, dirname, join } from 'node:path'
import type { AiVaultAgent } from '../../../../shared/ai-vault/contracts/ai-vault-types'
import { isPathInsideOrEqual } from '../../../../shared/file-access/cross-platform-path'
import { invalidateDeletedAiVaultSessionPaths } from '../../../ai-vault/deletion/host-session-delete'
import { isDefinitiveAbsence } from '../../../../shared/errors/definitive-filesystem-absence'
import { resolveOrcaManagedCodexHomePath } from '../../configuration/homes/codex-home-paths'
import { codexDatedRolloutRelativePath } from '../resume/codex-session-resume-home'
import { holdCodexRolloutForDeletion } from '../rollouts/codex-rollout-deletion-guard'
type RolloutTarget = { agent: AiVaultAgent; filePath: string }
type DeleteResult = { deleted: number; failed: number; freedBytes: number }
type RolloutName = { path: string; root: string }
const UUID_PATTERN = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g
/** One name as found: what it reads (a link's target), and enough to tell if it changed. */
type NameState = {
name: RolloutName
path: string
isHardLink: boolean
/** dev:ino of the file it reads; null for a dangling link. */
content: string | null
version: string
size: number
nlink: bigint
}
/** The `YYYY/MM/DD/rollout-*.jsonl` stem in one of these homes; archived `.zst` maps to its `.jsonl`. */
function rolloutStem(homes: readonly string[], filePath: string): string | null {
for (const home of homes) {
const relativePath = codexDatedRolloutRelativePath(join(home, 'sessions'), filePath)
if (relativePath) {
return relativePath.replace(/\.zst$/, '')
}
}
return null
}
/** Codex compresses idle rollouts and history passes link them across homes, so match by name. */
function rolloutNames(homes: readonly string[], stem: string): RolloutName[] {
const parts = stem.split('/')
const fileName = parts.at(-1) ?? stem
return homes.flatMap((home) => {
const sessions = join(home, 'sessions')
const archived = join(home, 'archived_sessions')
return [
{ path: join(sessions, ...parts), root: sessions },
{ path: `${join(sessions, ...parts)}.zst`, root: sessions },
{ path: join(archived, fileName), root: archived },
{ path: `${join(archived, fileName)}.zst`, root: archived }
]
})
}
/** Null when absent; throws when it can't be proven absent, is no file, or leaves its home. */
async function readName(name: RolloutName): Promise<NameState | null> {
let entry
try {
entry = await lstat(name.path, { bigint: true })
} catch (error) {
if (isDefinitiveAbsence(error)) {
return null
}
throw error
}
if (!entry.isFile() && !entry.isSymbolicLink()) {
throw new Error(`Not a rollout file: ${name.path}`)
}
// A dated folder linked elsewhere puts the name outside this home.
const [realFolder, realRoot] = await Promise.all([
realpath(dirname(name.path)),
realpath(name.root)
])
if (!isPathInsideOrEqual(realRoot, realFolder)) {
throw new Error(`Rollout outside its Codex home: ${name.path}`)
}
const target = entry.isSymbolicLink()
? await stat(name.path, { bigint: true }).catch((error: unknown) => {
if (isDefinitiveAbsence(error)) {
return null
}
throw error
})
: entry
return {
name,
path: name.path,
isHardLink: entry.isFile(),
// Some filesystems report inode 0 for every file: those names are checked one by one.
content: target
? target.ino === 0n
? `path:${name.path}`
: `${target.dev}:${target.ino}`
: null,
version: [
entry.ino,
entry.size,
entry.mtimeNs,
target?.ino,
target?.size,
target?.mtimeNs
].join(':'),
size: Number(target?.size ?? 0n),
nlink: entry.nlink
}
}
async function readNames(names: readonly RolloutName[]): Promise<NameState[]> {
const states: NameState[] = []
for (const name of names) {
const state = await readName(name)
if (state) {
states.push(state)
}
}
return states
}
async function removeName(path: string): Promise<boolean> {
try {
// Unlink only ever removes the name: never a folder, never a link's target.
await unlink(path)
return true
} catch (error) {
if (isDefinitiveAbsence(error)) {
return false
}
throw error
}
}
/** Space returns only when a file's last link goes, so each file counts once and only then. */
function freedBytesOf(removed: readonly NameState[]): number {
const linksByContent = new Map<string, { state: NameState; removed: number }>()
for (const state of removed) {
if (state.isHardLink && state.content) {
const tally = linksByContent.get(state.content) ?? { state, removed: 0 }
tally.removed += 1
linksByContent.set(state.content, tally)
}
}
let bytes = 0
for (const { state, removed: count } of linksByContent.values()) {
if (BigInt(count) >= state.nlink) {
bytes += state.size
}
}
return bytes
}
/**
* Codex holds `thread-writer-locks/<thread id>.lock` while a process has the thread open, also
* after a resume that hasn't written a turn yet; deleting then would cut off every later turn.
* Codex versions that keep no locks give no such proof, so their rollouts are kept.
*/
async function isOpenInCodex(homes: readonly string[], stem: string): Promise<boolean> {
// A reverted thread's name carries its thread id and its rollout id: either can be the lock's.
const ids = basename(stem).toLowerCase().match(UUID_PATTERN) ?? []
if (ids.length === 0) {
return true
}
let keepsLocks = false
for (const home of homes) {
const locks = join(home, 'thread-writer-locks')
for (const id of ids) {
try {
await lstat(join(locks, `${id}.lock`))
return true
} catch (error) {
if (!isDefinitiveAbsence(error)) {
return true
}
}
}
keepsLocks ||= await lstat(locks).then(
(entry) => entry.isDirectory(),
() => false
)
}
return !keepsLocks
}
async function deleteRollout(
target: RolloutTarget,
listHomes: () => Promise<readonly string[]>,
shouldDelete: (target: RolloutTarget) => Promise<boolean>,
result: DeleteResult,
deletedPaths: string[]
): Promise<void> {
const release = await holdCodexRolloutForDeletion(target.filePath)
try {
// Listed under the hold: an account added since the sweep began may already hold a link.
const homes = await listHomes()
const stem = rolloutStem(homes, target.filePath)
if (!stem) {
result.failed += 1
return
}
const names = rolloutNames(homes, stem)
if (await isOpenInCodex(homes, stem)) {
return
}
const found = await readNames(names)
// Every name, every extension: a chat resumed or still written anywhere keeps them all.
const checked = new Set<string>()
for (const state of found) {
if (state.content === null || checked.has(state.content)) {
continue
}
checked.add(state.content)
if (!(await shouldDelete({ agent: 'codex', filePath: state.path }))) {
return
}
}
if (checked.size === 0) {
return
}
// Reading takes a while: a name that appeared or changed meanwhile means the chat is in use.
const current = await readNames(names)
const versions = new Map(found.map((state) => [state.path, state.version]))
if (
current.length !== found.length ||
current.some((state) => versions.get(state.path) !== state.version)
) {
return
}
const removed: NameState[] = []
// Links first: removing a link's target first would read as the link having changed.
const order = [...found].sort((a, b) => Number(a.isHardLink) - Number(b.isHardLink))
try {
for (const { name } of order) {
const state = await readName(name)
if (!state) {
continue
}
// Checked once more right before its own unlink: a resume opens or writes one name.
if (state.version !== versions.get(name.path) || (await isOpenInCodex(homes, stem))) {
return
}
if (await removeName(state.path)) {
removed.push(state)
deletedPaths.push(state.path)
}
}
} finally {
result.freedBytes += freedBytesOf(removed)
}
result.deleted += 1
// A name another process links meanwhile is a fresh candidate for the next sweep's full checks.
await rm(join(resolveOrcaManagedCodexHomePath(), '.orca-session-copies', `${stem}.json`), {
force: true
}).catch(() => undefined)
} catch (error) {
console.warn('[workspace-cleanup] Failed to delete Codex rollout:', target.filePath, error)
result.failed += 1
} finally {
release()
}
}
/**
* Deletes each Codex rollout under every name it has in the listed homes, for good. `shouldDelete` is
* asked once per distinct file right before removal; false keeps every name of that rollout.
*/
export async function deleteCodexRolloutsPermanently(
targets: readonly RolloutTarget[],
shouldDelete: (target: RolloutTarget) => Promise<boolean>,
listHomes: () => Promise<readonly string[]>
): Promise<DeleteResult> {
const result: DeleteResult = { deleted: 0, failed: 0, freedBytes: 0 }
const deletedPaths: string[] = []
for (const target of targets) {
await deleteRollout(target, listHomes, shouldDelete, result, deletedPaths)
}
await invalidateDeletedAiVaultSessionPaths(deletedPaths)
return result
}
@@ -21,6 +21,7 @@ import {
} from '../backfill/codex-session-backfill-copy'
import { resolveCodexSessionBackfillPaths } from '../backfill/codex-session-backfill'
import { codexDatedRolloutRelativePath } from './codex-session-resume-home'
import { linkCodexRolloutUnlessHeld } from '../rollouts/codex-rollout-deletion-guard'
import { ManagedCodexHomeTemporarilyUnavailableError } from '../../../codex-accounts/managed-homes/host-codex-managed-home-ownership'
const RETRYABLE_RESUME_ERROR =
@@ -167,6 +168,35 @@ async function materializeLegacyRollout(
if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) {
throw new Error('Legacy rollout source is not a regular file.')
}
// A cleanup deleting every name of this rollout would miss one installed meanwhile.
if (
(await linkCodexRolloutUnlessHeld(sourcePath, () => installRollout(sourcePath, targetPath))) ===
'held'
) {
throw new Error('This rollout is being deleted with its workspace.')
}
const summary = {
stopped: false,
scannedFiles: 1,
linkedFiles: 0,
copiedFiles: 0,
skippedExistingFiles: 0,
skippedUnexpectedFiles: 0,
skippedSymlinkFiles: 0,
skippedUnsupportedFilesystemFiles: 0,
failedDirectories: 0,
failedFiles: 0,
failedHealAuditRecords: 0
}
await appendCodexSessionHealAuditRecord(
createCodexSessionBackfillAuditWriter(auditLogPath),
summary,
{ action: 'targeted-resume', source: sourcePath, target: targetPath }
)
}
async function installRollout(sourcePath: string, targetPath: string): Promise<void> {
await mkdir(dirname(targetPath), { recursive: true })
try {
await link(sourcePath, targetPath)
@@ -190,25 +220,6 @@ async function materializeLegacyRollout(
}
}
}
const summary = {
stopped: false,
scannedFiles: 1,
linkedFiles: 0,
copiedFiles: 0,
skippedExistingFiles: 0,
skippedUnexpectedFiles: 0,
skippedSymlinkFiles: 0,
skippedUnsupportedFilesystemFiles: 0,
failedDirectories: 0,
failedFiles: 0,
failedHealAuditRecords: 0
}
await appendCodexSessionHealAuditRecord(
createCodexSessionBackfillAuditWriter(auditLogPath),
summary,
{ action: 'targeted-resume', source: sourcePath, target: targetPath }
)
}
async function assertMatchingExistingTarget(sourcePath: string, targetPath: string): Promise<void> {
@@ -0,0 +1,66 @@
import { basename } from 'node:path'
// Rollout names a cleanup is deleting, counted per concurrent hold.
const heldRollouts = new Map<string, number>()
// Async links that give a rollout a new name, so a hold can wait for ones already started.
const linksInFlight = new Map<string, Set<Promise<unknown>>>()
/** Archived `.jsonl.zst` and live `.jsonl` names are one rollout. */
function rolloutKey(path: string): string {
const name = basename(path)
return name.endsWith('.zst') ? name.slice(0, -'.zst'.length) : name
}
export function isCodexRolloutHeldForDeletion(path: string): boolean {
return heldRollouts.size > 0 && heldRollouts.has(rolloutKey(path))
}
/** Runs an async link of this rollout unless a cleanup holds it; a hold waits for it to settle. */
export async function linkCodexRolloutUnlessHeld<T>(
sourcePath: string,
createLink: () => Promise<T>
): Promise<T | 'held'> {
const key = rolloutKey(sourcePath)
if (heldRollouts.has(key)) {
return 'held'
}
const pending = createLink()
const inFlight = linksInFlight.get(key) ?? new Set()
linksInFlight.set(key, inFlight)
inFlight.add(pending)
try {
return await pending
} finally {
inFlight.delete(pending)
if (inFlight.size === 0) {
linksInFlight.delete(key)
}
}
}
/**
* Stops history passes from giving a rollout a new name while every name it has is deleted, once
* links already under way have landed theirs. Synchronous links check the hold in the same tick.
*/
export async function holdCodexRolloutForDeletion(path: string): Promise<() => void> {
const key = rolloutKey(path)
heldRollouts.set(key, (heldRollouts.get(key) ?? 0) + 1)
let released = false
const release = (): void => {
if (released) {
return
}
released = true
const remaining = (heldRollouts.get(key) ?? 1) - 1
if (remaining > 0) {
heldRollouts.set(key, remaining)
} else {
heldRollouts.delete(key)
}
}
const inFlight = linksInFlight.get(key)
if (inFlight) {
await Promise.allSettled(Array.from(inFlight))
}
return release
}
@@ -0,0 +1,68 @@
import { lstatSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { holdCodexRolloutForDeletion } from './codex-rollout-deletion-guard'
import { linkCodexSessionFile, linkCodexSessionFileAsync } from './codex-session-link'
const NAME = 'rollout-2026-11-01T10-00-00-00000001-0000-4000-8000-000000000000.jsonl'
let root: string
afterEach(() => {
rmSync(root, { recursive: true, force: true })
})
function hasEntry(path: string): boolean {
try {
lstatSync(path)
return true
} catch {
return false
}
}
describe('Codex session links', () => {
it('leaves no dangling link when the source was deleted after it was listed', async () => {
root = mkdtempSync(join(tmpdir(), 'orca-codex-link-'))
const source = join(root, 'source', NAME)
expect(linkCodexSessionFile(source, join(root, 'sync.jsonl'))).toBe(false)
expect(
await linkCodexSessionFileAsync(source, join(root, 'async.jsonl'), { hardlinkOnly: false })
).toBe('failed')
expect([join(root, 'sync.jsonl'), join(root, 'async.jsonl')].filter(hasEntry)).toEqual([])
})
it('gives a rollout no new name while it is held for deletion', async () => {
root = mkdtempSync(join(tmpdir(), 'orca-codex-link-'))
const source = join(root, NAME)
writeFileSync(source, '{}\n')
const release = await holdCodexRolloutForDeletion(`${source}.zst`)
expect(linkCodexSessionFile(source, join(root, 'sync.jsonl'))).toBe(false)
expect(
await linkCodexSessionFileAsync(source, join(root, 'async.jsonl'), { hardlinkOnly: false })
).toBe('failed')
release()
expect(
await linkCodexSessionFileAsync(source, join(root, 'after.jsonl'), { hardlinkOnly: false })
).toBe('linked')
expect([join(root, 'sync.jsonl'), join(root, 'async.jsonl')].filter(hasEntry)).toEqual([])
})
it('waits for a link already under way before a hold takes effect', async () => {
root = mkdtempSync(join(tmpdir(), 'orca-codex-link-'))
const source = join(root, NAME)
writeFileSync(source, '{}\n')
const linking = linkCodexSessionFileAsync(source, join(root, 'linked.jsonl'), {
hardlinkOnly: false
})
const release = await holdCodexRolloutForDeletion(source)
// The deleter lists names only now, so the new one must already be there to be seen.
expect(hasEntry(join(root, 'linked.jsonl'))).toBe(true)
release()
expect(await linking).toBe('linked')
})
})
@@ -1,19 +1,39 @@
import { linkSync, symlinkSync } from 'node:fs'
import { link, symlink } from 'node:fs/promises'
import {
isCodexRolloutHeldForDeletion,
linkCodexRolloutUnlessHeld
} from './codex-rollout-deletion-guard'
export function tryHardlinkCodexSessionFile(sourcePath: string, targetPath: string): boolean {
function errorCode(error: unknown): unknown {
return typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined
}
function hardlinkCodexSessionFile(
sourcePath: string,
targetPath: string
): 'linked' | 'source-missing' | 'failed' {
if (isCodexRolloutHeldForDeletion(sourcePath)) {
return 'failed'
}
try {
// Codex resume ignores symlinked JSONL sessions; hardlinks keep one resumable log.
linkSync(sourcePath, targetPath)
return true
} catch {
return false
return 'linked'
} catch (error) {
return errorCode(error) === 'ENOENT' ? 'source-missing' : 'failed'
}
}
export function tryHardlinkCodexSessionFile(sourcePath: string, targetPath: string): boolean {
return hardlinkCodexSessionFile(sourcePath, targetPath) === 'linked'
}
export function linkCodexSessionFile(sourcePath: string, targetPath: string): boolean {
if (tryHardlinkCodexSessionFile(sourcePath, targetPath)) {
return true
const hardlink = hardlinkCodexSessionFile(sourcePath, targetPath)
// A held source, or one deleted since it was listed, must not get a (dangling) symlink.
if (hardlink !== 'failed' || isCodexRolloutHeldForDeletion(sourcePath)) {
return hardlink === 'linked'
}
try {
// Cross-volume hardlinks fail; symlinks still prevent copy divergence.
@@ -30,14 +50,30 @@ export async function linkCodexSessionFileAsync(
sourcePath: string,
targetPath: string,
options: { hardlinkOnly: boolean }
): Promise<'linked' | 'existing' | 'skipped' | 'failed'> {
const outcome = await linkCodexRolloutUnlessHeld(sourcePath, () =>
linkOrSymlink(sourcePath, targetPath, options)
)
return outcome === 'held' ? 'failed' : outcome
}
async function linkOrSymlink(
sourcePath: string,
targetPath: string,
options: { hardlinkOnly: boolean }
): Promise<'linked' | 'existing' | 'skipped' | 'failed'> {
try {
await link(sourcePath, targetPath)
return 'linked'
} catch (error) {
if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'EEXIST') {
const code = errorCode(error)
if (code === 'EEXIST') {
return 'existing'
}
// A source deleted since it was listed would leave a dangling symlink.
if (code === 'ENOENT') {
return 'failed'
}
}
if (options.hardlinkOnly) {
// A symlink would be ignored by resume and dangle once its account goes.
@@ -124,6 +124,7 @@ export type RuntimeStore = {
agentWorkspaceTrustEnabled?: GlobalSettings['agentWorkspaceTrustEnabled']
codexManagedAccounts?: GlobalSettings['codexManagedAccounts']
codexShareHistoryAcrossAccounts?: GlobalSettings['codexShareHistoryAcrossAccounts']
codexSessionSourceHome?: GlobalSettings['codexSessionSourceHome']
deleteChatHistoryWithWorkspace?: GlobalSettings['deleteChatHistoryWithWorkspace']
nestedWorkerMaxDepth?: GlobalSettings['nestedWorkerMaxDepth']
orchestrationWorkerAutoReleaseEnabled?: GlobalSettings['orchestrationWorkerAutoReleaseEnabled']
@@ -0,0 +1,74 @@
import { createReadStream } from 'node:fs'
import {
isZstdTranscriptPath,
readZstdTranscriptSlice,
zstdTranscriptStream
} from '../../../native-chat/transcript-streaming/transcript-zstd-decompression'
import { isStillIdleInGoneFolder, readLastRecordedCwd } from './transcript-last-cwd'
// Archived rollouts measured up to 32 MB unpacked; a larger one is kept rather than held in memory.
const MAX_UNPACKED_BYTES = 64 * 1024 * 1024
const NEWLINE = 0x0a
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
/** Codex nests the cwd in `payload`: `session_meta` holds the start folder, `turn_context` each turn's. */
function codexRecordCwd(line: Buffer): string | null {
if (!line.includes('"cwd"')) {
return null
}
try {
const record: unknown = JSON.parse(line.toString('utf8'))
if (
!isObject(record) ||
(record.type !== 'session_meta' && record.type !== 'turn_context') ||
!isObject(record.payload)
) {
return null
}
return typeof record.payload.cwd === 'string' ? record.payload.cwd : null
} catch {
return null
}
}
/** `.jsonl.zst` can't be read from its end, so it is unpacked whole and read back from there. */
async function readLastArchivedRolloutCwd(filePath: string): Promise<string | null> {
const raw = createReadStream(filePath)
const unpacked = zstdTranscriptStream(raw)
try {
const text = await readZstdTranscriptSlice(unpacked, MAX_UNPACKED_BYTES + 1)
if (text.length > MAX_UNPACKED_BYTES) {
return null
}
for (let end = text.length; end > 0;) {
const start = text.lastIndexOf(NEWLINE, end - 1) + 1
const cwd = codexRecordCwd(text.subarray(start, end))
if (cwd !== null) {
return cwd
}
end = start - 1
}
return null
} finally {
unpacked.destroy()
raw.destroy()
}
}
function readLastRolloutCwd(filePath: string): Promise<string | null> {
return isZstdTranscriptPath(filePath)
? readLastArchivedRolloutCwd(filePath)
: readLastRecordedCwd(filePath, codexRecordCwd)
}
/** Re-read right before deletion: idle, and its last turn ran in the gone folder, not where it was resumed. */
export function isCodexRolloutStillIdleInGoneFolder(
filePath: string,
folderKey: string,
now: number
): Promise<boolean> {
return isStillIdleInGoneFolder(filePath, folderKey, now, readLastRolloutCwd)
}
@@ -178,7 +178,6 @@ describe('sweepDeletedWorkspaceChatHistory', () => {
session('archived.jsonl', join(appWorkspaces, 'archived')),
session('recent.jsonl', gone, { modifiedAt: TEN_MINUTES_AGO }),
session('outside.jsonl', join(root, 'elsewhere', 'gone')),
session('codex.jsonl', gone, { agent: 'codex' }),
session('server.jsonl', gone, { executionHostId: 'runtime:env-1' }),
session('unmounted.jsonl', join(root, 'unmounted', 'other', 'feature')),
session('renamed.jsonl', join(appWorkspaces, 'old-name')),
@@ -23,6 +23,10 @@ import {
type GoneFolder
} from './deleted-workspace-folders'
import { isChatStillIdleInGoneFolder } from './transcript-last-cwd'
import { isCodexRolloutStillIdleInGoneFolder } from './codex-rollout-last-cwd'
import { parseWslUncPath } from '../../../../shared/file-access/wsl-paths'
import { deleteCodexRolloutsPermanently } from '../../../codex/history/cleanup/codex-rollout-permanent-delete'
import { listHostCodexRolloutHomes } from '../../../codex/history/cleanup/codex-host-rollout-homes'
export type ChatHistorySweepResult = { deleted: number; failed: number; freedBytes: number }
@@ -44,16 +48,19 @@ export type ChatHistorySweepDeps = {
}
/**
* Agents whose transcripts record the cwd on every message, so a chat resumed in another workspace
* shows it. Agents that record it once (Pi, OMP, Copilot, Cursor) can't prove that and are kept.
* Agents whose transcripts record the cwd on every message (Claude) or turn (Codex), so a chat
* resumed in another workspace shows it. Agents that record it once (Pi, OMP, Copilot, Cursor)
* can't prove that and are kept.
*/
const SWEPT_AGENTS: ReadonlySet<AiVaultAgent> = new Set(['claude'])
const SWEPT_AGENTS: ReadonlySet<AiVaultAgent> = new Set(['claude', 'codex'])
function isSweepableSession(session: AiVaultSession, now: number): boolean {
const modifiedAt = Date.parse(session.modifiedAt)
return (
normalizeExecutionHostId(session.executionHostId) === LOCAL_EXECUTION_HOST_ID &&
SWEPT_AGENTS.has(session.agent) &&
// A WSL distro's history is its own to clean, and reading it can boot the distro.
!parseWslUncPath(session.filePath) &&
// Recently written history may belong to a workspace still in use or being recreated.
Number.isFinite(modifiedAt) &&
now - modifiedAt >= WORKSPACE_CLEANUP_RULE_GRACE_MS
@@ -158,7 +165,11 @@ export async function sweepDeletedWorkspaceChatHistory(
targets,
// The slow transcript reads first: the cheap folder and row checks then run last, nearest the rm.
async (target) =>
(await isChatStillIdleInGoneFolder(target.filePath, key, Date.now())) &&
(await (
target.agent === 'codex'
? isCodexRolloutStillIdleInGoneFolder
: isChatStillIdleInGoneFolder
)(target.filePath, key, Date.now())) &&
!deps.signal?.aborted &&
deps.isEnabled() &&
(await isStillGone(folder)) &&
@@ -188,7 +199,26 @@ export function deleteChatHistoryOfDeletedWorkspaces(
{ signal: scanSignal }
)
).sessions,
deleteSessions: deleteHostAiVaultSessionsPermanently,
deleteSessions: async (targets, shouldDelete) => {
const isCodex = (target: ChatHistoryTarget): boolean => target.agent === 'codex'
const others = targets.filter((target) => !isCodex(target))
const codex = targets.filter(isCodex)
const empty: ChatHistorySweepResult = { deleted: 0, failed: 0, freedBytes: 0 }
const swept =
others.length > 0 ? await deleteHostAiVaultSessionsPermanently(others, shouldDelete) : empty
// AI Vault lists one name per rollout and refuses Codex deletes: links would bring it back.
const rollouts =
codex.length > 0
? await deleteCodexRolloutsPermanently(codex, shouldDelete, () =>
listHostCodexRolloutHomes(store.getSettings())
)
: empty
return {
deleted: swept.deleted + rollouts.deleted,
failed: swept.failed + rollouts.failed,
freedBytes: swept.freedBytes + rollouts.freedBytes
}
},
isEnabled: () => store.getSettings().deleteChatHistoryWithWorkspace === true
})
}
@@ -0,0 +1,206 @@
import {
linkSync,
lstatSync,
mkdirSync,
mkdtempSync,
rmSync,
statSync,
symlinkSync,
utimesSync,
writeFileSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { zstdCompressSync } from 'node:zlib'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { AiVaultSession } from '../../../../shared/ai-vault/contracts/ai-vault-types'
import type { RuntimeStore } from '../../../runtime/construction/runtime-store-contract'
import { deleteCodexRolloutsPermanently } from '../../../codex/history/cleanup/codex-rollout-permanent-delete'
import { sweepDeletedWorkspaceChatHistory } from './deleted-workspace-chat-history'
// Fixed and long past: the sweep's own idle check reads the clock, and these files are older than any run.
const WRITTEN = new Date('2026-01-01T12:00:00.000Z')
const NOW = Date.parse('2026-01-02T12:00:00.000Z')
const NAME = (id: string): string =>
`rollout-2026-11-01T10-00-00-0000000${id}-0000-4000-8000-000000000000.jsonl`
const DATED = ['sessions', '2026', '11', '01']
let root: string
afterEach(() => {
vi.unstubAllEnvs()
rmSync(root, { recursive: true, force: true })
})
/** A Codex rollout: the start folder, one turn per later cwd, then a long reply with no cwd. */
function rollout(startCwd: string, turnCwds: string[] = []): string {
const records = [
{ type: 'session_meta', payload: { id: 'thread', cwd: startCwd } },
...turnCwds.map((cwd) => ({ type: 'turn_context', payload: { cwd } })),
// Tool calls name other folders; only session_meta and turn_context records count.
{ type: 'event_msg', payload: { type: 'exec', cwd: startCwd, text: 'x'.repeat(300 * 1024) } }
]
return `${records.map((record) => JSON.stringify(record)).join('\n')}\n`
}
function write(path: string, contents: string | Buffer): string {
mkdirSync(dirname(path), { recursive: true })
writeFileSync(path, contents)
utimesSync(path, WRITTEN, WRITTEN)
return path
}
describe('sweepDeletedWorkspaceChatHistory with Codex rollouts', () => {
// Creating symlinks on Windows needs Developer Mode or admin rights.
it.skipIf(process.platform === 'win32')(
'deletes every name a rollout has across Codex homes unless any copy ran elsewhere',
async () => {
root = mkdtempSync(join(tmpdir(), 'orca-codex-history-'))
vi.stubEnv('ORCA_USER_DATA_PATH', join(root, 'user-data'))
const appWorkspaces = join(root, 'workspaces', 'app')
mkdirSync(join(appWorkspaces, 'live'), { recursive: true })
mkdirSync(join(root, 'repos', 'app'), { recursive: true })
const gone = join(appWorkspaces, 'gone')
const live = join(appWorkspaces, 'live')
const system = join(root, 'codex')
const managed = join(root, 'user-data', 'codex-runtime-home', 'home')
const account = join(root, 'user-data', 'codex-accounts', 'a1', 'home')
const homes = [system, managed, account]
// Shared across homes by hardlink, archived under the account, and a stale link in the mirror.
const shared = write(join(system, ...DATED, NAME('1')), rollout(gone, [gone]))
mkdirSync(join(managed, ...DATED), { recursive: true })
linkSync(shared, join(managed, ...DATED, NAME('1')))
const sharedPacked = write(
join(account, ...DATED, `${NAME('1')}.zst`),
zstdCompressSync(rollout(gone, [gone]))
)
const sharedArchived = write(join(account, 'archived_sessions', NAME('1')), rollout(gone))
symlinkSync(join(root, 'missing'), join(managed, ...DATED, `${NAME('1')}.zst`))
const marker = write(
join(managed, '.orca-session-copies', '2026', '11', '01', `${NAME('1')}.json`),
'{}'
)
// Codex compressed the account's copy, breaking the link, and that copy was resumed in `live`.
const resumed = write(join(system, ...DATED, NAME('2')), rollout(gone, [gone]))
const resumedPacked = write(
join(account, ...DATED, `${NAME('2')}.zst`),
zstdCompressSync(rollout(gone, [gone, live]))
)
// Archived by Codex before it ever ran a turn, and hardlinked into a backup Orca doesn't know.
const packedOnly = write(
join(system, ...DATED, `${NAME('3')}.zst`),
zstdCompressSync(rollout(gone))
)
mkdirSync(join(root, 'backup'))
linkSync(packedOnly, join(root, 'backup', 'rollout.zst'))
// A cross-volume bridge's symlink to it: removing the target first must not read as a change.
const packedLink = join(account, ...DATED, `${NAME('3')}.zst`)
symlinkSync(packedOnly, packedLink)
// A reverted thread's rollout, named by thread id and rollout id.
const reverted = write(
join(
system,
...DATED,
NAME('6').replace('.jsonl', '_00000006-0000-4000-8000-000000000001.jsonl')
),
rollout(gone, [gone])
)
// Resumed under an account and still open there, with no turn written yet.
const open = write(join(system, ...DATED, NAME('4')), rollout(gone, [gone]))
write(join(account, 'thread-writer-locks', '00000004-0000-4000-8000-000000000000.lock'), '')
// Space returns only for files whose every link went; the backup keeps the last one's.
const freed =
statSync(shared).size +
statSync(sharedPacked).size +
statSync(sharedArchived).size +
statSync(reverted).size
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the sweep reads only these store methods
const store = {
getSettings: () => ({
workspaceDir: join(root, 'workspaces'),
nestWorkspaces: true,
workspaceDirHistory: []
}),
getRepos: () => [
{
id: 'app',
path: join(root, 'repos', 'app'),
displayName: 'app',
badgeColor: '',
addedAt: 0
}
],
getAllWorktreeMeta: () => ({}),
getFolderWorkspaces: () => []
} as unknown as RuntimeStore
// AI Vault lists one name per rollout.
const listed = [shared, resumed, packedOnly, reverted, open].map(
(filePath) =>
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the sweep reads only the fields set here
({
executionHostId: 'local',
agent: 'codex',
sessionId: filePath,
cwd: gone,
filePath,
modifiedAt: WRITTEN.toISOString()
}) as AiVaultSession
)
const result = await sweepDeletedWorkspaceChatHistory({
store,
now: NOW,
listSessions: async () => listed,
isEnabled: () => true,
deleteSessions: (targets, shouldDelete) =>
deleteCodexRolloutsPermanently(targets, shouldDelete, async () => homes)
})
expect(
[
shared,
join(managed, ...DATED, NAME('1')),
sharedPacked,
sharedArchived,
join(managed, ...DATED, `${NAME('1')}.zst`),
marker,
packedOnly,
packedLink,
reverted
].filter(exists)
).toEqual([])
expect([resumed, resumedPacked, open].filter(exists)).toEqual([resumed, resumedPacked, open])
expect(result).toEqual({ deleted: 3, failed: 0, freedBytes: freed })
// A Codex that keeps no writer locks gives no proof a chat isn't open, so its chats stay.
rmSync(join(account, 'thread-writer-locks'), { recursive: true })
const lockless = write(join(system, ...DATED, NAME('5')), rollout(gone, [gone]))
const locklessRun = await sweepDeletedWorkspaceChatHistory({
store,
now: NOW,
listSessions: async () => [{ ...listed[0], filePath: lockless }],
isEnabled: () => true,
deleteSessions: (targets, shouldDelete) =>
deleteCodexRolloutsPermanently(targets, shouldDelete, async () => homes)
})
expect(exists(lockless)).toBe(true)
expect(locklessRun).toEqual({ deleted: 0, failed: 0, freedBytes: 0 })
}
)
})
/** Dangling links count: they block the name for later links. */
function exists(path: string): boolean {
try {
lstatSync(path)
return true
} catch {
return false
}
}
@@ -21,8 +21,11 @@ function topLevelCwd(line: Buffer): string | null {
}
}
/** The last top-level `cwd` a JSONL transcript recorded, reading whole records back from its end. */
async function readLastRecordedCwd(filePath: string): Promise<string | null> {
/** The last cwd a JSONL transcript recorded, reading whole records back from its end. */
export async function readLastRecordedCwd(
filePath: string,
recordCwd: (line: Buffer) => string | null = topLevelCwd
): Promise<string | null> {
const handle = await open(filePath, 'r')
try {
const { size } = await handle.stat()
@@ -39,7 +42,7 @@ async function readLastRecordedCwd(filePath: string): Promise<string | null> {
continue
}
const head = chunk.subarray(index + 1, lineEnd)
const cwd = topLevelCwd(pieces.length > 0 ? Buffer.concat([head, ...pieces]) : head)
const cwd = recordCwd(pieces.length > 0 ? Buffer.concat([head, ...pieces]) : head)
if (cwd !== null) {
return cwd
}
@@ -48,7 +51,7 @@ async function readLastRecordedCwd(filePath: string): Promise<string | null> {
}
pieces.unshift(chunk.subarray(0, lineEnd))
if (start === 0) {
return topLevelCwd(Buffer.concat(pieces))
return recordCwd(Buffer.concat(pieces))
}
}
return null
@@ -64,14 +67,15 @@ async function readLastRecordedCwd(filePath: string): Promise<string | null> {
export async function isStillIdleInGoneFolder(
filePath: string,
folderKey: string,
now: number
now: number,
readLastCwd: (filePath: string) => Promise<string | null> = readLastRecordedCwd
): Promise<boolean> {
try {
if (now - (await stat(filePath)).mtimeMs < WORKSPACE_CLEANUP_RULE_GRACE_MS) {
return false
}
// No recorded location means no proof the chat stayed in the gone folder: keep it.
const lastCwd = await readLastRecordedCwd(filePath)
const lastCwd = await readLastCwd(filePath)
if (lastCwd === null) {
return false
}
@@ -106,7 +106,7 @@ export function WorkspaceCleanupChatHistorySetting({
<DialogDescription>
{t(
'components.settings.workspaceCleanup.chatHistory.confirmDescription',
"Orca will delete Claude Code chats from workspaces that no longer exist, including ones deleted before today. Chats from workspaces you still have are kept. Deleted chats can't be recovered."
"Orca will delete Claude Code and Codex chats from workspaces that no longer exist, including ones deleted before today. Chats from workspaces you still have are kept. Deleted chats can't be recovered."
)}
</DialogDescription>
</DialogHeader>
@@ -137,7 +137,7 @@ export const getWorkspaceCleanupSettingsSearchParts = createLocalizedCatalog(
),
description: translate(
'components.settings.workspaceCleanup.chatHistory.deleteWithWorkspaceDescription',
"Claude Code chats from deleted workspaces are removed automatically to free disk space. They can't be recovered."
"Claude Code and Codex chats from deleted workspaces are removed automatically to free disk space. They can't be recovered."
),
keywords: [
...translateSearchKeyword('components.settings.workspaceCleanup.search.chat', 'chat'),
+2 -2
View File
@@ -22740,9 +22740,9 @@
"updateFailed": "Couldn't update the setting on {{host}}.",
"unsupported": "Update Orca on {{host}} to use this setting there.",
"confirmTitle": "Delete chat history from deleted workspaces?",
"confirmDescription": "Orca will delete Claude Code chats from workspaces that no longer exist, including ones deleted before today. Chats from workspaces you still have are kept. Deleted chats can't be recovered.",
"confirmDescription": "Orca will delete Claude Code and Codex chats from workspaces that no longer exist, including ones deleted before today. Chats from workspaces you still have are kept. Deleted chats can't be recovered.",
"deleteWithWorkspace": "Delete chat history with the workspace",
"deleteWithWorkspaceDescription": "Claude Code chats from deleted workspaces are removed automatically to free disk space. They can't be recovered."
"deleteWithWorkspaceDescription": "Claude Code and Codex chats from deleted workspaces are removed automatically to free disk space. They can't be recovered."
}
},
"repository": {