prodex 0.2.115

OpenAI profile pooling and safe auto-rotate for Codex CLI and Claude Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
use super::*;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SharedCodexEntryKind {
    Directory,
    File,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct SharedCodexEntry {
    name: String,
    kind: SharedCodexEntryKind,
}

pub(crate) fn copy_codex_home(source: &Path, destination: &Path) -> Result<()> {
    if !source.is_dir() {
        bail!("copy source {} is not a directory", source.display());
    }

    if same_path(source, destination) {
        bail!("copy source and destination are the same path");
    }

    if destination.exists() && !dir_is_empty(destination)? {
        bail!(
            "destination {} already exists and is not empty",
            destination.display()
        );
    }

    create_codex_home_if_missing(destination)?;
    copy_directory_contents(source, destination)
}

pub(crate) fn copy_directory_contents(source: &Path, destination: &Path) -> Result<()> {
    for entry in fs::read_dir(source)
        .with_context(|| format!("failed to read directory {}", source.display()))?
    {
        let entry =
            entry.with_context(|| format!("failed to read entry in {}", source.display()))?;
        let source_path = entry.path();
        let destination_path = destination.join(entry.file_name());
        let file_type = entry
            .file_type()
            .with_context(|| format!("failed to read metadata for {}", source_path.display()))?;

        if file_type.is_dir() {
            create_codex_home_if_missing(&destination_path)?;
            copy_directory_contents(&source_path, &destination_path)?;
        } else if file_type.is_file() {
            fs::copy(&source_path, &destination_path).with_context(|| {
                format!(
                    "failed to copy {} to {}",
                    source_path.display(),
                    destination_path.display()
                )
            })?;
        } else if file_type.is_symlink() {
            #[cfg(unix)]
            {
                let target = fs::read_link(&source_path)
                    .with_context(|| format!("failed to read symlink {}", source_path.display()))?;
                std::os::unix::fs::symlink(target, &destination_path).with_context(|| {
                    format!("failed to recreate symlink {}", destination_path.display())
                })?;
            }
            #[cfg(not(unix))]
            {
                bail!("symlinks are not supported on this platform");
            }
        }
    }

    Ok(())
}

pub(crate) fn prepare_managed_codex_home(paths: &AppPaths, codex_home: &Path) -> Result<()> {
    create_codex_home_if_missing(codex_home)?;
    migrate_legacy_shared_codex_root(paths)?;
    seed_legacy_default_codex_home(paths)?;
    fs::create_dir_all(&paths.shared_codex_root)
        .with_context(|| format!("failed to create {}", paths.shared_codex_root.display()))?;

    for entry in shared_codex_entries(paths, codex_home)? {
        ensure_shared_codex_entry(paths, codex_home, &entry)?;
    }

    Ok(())
}

fn seed_legacy_default_codex_home(paths: &AppPaths) -> Result<()> {
    if env::var_os("PRODEX_SHARED_CODEX_HOME").is_some() {
        return Ok(());
    }

    let legacy_root = legacy_default_codex_home()?;
    if same_path(&paths.shared_codex_root, &legacy_root) || !legacy_root.is_dir() {
        return Ok(());
    }

    fs::create_dir_all(&paths.shared_codex_root)
        .with_context(|| format!("failed to create {}", paths.shared_codex_root.display()))?;

    let mut entries = SHARED_CODEX_DIR_NAMES
        .iter()
        .map(|name| SharedCodexEntry {
            name: (*name).to_string(),
            kind: SharedCodexEntryKind::Directory,
        })
        .chain(SHARED_CODEX_FILE_NAMES.iter().map(|name| SharedCodexEntry {
            name: (*name).to_string(),
            kind: SharedCodexEntryKind::File,
        }))
        .collect::<Vec<_>>();

    let mut sqlite_entries = BTreeSet::new();
    collect_shared_codex_sqlite_entries(&legacy_root, &mut sqlite_entries)?;
    for name in sqlite_entries {
        entries.push(SharedCodexEntry {
            name,
            kind: SharedCodexEntryKind::File,
        });
    }

    for entry in entries {
        let legacy_path = legacy_root.join(&entry.name);
        let shared_path = paths.shared_codex_root.join(&entry.name);
        seed_shared_codex_entry(&legacy_path, &shared_path, entry.kind)?;
    }

    Ok(())
}

fn migrate_legacy_shared_codex_root(paths: &AppPaths) -> Result<()> {
    if same_path(&paths.shared_codex_root, &paths.legacy_shared_codex_root)
        || !paths.legacy_shared_codex_root.exists()
    {
        return Ok(());
    }

    fs::create_dir_all(&paths.shared_codex_root)
        .with_context(|| format!("failed to create {}", paths.shared_codex_root.display()))?;

    let mut entries = SHARED_CODEX_DIR_NAMES
        .iter()
        .map(|name| SharedCodexEntry {
            name: (*name).to_string(),
            kind: SharedCodexEntryKind::Directory,
        })
        .chain(SHARED_CODEX_FILE_NAMES.iter().map(|name| SharedCodexEntry {
            name: (*name).to_string(),
            kind: SharedCodexEntryKind::File,
        }))
        .collect::<Vec<_>>();

    let mut sqlite_entries = BTreeSet::new();
    collect_shared_codex_sqlite_entries(&paths.legacy_shared_codex_root, &mut sqlite_entries)?;
    for name in sqlite_entries {
        entries.push(SharedCodexEntry {
            name,
            kind: SharedCodexEntryKind::File,
        });
    }

    for entry in entries {
        let legacy_path = paths.legacy_shared_codex_root.join(&entry.name);
        let shared_path = paths.shared_codex_root.join(&entry.name);
        migrate_shared_codex_entry(&legacy_path, &shared_path, entry.kind)?;
    }

    Ok(())
}

fn shared_codex_entries(paths: &AppPaths, codex_home: &Path) -> Result<Vec<SharedCodexEntry>> {
    let mut entries = SHARED_CODEX_DIR_NAMES
        .iter()
        .map(|name| SharedCodexEntry {
            name: (*name).to_string(),
            kind: SharedCodexEntryKind::Directory,
        })
        .chain(SHARED_CODEX_FILE_NAMES.iter().map(|name| SharedCodexEntry {
            name: (*name).to_string(),
            kind: SharedCodexEntryKind::File,
        }))
        .collect::<Vec<_>>();

    let mut sqlite_entries = BTreeSet::new();
    let mut scan_roots = vec![paths.shared_codex_root.clone(), codex_home.to_path_buf()];
    scan_roots.sort();
    scan_roots.dedup();

    for root in scan_roots {
        collect_shared_codex_sqlite_entries(&root, &mut sqlite_entries)?;
    }

    for name in sqlite_entries {
        entries.push(SharedCodexEntry {
            name,
            kind: SharedCodexEntryKind::File,
        });
    }

    Ok(entries)
}

fn collect_shared_codex_sqlite_entries(root: &Path, names: &mut BTreeSet<String>) -> Result<()> {
    if !root.is_dir() {
        return Ok(());
    }

    for entry in fs::read_dir(root).with_context(|| format!("failed to read {}", root.display()))? {
        let entry = entry.with_context(|| format!("failed to read entry in {}", root.display()))?;
        let file_name = entry.file_name();
        let file_name = file_name.to_string_lossy();
        if is_shared_codex_sqlite_name(&file_name) {
            names.insert(file_name.into_owned());
        }
    }

    Ok(())
}

fn is_shared_codex_sqlite_name(file_name: &str) -> bool {
    SHARED_CODEX_SQLITE_PREFIXES
        .iter()
        .any(|prefix| file_name.starts_with(prefix))
        && SHARED_CODEX_SQLITE_SUFFIXES
            .iter()
            .any(|suffix| file_name.ends_with(suffix))
}

fn ensure_shared_codex_entry(
    paths: &AppPaths,
    codex_home: &Path,
    entry: &SharedCodexEntry,
) -> Result<()> {
    let local_path = codex_home.join(&entry.name);
    let shared_path = paths.shared_codex_root.join(&entry.name);
    if let Some(parent) = shared_path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }

    migrate_shared_codex_entry(&local_path, &shared_path, entry.kind)?;

    if entry.kind == SharedCodexEntryKind::Directory && !shared_path.exists() {
        create_codex_home_if_missing(&shared_path)?;
    }

    ensure_symlink_to_shared(&local_path, &shared_path, entry.kind)
}

