codex-multi-auth icon indicating copy to clipboard operation
codex-multi-auth copied to clipboard

feat(rotation): opt-in adopt-history command for provider-filtered session history

Open plustar35 opened this issue 5 months ago • 3 comments

Problem

Current Codex builds filter conversation history by the active model provider — in both the CLI resume picker and Codex Desktop. While the app bind is active the provider is codex-multi-auth-runtime-proxy, so every session recorded under the native openai provider disappears from both lists. The data stays on disk, but the only documented remedy today is to unbind/disable before browsing old history and re-bind afterwards (docs/troubleshooting.md), which gets old fast for daily users.

Solution

codex-multi-auth rotation adopt-history — an explicit, opt-in, fully reversible rewrite of the recorded provider markers:

  1. Rollout files: rewrites "model_provider":"openai" → "model_provider":"codex-multi-auth-runtime-proxy" in sessions/**/rollout-*.jsonl, atomically per file (tmp + rename, shared withFileOperationRetry taxonomy). Covers the CLI resume picker.
  2. Codex Desktop thread index: issues the matching UPDATE threads SET model_provider=… against the newest state_<n>.sqlite via the sqlite3 CLI when available; prints the manual SQL when it isn't. Covers Desktop history.

UX safeguards, since this touches user data:

  • Prints the mechanism and caveats up front (quit Desktop first; visibility follows the active provider; run --reverse before uninstalling)
  • Interactive confirmation required; --yes for non-interactive use, refuses to write without it
  • --dry-run reports match counts without writing
  • --reverse is the exact inverse substitution (token-level swap is bijective), for pre-uninstall restoration
  • Writes a manifest of changed files under the codex-multi-auth data directory
  • --json machine-readable summary

session_index.jsonl is intentionally untouched — it carries no provider markers.

Validation

  • 8 new behavior tests (test/adopt-history.test.ts): dry-run immutability, non-interactive refusal, forward + reverse rewrite with JSON-validity checks, declined-confirmation abort, sqlite-unavailable fallback, unknown-option rejection, state-db version selection — all passing
  • npm run typecheck and npm run lint clean; related suites (rotation command, help) pass — 217/217
  • Verified end-to-end on a live macOS install: 626 rollout files + 637 thread rows re-tagged; history visible in both the CLI picker and Codex Desktop afterwards; --reverse restores the original state
  • Docs updated per CONTRIBUTING: docs/reference/commands.md, docs/troubleshooting.md, docs/features.md, rotation usage text, and main help

Scope note

Local metadata rewrite only — no auth, network, or policy surface is touched; it edits the same files/database Codex itself maintains locally.

🤖 Generated with Claude Code

note: greptile review for oc-chatgpt-multi-auth. cite files like lib/foo.ts:123. confirm regression tests + windows concurrency/token redaction coverage.

Greptile Summary

adds codex-multi-auth rotation adopt-history, an opt-in, fully reversible command that rewrites "model_provider" markers in local rollout files and the codex desktop sqlite thread index so pre-bind sessions stay visible in the cli picker and desktop history while the rotation proxy provider is active.

  • core rewrite logic (adopt-history.ts): recursive rollout file walk, content-cached scan phase, atomic tmp+rename writes with withFileOperationRetry, and a sqlite3 cli UPDATE for the desktop thread index — gated behind dry-run, interactive confirmation, and --reverse symmetry.
  • ux safeguards: prints mechanism/caveats, requires --yes for non-interactive use, writes an advisory manifest, and surfaces manual sql when the sqlite3 binary is absent.
  • dispatch + docs: hooked into the rotation subcommand router with the real confirm dep; all five doc files updated.

Confidence Score: 3/5

hold until the open items from previous review rounds are addressed — in particular the predictable .adopt-tmp staging path and the silent exit-0 when session files are rewritten but the sqlite UPDATE fails.

the command touches user data in two places (session rollout files and the desktop sqlite db) with no rollback path if the db step fails after files are already rewritten. the .adopt-tmp staging name is fully predictable and bypasses the tempPathFor() contract that guards every other atomic write in this codebase. the sqliteAvailable init bug means the json summary misreports the sqlite probe state when no desktop db is present. together these leave the migration in a silently half-complete state for automation users relying on --yes --json and the exit code.

lib/codex-manager/commands/adopt-history.ts — the staging path, partial-failure exit code, and sqliteAvailable init issues from prior rounds are all in this file and are not yet addressed in this iteration.