fn migrate_shared_codex_entry(
    local_path: &Path,
    shared_path: &Path,
    kind: SharedCodexEntryKind,
) -> Result<()> {
    let metadata = match fs::symlink_metadata(local_path) {
        Ok(metadata) => metadata,
        Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(err) => {
            return Err(err).with_context(|| format!("failed to inspect {}", local_path.display()));
        }
    };

    if metadata.file_type().is_symlink() {
        migrate_shared_codex_symlink_target(local_path, shared_path, kind)?;
        remove_path(local_path)?;
        return Ok(());
    }

    match kind {
        SharedCodexEntryKind::Directory => {
            if !metadata.is_dir() {
                bail!(
                    "expected {} to be a directory for shared Codex state",
                    local_path.display()
                );
            }

            if !shared_path.exists() {
                move_directory(local_path, shared_path)?;
                return Ok(());
            }
            if !shared_path.is_dir() {
                bail!(
                    "expected {} to be a directory for shared Codex state",
                    shared_path.display()
                );
            }

            copy_directory_contents(local_path, shared_path)?;
            fs::remove_dir_all(local_path)
                .with_context(|| format!("failed to remove {}", local_path.display()))?;
        }
        SharedCodexEntryKind::File => {
            if !metadata.is_file() {
                bail!(
                    "expected {} to be a file for shared Codex state",
                    local_path.display()
                );
            }

            if !shared_path.exists() {
                move_file(local_path, shared_path)?;
                return Ok(());
            }
            if !shared_path.is_file() {
                bail!(
                    "expected {} to be a file for shared Codex state",
                    shared_path.display()
                );
            }

            if is_history_jsonl(local_path) {
                merge_history_files(local_path, shared_path)?;
            }

            fs::remove_file(local_path)
                .with_context(|| format!("failed to remove {}", local_path.display()))?;
        }
    }

    Ok(())
}