Important Files Changed

Filename Overview
lib/codex-manager/commands/adopt-history.ts new command implementing the provider-rewrite migration; carries three open issues from previous review rounds (predictable .adopt-tmp staging path, silent exit-0 on partial sqlite failure, sqliteAvailable initialized true when no db is found) plus a non-atomic manifest write noted in this round.
lib/codex-manager/commands/rotation.ts adds the adopt-history subcommand dispatch; cleanly delegates to runAdoptHistory with the real confirm dep and forwarded logInfo/logError.
test/adopt-history.test.ts 8 behavior tests covering dry-run, non-interactive refusal, forward/reverse rewrite, confirmation abort, sqlite unavailable, JSON shape, unknown option, and db version selection; still missing --dry-run --json combined output shape and partial-failure (session files rewritten but sqlite UPDATE throws) non-zero exit coverage.
lib/codex-manager/help.ts adds adopt-history usage line to top-level help output; no logic changes.
docs/reference/commands.md docs updated with new subcommand, flag table entries for --dry-run and --json, and a behavior description for adopt-history.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[runAdoptHistory args] --> B{parse flags}
    B -->|unknown flag| Z1[return 1]
    B -->|--help| Z2[print usage, return 0]
    B --> C[resolve codexHome / sessionsRoot]
    C --> D[collectRolloutFiles]
    D --> E[scan: readFile + filter by fromToken]
    E --> F[findStateDb]
    F --> G{stateDbPath?}
    G -->|yes| H[runSqlite COUNT]
    H -->|ok| I[threadRowsMatched = N]
    H -->|throws| J[sqliteAvailable = false\nthreadRowsMatched = null]
    G -->|no| K[skip db step]
    I --> L{--dry-run?}
    J --> L
    K --> L
    L -->|yes| Z3[print/JSON summary, return 0]
    L -->|no| M{nothing to do?}
    M -->|yes| Z4[return 0]
    M -->|no| N{--yes?}
    N -->|no| O{isTTY?}
    O -->|no| Z5[error: use --yes, return 1]
    O -->|yes| P[confirm prompt]
    P -->|declined| Z6[Aborted, return 0]
    P -->|confirmed| Q
    N -->|yes| Q[rewrite session files\ntmp + rename per file]
    Q --> R{stateDbPath and sqliteAvailable\nand threadRowsMatched > 0?}
    R -->|yes| S[runSqlite UPDATE]
    S -->|ok| T[threadRowsUpdated = N]
    S -->|throws| U[logError + manual SQL hint]
    R -->|no| V
    T --> V[write manifest\nwriteFile direct]
    U --> V
    V --> W[print summary / JSON]
    W --> X[return 0]
Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
lib/codex-manager/commands/adopt-history.ts:361-381
**non-atomic manifest write — inconsistent with session file pattern**

every session file rewrite uses `writeFile(tmp) → rename(file)` inside `withFileOperationRetry`, but the manifest at line 364 uses a bare `writeFile` directly to the final path. on windows, a crash between the os-level write calls that implement `writeFile` leaves a partially-written json file; a concurrent second invocation (e.g. two `--yes` runs triggered by a wrapper script) races the same path with no tmp barrier. since `summary.manifestPath` is set only on success and the catch is silent, callers reading the manifest may get truncated json with no signal of corruption. apply the same tmp+rename pattern here using `tempPathFor(manifestPath)` — consistent with the approach the rest of the file relies on for atomic writes.

Reviews (2): Last reviewed commit: "refactor(rotation): address review feedb..." | Re-trigger Greptile

plustar35 avatar Jun 11 '26 13:06 plustar35

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. Credits must be used to enable repository wide code reviews.

[!CAUTION]

Review failed

An error occurred during the review process. Please try again later.

📝 Walkthrough

Opt-in provider history adoption command — Severity: Minor/Feature. Adds a safe, reversible CLI command to retag local session history so pre-bind conversations remain visible when the rotation proxy is active; no breaking API changes and no network/auth surfaces modified. Tests cover main behaviors and the feature includes multiple safety guards (interactive confirm, --dry-run, atomic writes, manifest, and --reverse).