fn migrate_shared_codex_symlink_target(
    local_path: &Path,
    shared_path: &Path,
    kind: SharedCodexEntryKind,
) -> Result<()> {
    let target = fs::read_link(local_path)
        .with_context(|| format!("failed to read symlink {}", local_path.display()))?;
    let target_path = if target.is_absolute() {
        target
    } else {
        local_path
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join(target)
    };

    if same_path(&target_path, shared_path) || !target_path.exists() {
        return Ok(());
    }

    if let Some(parent) = shared_path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }

    match kind {
        SharedCodexEntryKind::Directory => {
            if !target_path.is_dir() {
                bail!(
                    "expected {} to be a directory for shared Codex state",
                    target_path.display()
                );
            }

            if !shared_path.exists() {
                create_codex_home_if_missing(shared_path)?;
            } else if !shared_path.is_dir() {
                bail!(
                    "expected {} to be a directory for shared Codex state",
                    shared_path.display()
                );
            }

            copy_directory_contents(&target_path, shared_path)?;
        }
        SharedCodexEntryKind::File => {
            if !target_path.is_file() {
                bail!(
                    "expected {} to be a file for shared Codex state",
                    target_path.display()
                );
            }

            if !shared_path.exists() {
                fs::copy(&target_path, shared_path).with_context(|| {
                    format!(
                        "failed to copy {} to {}",
                        target_path.display(),
                        shared_path.display()
                    )
                })?;
            } else if !shared_path.is_file() {
                bail!(
                    "expected {} to be a file for shared Codex state",
                    shared_path.display()
                );
            } else if is_history_jsonl(local_path) {
                merge_history_files(&target_path, shared_path)?;
            }
        }
    }

    Ok(())
}