Summary

  • New command: codex-multi-auth rotation adopt-history implemented in lib/codex-manager/commands/adopt-history.ts (423 lines). It scans sessions/<...>/rollout-*.jsonl for model_provider markers and rewrites between the native provider ("openai") and the runtime rotation proxy (RUNTIME_ROTATION_PROXY_PROVIDER_ID). It optionally updates the Desktop thread index (newest state_.sqlite) via sqlite3 or prints a manual UPDATE SQL snippet when sqlite3 is unavailable. The command writes an advisory history-adopt-manifest.json to the multi-auth data dir, supports --dry-run, --reverse (bijective inverse), --yes, --json, and refuses to mutate without consent.
  • CLI wiring & help: rotation adopt-history hooked into lib/codex-manager/commands/rotation.ts and usage/help text added in lib/codex-manager/help.ts.
  • Documentation: docs/features.md, docs/reference/commands.md, and docs/troubleshooting.md updated to document the workflow, caveats, and troubleshooting remediation.
  • Tests: test/adopt-history.test.ts (194 lines) adds 8 behavior tests exercising dry-run immutability, interactive confirmation and abort, non-interactive refusal, forward + reverse rewrites, sqlite-unavailable fallback with manual SQL, --json output parseability, unknown-option rejection, and selection of the highest-version state DB. Tests seed temporary Codex home and CODEX_MULTI_AUTH_DIR and clean up after each run.

Architectural/Review Focus

  • File rewrite strategy: atomic temp-file write + rename with file-operation retry and cached file contents to avoid a scan→rewrite TOCTOU window — reviewers should confirm correctness of retry and rename semantics across platforms.
  • Desktop DB update: uses sqlite3 CLI if available and records row counts; when sqlite3 is missing the command prints manual SQL (non-destructive advisory). Reviewers should validate the chosen approach for invocation, timeouts, and error handling, plus the decision to not treat manifest write failures as fatal.
  • Interaction model: enforces interactivity by default (refuses on non-TTY), injects confirm/runSqlite for testability, and requires explicit --yes or an interactive confirmation to proceed. Confirm behavior and messaging should be validated for clarity.
  • Scope decisions: session_index.jsonl is intentionally not touched; only rollout-*.jsonl and the threads table (if present) are modified. This metadata-only design preserves auth/policy boundaries but reviewers should verify there are no other persisted locations needing retagging.

Risk assessment

  • Data-loss: Low. Rewrites are atomic, fully reversible via --reverse, and recorded in a manifest; manifest-write failures are advisory and do not block the migration.
  • Security/auth: None — operation is local metadata-only; no credentials or network operations are introduced.
  • Regression: Minimal. No exported/public API changes beyond adding the command; 8 targeted behavior tests added and related suites remain clean.

Walkthrough

new cli rotation adopt-history rewrites provider markers in rollout files and optionally updates the desktop state sqlite, records a history-adopt-manifest.json, and is documented in docs and help (see lib/codex-manager/commands/adopt-history.ts:173-397, docs/reference/commands.md:319).

Changes

rotation adopt-history feature

Layer / File(s) Summary
feature and command documentation
docs/features.md, docs/reference/commands.md, docs/troubleshooting.md, lib/codex-manager/help.ts
adds "history provider adoption" docs and updates command reference and troubleshooting text; help usage line added for rotation adopt-history (see docs/features.md:28, docs/reference/commands.md:319, docs/troubleshooting.md:82, lib/codex-manager/help.ts:40).
core helpers and DI surface
lib/codex-manager/commands/adopt-history.ts
introduces constants, AdoptHistoryDeps, sqlite exec wrapper, file discovery helpers, and rollout parsing utilities (see lib/codex-manager/commands/adopt-history.ts:1-128).
cli parsing and scanning
lib/codex-manager/commands/adopt-history.ts
implements option parsing, determines from/to providers, validates sessions dir, scans sessions/**/rollout-*.jsonl and computes optional sqlite pre-count (see lib/codex-manager/commands/adopt-history.ts:173-274).
atomic rewrite, sqlite update, manifest & output
lib/codex-manager/commands/adopt-history.ts
performs token substitution with temp-file write+rename, runs UPDATE threads SET model_provider when applicable, writes advisory history-adopt-manifest.json, and emits json or human text output (see lib/codex-manager/commands/adopt-history.ts:331-397).
cli command integration
lib/codex-manager/commands/rotation.ts
wires rotation adopt-history to runAdoptHistory with injected confirm/logging and extends rotation usage/help text (see lib/codex-manager/commands/rotation.ts:743-745, lib/codex-manager/commands/rotation.ts:103-111).
test suite with fixtures
test/adopt-history.test.ts
vitest coverage for dry-run, non-interactive gating, adoption/reverse with --yes, manifest contents, sqlite-failure fallback logging, json output, unknown-option error, and state DB selection; uses temp codexHome and CODEX_MULTI_AUTH_DIR (see test/adopt-history.test.ts:71-122, test/adopt-history.test.ts:152-168, test/adopt-history.test.ts:188-193).
sequenceDiagram
  participant user as cli
  participant adoptCmd as runAdoptHistory
  participant fs as rollout_files
  participant sqlite as state_db
  participant manifest as manifest
  participant stdout as output

  user->>adoptCmd: invoke rotation adopt-history [--dry-run|--reverse|--yes|--json]
  adoptCmd->>fs: scan sessions/**/rollout-*.jsonl and find provider tokens
  adoptCmd->>sqlite: optional SELECT count(*) FROM threads WHERE model_provider=from
  adoptCmd->>fs: write temp files and rename to replace provider token
  adoptCmd->>sqlite: run UPDATE threads SET model_provider=to
  adoptCmd->>sqlite: SELECT changes()
  adoptCmd->>manifest: write advisory manifest with direction/files/counts
  adoptCmd->>stdout: emit json or human summary

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