fn seed_shared_codex_entry(
    legacy_path: &Path,
    shared_path: &Path,
    kind: SharedCodexEntryKind,
) -> Result<()> {
    let metadata = match fs::symlink_metadata(legacy_path) {
        Ok(metadata) => metadata,
        Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(err) => {
            return Err(err)
                .with_context(|| format!("failed to inspect {}", legacy_path.display()));
        }
    };

    if metadata.file_type().is_symlink() {
        return Ok(());
    }

    if let Some(parent) = shared_path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }

    match kind {
        SharedCodexEntryKind::Directory => {
            if !metadata.is_dir() {
                bail!(
                    "expected {} to be a directory for shared Codex state",
                    legacy_path.display()
                );
            }

            if shared_path.exists() {
                if !shared_path.is_dir() {
                    bail!(
                        "expected {} to be a directory for shared Codex state",
                        shared_path.display()
                    );
                }

                // Legacy seeding is a one-time bootstrap. Recopying populated
                // session trees from ~/.codex on every `prodex run` adds large
                // disk I/O directly to the startup hot path.
                if !dir_is_empty(shared_path)? {
                    return Ok(());
                }
            } else {
                create_codex_home_if_missing(shared_path)?;
            }

            copy_directory_contents(legacy_path, shared_path)?;
        }
        SharedCodexEntryKind::File => {
            if !metadata.is_file() {
                bail!(
                    "expected {} to be a file for shared Codex state",
                    legacy_path.display()
                );
            }

            if !shared_path.exists() {
                fs::copy(legacy_path, shared_path).with_context(|| {
                    format!(
                        "failed to copy legacy shared Codex file {} to {}",
                        legacy_path.display(),
                        shared_path.display()
                    )
                })?;
            } else if !shared_path.is_file() {
                bail!(
                    "expected {} to be a file for shared Codex state",
                    shared_path.display()
                );
            } else if is_history_jsonl(legacy_path) {
                // Legacy default CODEX_HOME seeding should stay one-shot so
                // startup does not reread and rewrite large history files on
                // every `prodex run`.
                return Ok(());
            }
        }
    }

    Ok(())
}

fn move_directory(source: &Path, destination: &Path) -> Result<()> {
    if let Some(parent) = destination.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }

    match fs::rename(source, destination) {
        Ok(()) => Ok(()),
        Err(_) => {
            create_codex_home_if_missing(destination)?;
            copy_directory_contents(source, destination)?;
            fs::remove_dir_all(source)
                .with_context(|| format!("failed to remove {}", source.display()))
        }
    }
}

fn move_file(source: &Path, destination: &Path) -> Result<()> {
    if let Some(parent) = destination.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }

    match fs::rename(source, destination) {
        Ok(()) => Ok(()),
        Err(_) => {
            fs::copy(source, destination).with_context(|| {
                format!(
                    "failed to copy {} to {}",
                    source.display(),
                    destination.display()
                )
            })?;
            fs::remove_file(source)
                .with_context(|| format!("failed to remove {}", source.display()))
        }
    }
}

fn is_history_jsonl(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name == "history.jsonl")
}