flagged issues (senior staff style, concise):

  • missing windows regression test: atomic temp-file-rename pattern uses fs.promises.rename. verify cross-drive and windows semantics. see lib/codex-manager/commands/adopt-history.ts:331-359 and test/adopt-history.test.ts:71-122 where cross-platform rename is not exercised.
  • sqlite concurrency and busy handling: UPDATE runs without explicit busy_timeout or transaction isolation. inspect lib/codex-manager/commands/adopt-history.ts:331-359 and consider PRAGMA busy_timeout or BEGIN IMMEDIATE in sqlite runner.
  • manifest write failure untested: manifest write errors are swallowed; no test covers permission-denied or disk-full cases. see lib/codex-manager/commands/adopt-history.ts:361-397 and test/adopt-history.test.ts for absence of such case.
  • concurrent runs risk: running adopt-history concurrently could produce race conditions on rollout files and manifest. review atomicity and consider a simple lock/guard before scanning (see lib/codex-manager/commands/adopt-history.ts:275-329 and lib/codex-manager/commands/adopt-history.ts:331-359).

references to inspect quickly: lib/codex-manager/commands/adopt-history.ts:173-397, lib/codex-manager/commands/adopt-history.ts:1-128, lib/codex-manager/commands/rotation.ts:743-745, test/adopt-history.test.ts:71-122.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning Title exceeds 72-character limit (82 chars) and uses mixed case, violating conventional commits format requirements. Shorten to ≤72 chars in lowercase imperative: e.g., 'feat(rotation): add opt-in adopt-history command for session provider rewrite'.
Docstring Coverage ⚠️ Warning Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed Description is comprehensive with problem/solution structure, validation details, and all required docs checklist items addressed; satisfies template expectations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests
✨ Simplify code
  • [ ] Create PR with simplified code

[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Jun 11 '26 13:06 coderabbitai[bot]

Thanks for the review. Pushed a fixup addressing the actionable items:

  • TOCTOU / double read: the scan now caches each matched file's content and the rewrite loop reuses it (no second readFile, no scan→rewrite window).
  • Explicit types: readdir results typed as Dirent[] / string[].
  • Redundant wrapper: confirm is passed directly instead of (message) => confirm(message).
  • Test cleanup: switched to the shared removeWithRetry helper.
  • --json coverage: added a test asserting the output is parseable with stable direction / sessionFilesRewritten / dryRun fields.
  • Docs: adopt-history now appears in the commands.md summary row and the --json / --dry-run flag tables.

typecheck, lint, and the adopt-history suite all pass.

plustar35 avatar Jun 11 '26 13:06 plustar35

Thanks for this, @plustar35, and for addressing the review feedback (the TOCTOU/double-read fix and explicit typing). Closing this one for now: unlike the contrib utilities, adopt-history touches core rotation/command surface (lib/codex-manager/), it's currently in a conflicting state against main, and a provider-filtered session-history adopt flow is a behavioral/product decision we want to design deliberately rather than land ad hoc. If you'd like to pursue it, the best path is a short issue proposing the command's semantics first so we can align before implementation — your branch is a solid starting point and you'd of course get credit. Appreciate it. 🙏

ndycode avatar Jun 19 '26 06:06 ndycode