fn merge_history_files(source: &Path, destination: &Path) -> Result<()> {
    #[derive(Debug)]
    struct HistoryLine {
        ts: Option<i64>,
        line: String,
        order: usize,
    }

    fn load_history_lines(
        path: &Path,
        merged: &mut Vec<HistoryLine>,
        seen: &mut BTreeSet<String>,
    ) -> Result<()> {
        let content = fs::read_to_string(path)
            .with_context(|| format!("failed to read {}", path.display()))?;
        for raw_line in content.lines() {
            let line = raw_line.trim_end_matches('\r');
            if line.is_empty() || !seen.insert(line.to_string()) {
                continue;
            }

            let ts = serde_json::from_str::<serde_json::Value>(line)
                .ok()
                .and_then(|value| value.get("ts").and_then(serde_json::Value::as_i64));
            merged.push(HistoryLine {
                ts,
                line: line.to_string(),
                order: merged.len(),
            });
        }

        Ok(())
    }

    let mut merged = Vec::new();
    let mut seen = BTreeSet::new();

    if destination.exists() {
        load_history_lines(destination, &mut merged, &mut seen)?;
    }
    load_history_lines(source, &mut merged, &mut seen)?;

    merged.sort_by(|left, right| match (left.ts, right.ts) {
        (Some(left_ts), Some(right_ts)) => {
            left_ts.cmp(&right_ts).then(left.order.cmp(&right.order))
        }
        _ => left.order.cmp(&right.order),
    });

    let mut content = String::new();
    for (index, entry) in merged.iter().enumerate() {
        if index > 0 {
            content.push('\n');
        }
        content.push_str(&entry.line);
    }

    fs::write(destination, content)
        .with_context(|| format!("failed to write merged history {}", destination.display()))
}

fn ensure_symlink_to_shared(
    local_path: &Path,
    shared_path: &Path,
    kind: SharedCodexEntryKind,
) -> Result<()> {
    if local_path.exists() {
        remove_path(local_path)?;
    } else if fs::symlink_metadata(local_path).is_ok() {
        remove_path(local_path)?;
    }

    create_symlink(shared_path, local_path, kind)
}

fn create_symlink(target: &Path, link: &Path, kind: SharedCodexEntryKind) -> Result<()> {
    #[cfg(unix)]
    {
        let _ = kind;
        std::os::unix::fs::symlink(target, link).with_context(|| {
            format!(
                "failed to link shared Codex state {} -> {}",
                link.display(),
                target.display()
            )
        })?;
    }

    #[cfg(windows)]
    {
        match kind {
            SharedCodexEntryKind::Directory => std::os::windows::fs::symlink_dir(target, link),
            SharedCodexEntryKind::File => std::os::windows::fs::symlink_file(target, link),
        }
        .with_context(|| {
            format!(
                "failed to link shared Codex state {} -> {}",
                link.display(),
                target.display()
            )
        })?;
    }

    #[cfg(not(any(unix, windows)))]
    {
        let _ = kind;
        bail!("shared Codex session links are not supported on this platform");
    }

    Ok(())
}

fn remove_path(path: &Path) -> Result<()> {
    let metadata = fs::symlink_metadata(path)
        .with_context(|| format!("failed to inspect {}", path.display()))?;
    let file_type = metadata.file_type();

    if file_type.is_symlink() {
        fs::remove_file(path)
            .or_else(|_| fs::remove_dir(path))
            .with_context(|| format!("failed to remove symbolic link {}", path.display()))?;
        return Ok(());
    }

    if metadata.is_dir() {
        fs::remove_dir_all(path).with_context(|| format!("failed to remove {}", path.display()))?;
    } else {
        fs::remove_file(path).with_context(|| format!("failed to remove {}", path.display()))?;
    }

    Ok(())
}

pub(crate) fn create_codex_home_if_missing(path: &Path) -> Result<()> {
    fs::create_dir_all(path).with_context(|| format!("failed to create {}", path.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let permissions = fs::Permissions::from_mode(0o700);
        let _ = fs::set_permissions(path, permissions);
    }
    Ok(())
}

fn dir_is_empty(path: &Path) -> Result<bool> {
    if !path.exists() {
        return Ok(true);
    }
    let mut entries =
        fs::read_dir(path).with_context(|| format!("failed to read {}", path.display()))?;
    Ok(entries.next().is_none())
}