codex-cross-provider-session-repair
Skill1 starsChanged 2 months agoMITView on GitHub
Repair Codex Desktop sessions that fail after switching model providers or importing/forking old conversations. Use this skill whenever a user mentions an old Codex session becoming invalid, “model provider not found”, “Codex cannot load config.toml”, remote context compaction 404s, “Item with id rs_... not found”, repeated reconnecting during resume, or a migrated Codex conversation that cannot continue—even when the user only asks to inspect or explain the failure. Diagnose the target session across its JSONL rollout, root state_5.sqlite, config.toml, and logs_2.sqlite, then make a target-scoped backup-first repair with verification and restart instructions.
In this repository7 other files it gives its agents.
- agent-privacy-checkSkill
- codex-doctorSkill
- github-repo-i18nSkill
- public-release-gateSkill
- public-repo-git-gateSkill
- shadow-skill-publisherSkill
- test-scope-routingSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
26 rules. About 0 are common, 11 are distinctive, and 15 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈11
Distinctive · estimate
This author's own choices. Worth a look.
15
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 18
Use this skill for a damaged or incompatible *saved Codex session*, not for ordinary model/API troubleshooting.
- Distinctive: line 32
If the user does not know the UUID, help them find it:
- Very specific: line 53
After Codex Desktop is fully quit, the manual one-shot command can combine all needed flags in a single --apply invocation:
- Very specific: line 60
Run the same command without --apply afterward.
- Distinctive: line 116
Start with a dry run. Before any write, make a timestamped backup of the JSONL.
- Very specific: line 117
Ask the user to fully quit Codex Desktop, including the tray process and its bundled codex app-server/service processes, before applying …
- Very specific: line 118
Never treat a task-bound background waiter, a closed tool session, or a returned process exit code without a backup as proof that a repair …
- Very specific: line 119
Never delete the whole Codex home, all sessions, config.toml, auth tokens, caches, or databases as a generic “reset”.
- Very specific: line 121
Prefer the target-scoped offline repair (scripts/repair_session_offline.py) over a global config.toml change when the remote-compaction …
- Distinctive: line 122
Do not print auth tokens, refresh tokens, API keys, or complete session contents.
- Distinctive: line 123
If the target rollout cannot be found, JSON parsing fails, or a backup cannot be created, stop and report the blocker instead of guessing.
- Very specific: line 129
Use the exact session UUID supplied by the user.
- Distinctive: line 135
Run the bundled script in dry-run mode:
- Very specific: line 151
Use Python's built-in sqlite3 module.
- Distinctive: line 155
Provider mismatch: If the current provider is known and the target session or target DB row still names an old provider, apply a …
- Very specific: line 162
Update only the target session's session_meta payload and the target threads row.
- Very specific: line 164
Unsupported saved model: If the report shows a model such as ark-code-latest that the current account does not support, align only the …
- Very specific: line 177
Stale remote compaction: If logs show Item with id 'rs_...' not found and the IDs map to local response_item records with payload.type == …
- Very specific: line 232
Gemini model-turn compaction: If the dry-run report shows Model-turn compaction: RISK or logged-error, the effective history ends with an …
- Very specific: line 241
Remote compaction contract failure: When the report shows error evidence for remote compaction and the feature stage is removed (or the …
- Very specific: line 246
Ask the user to fully quit Codex.
- Distinctive: line 275
After a verified run, tell the user to reopen Codex and continue the session through the ordinary provider URL — the shim is only needed …
- Very specific: line 283
Run the script again without --apply, or use its --verify output.
- Distinctive: line 285
every remaining JSONL line parses.
- Distinctive: line 291
no unrelated session was changed.
- Distinctive: line 311
If compaction succeeds and the error changes to authentication, transport, or provider availability, stop treating it as a session-file …
≈ “Common” is an estimate: at least 1 in 5 of the 372,429 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Codex cross-provider session repair
Compatibility: Requires Python 3.9+ with the standard library; Windows, macOS, and Linux Codex homes are supported. Stop Codex Desktop before applying file or database changes. On macOS, the recommended launcher requires Terminal automation permission so it can close only its uniquely titled repair window.
Use this skill for a damaged or incompatible saved Codex session, not for ordinary model/API troubleshooting. The goal is to make one existing conversation resumable while keeping its user-visible history and avoiding broad cache deletion.
User interaction flow (end-to-end)
The user does not need to memorise CLI flags. A typical session looks like this:
- User opens a new Codex conversation (the broken one cannot be used) and provides the session UUID and visible error.
- Agent runs the dry-run diagnostic (see Workflow below). The report shows which failure mode applies and what will be changed.
- Agent explains the root cause and gets approval for the write. After approval, start
scripts/start_repair.pyimmediately. On macOS it opens a readable Terminal tab/window and runs the independent worker through a short temporary runner; do not paste the full worker command into the user's shell. The worker is safe whether Codex is still open, is being closed, or was already closed after the approval. Immediately tell the user in the current conversation:修复任务已启动,最多等待 300 秒;请完全退出 Codex。终端会持续显示进度,完成前不要重新打开。 / Repair started; it may wait up to 300 seconds. Fully quit Codex; follow the Terminal status and do not reopen it before completion. - Do not reopen Codex until verification says
Verified / 已验证. The Terminal shows bilingual states:Waiting / 等待中,Applying / 修复中,Verified / 已验证, orFailed / 失败. During the default 300-second wait it prints reminders at about 60, 180, and 240 seconds. The status JSON also exposeswait_timeout_seconds,wait_phase,conversation_notice, andcan_reopen; onlycan_reopen: truepermits reopening. If the current conversation remains available, mirror the wait/reminder status there; after Codex is fully closed, the independent Terminal and status JSON are authoritative. - After verification, relaunch Codex Desktop (Cmd+Q/reopen on macOS), open the repaired session, and send a short test message.
Finding the session ID
If the user does not know the UUID, help them find it:
- From the Codex App UI: right-click the broken conversation in the sidebar; some versions show the ID in the context menu or in the URL bar.
From the filesystem: list recent rollout files:
ls -lt ~/.codex/sessions/*/*/rollout-*.jsonl | head -10The UUID is the last segment of the filename (e.g.
rollout-2026-08-02T22-05-32-<UUID>.jsonl).From the database: query the threads table for recent sessions:
import sqlite3 conn = sqlite3.connect("~/.codex/state_5.sqlite".replace("~", str(__import__("pathlib").Path.home()))) for row in conn.execute("SELECT id, title, model, updated_at FROM threads ORDER BY updated_at DESC LIMIT 10"): print(row)
One-shot repair command
After Codex Desktop is fully quit, the manual one-shot command can combine all
needed flags in a single --apply invocation:
python3 <skill_dir>/scripts/repair.py --session-id <UUID> --codex-home <CODEX_HOME> --fix-provider --provider <current> --fix-model-turn --remove-reasoning all --applyRun the same command without --apply afterward. Do not report completion until
the post-repair report has been captured and verified.
What this skill fixes
Codex stores continuation state in several layers:
- the global
config.toml(current provider defaults); - a dated
sessions/**/rollout-*.jsonlfile (the conversation event stream); - the root
state_5.sqlitethreadsrow (the desktop index and provider snapshot); and logs_2.sqlite(diagnostic evidence).
After a provider switch, an old thread can retain a provider in layers 2 or 3 even when the global config is correct. Separately, an imported/forked long thread can contain response_item reasoning records that were sent with store=false and never persisted by the service. Remote compaction then fails with HTTP 404: Item with id 'rs_...' not found.
The second failure is not fixed by changing the provider, deleting config.toml, or clearing browser cache. If multiple different rs_... IDs fail in succession, remove the non-user-visible local reasoning items in one pass; deleting one ID at a time only exposes the next stale reference.
A third failure occurs when switching to a Gemini-backed model (e.g. gemini-3.6-flash-high via a proxy such as CC Switch). Gemini's API rejects requests whose message history ends with a model/assistant turn: Requests ending with a model turn are not supported. (HTTP 400 INVALID_ARGUMENT). Codex triggers pre-sampling context compaction (CompHashChanged) on model switch; if the effective history after thread_rolled_back events ends with an assistant message, the compaction request fails and the turn cannot start. This is systemic—every session switched to Gemini that needs compaction will hit it until the JSONL is repaired.
A fourth failure occurs when the current provider/model does not implement
Codex's remote compaction v2. The turn fails with Error running remote compact
task: Fatal error: remote compaction v2 expected exactly one compaction output
item, got 0 from N output items. This is not a JSONL corruption: the backend
simply did not return the type: "compaction" output item Codex requires.
Detection reads two sources, because Codex frequently records only the generic
Failed to run pre-sampling compact line in logs_2.sqlite while the detailed
message lands in the rollout's event_msg/task_complete payload. The report
line Remote compaction v2: feature=<stage> | error evidence: ... shows both.
The remedy depends on the feature stage reported by codex features list:
- Toggleable (
stable,experimental, …): the operator may disable the feature with--disable-remote-compaction(requires--applyand explicit user approval), which writesremote_compaction_v2 = falseunder[features]in config.toml with a backup, or switch to a provider/model that supports it. removed: the flag is a tombstone. Codex ignores the config key and there is no local compaction fallback, so the script refuses--disable-remote-compactionwith exit code 2. The contract has to be satisfied on the server side, or the conversation must move to a backend that implements remote compaction v2.
Compaction is mandatory in such builds, so an over-limit session cannot
continue until the contract is met. scripts/repair_session_offline.py performs
that repair against the failing session without editing config.toml.
A fifth failure occurs when an imported session is pinned to a model that the
current ChatGPT account cannot use, such as ark-code-latest. The report
identifies the model in the rollout's structured turn settings and the target
threads.model snapshot. Use --fix-model --model <current-model> to update
only those target-session values. Pair it with --remove-reasoning none when
the session has no stale-reasoning diagnosis; this preserves all local
reasoning records.
Safety contract
- Work on the requested session ID only. Do not update every thread or every session by default.
- Start with a dry run. Before any write, make a timestamped backup of the JSONL; back up the root SQLite database (including WAL/SHM sidecars) only when changing its provider row.
- Ask the user to fully quit Codex Desktop, including the tray process and its bundled
codex app-server/service processes, before applying changes. A live process can cache old events or hold a file lock. - Never treat a task-bound background waiter, a closed tool session, or a returned process exit code without a backup as proof that a repair ran. The independent wait wrapper must end in
verified. - Never delete the whole Codex home, all sessions,
config.toml, auth tokens, caches, or databases as a generic “reset”. - Preserve every user message, visible assistant message, tool call, tool result, and
event_msg. Only removeresponse_itemrecords whose payload type isreasoning, and only when the diagnosis supports the stale-compaction repair. - Prefer the target-scoped offline repair (
scripts/repair_session_offline.py) over a globalconfig.tomlchange when the remote-compaction flag is a tombstone or the user declines a global edit. It backs up files beside their originals and leaves no daemon running. - Do not print auth tokens, refresh tokens, API keys, or complete session contents. Redact paths and secrets in reports.
- If the target rollout cannot be found, JSON parsing fails, or a backup cannot be created, stop and report the blocker instead of guessing.
Workflow
1. Identify the target and Codex home
Use the exact session UUID supplied by the user. Resolve CODEX_HOME first; on Windows fall back to %USERPROFILE%\\.codex, and on macOS/Linux to $HOME/.codex. Do not repurpose common environment variables in shell snippets.
Locate the rollout by filename suffix and then confirm its first session_meta record contains the requested ID. Do not trust a title or current working directory alone; imported files can contain more than one session_meta record.
2. Diagnose read-only
Run the bundled script in dry-run mode:
python scripts/repair.py --session-id <UUID> --codex-home <CODEX_HOME>The report should include:
- the exact rollout path and line count;
- JSON parse errors (must be zero before repair);
- target
session_metaprovider values; - the global provider from
config.toml; - the target
threads.model_providerfrom rootstate_5.sqlite(the important database, when present); - distinct
rs_...IDs extracted from target-thread log errors; and - how many of those IDs are actual local
response_itemreasoning records.
Use Python's built-in sqlite3 module; do not require the optional sqlite3 CLI. Treat a missing sqlite/ child database as normal and do not invent one.
3. Select the smallest justified repair
Provider mismatch. If the current provider is known and the target session or target DB row still names an old provider, apply a target-only provider repair:
python scripts/repair.py --session-id <UUID> --codex-home <CODEX_HOME> \
--provider <current-provider> --fix-provider --applyUpdate only the target session's session_meta payload and the target threads row. Never run a global UPDATE ... WHERE model_provider=... for a shared Codex home.
Unsupported saved model. If the report shows a model such as
ark-code-latest that the current account does not support, align only the
target rollout settings and root thread snapshot with the current configured
model:
python scripts/repair.py --session-id <UUID> --codex-home <CODEX_HOME> \
--model <current-model> --fix-model --remove-reasoning none --applyThis creates a JSONL backup and a database backup when the target row changes.
It does not delete reasoning records or alter the global config.toml.
Stale remote compaction. If logs show Item with id 'rs_...' not found and the IDs map to local response_item records with payload.type == "reasoning", use:
python scripts/repair.py --session-id <UUID> --codex-home <CODEX_HOME> \
--remove-reasoning stale --applyThis removes only the exact stale IDs. If the user has already seen two or more different stale IDs from the same imported/migrated session, or a retry reveals another ID immediately, use the one-pass cleanup:
python scripts/repair.py --session-id <UUID> --codex-home <CODEX_HOME> \
--remove-reasoning all --applyall means all local response_item records whose payload type is reasoning; it does not remove event_msg.agent_reasoning, visible messages, tool calls, or tool outputs. This is appropriate because those reasoning items are internal model traces and the service has already confirmed that they were not persisted.
Provider repair and reasoning cleanup can be combined in one invocation after the dry-run report confirms both conditions.
For the recommended user-facing execution, start this command immediately after the user approves the repair. On macOS it opens a visible Terminal window, shows the final result, and closes its uniquely titled repair window after the user presses Enter:
python3 <skill_dir>/scripts/start_repair.py --session-id <UUID> \
--codex-home <CODEX_HOME> --remove-reasoning staleThe command passes --allow-already-stopped to the worker, so the user may
quit Codex before or after the worker starts. The worker still requires a
stable process-free window and a rollout fingerprint match before writing.
Terminal output and the status file use bilingual labels. The Terminal opens a
120-column by 36-row window, hides the long worker command behind a temporary
runner, and first announces the maximum wait, then reminds the user at about
60, 180, and 240 seconds. Verified / 已验证 means it is safe to reopen; Failed / 失败
means keep Codex closed. The launcher tags the repair window with the session
ID; after the final Enter prompt, it closes that exact window when it contains
only the repair tab and exits its shell. If macOS has not granted Terminal
automation permission, the worker still exits normally and the user can close
the finished window with Command+W. A timeout writes wait_timed_out: true
and a conversation-ready next-step message without changing the session.
For advanced use, start the lower-level process-aware worker from a Terminal that is independent of Codex while Codex is still open:
python3 <skill_dir>/scripts/wait_and_repair.py --session-id <UUID> --codex-home <CODEX_HOME> --remove-reasoning all --status-file /tmp/codex-session-repair-<UUID>.jsonThen fully quit Codex Desktop. The wrapper prints bilingual status labels and
atomically updates the same status file. It announces the configured wait
limit and emits periodic reminders. If Codex reappears during the stability
window or the rollout changes while waiting, it stops without writing and
reports Failed / 失败.
Gemini model-turn compaction. If the dry-run report shows Model-turn compaction: RISK or logged-error, the effective history ends with an assistant message and Gemini compaction will fail. Use:
python scripts/repair.py --session-id <UUID> --codex-home <CODEX_HOME> \
--fix-model-turn --applyThis removes thread_rolled_back event records so that previously rolled-back turns (which typically contain the trailing user message) become effective again. If the last effective message is still assistant after rollback removal, a dummy user message is appended to satisfy Gemini's requirement. The repair can be combined with --fix-provider and --remove-reasoning in the same invocation.
Remote compaction contract failure. When the report shows error evidence for
remote compaction and the feature stage is removed (or the user declines a
global config change), repair the session offline instead of editing
config.toml:
- Ask the user to fully quit Codex. The desktop app keeps a writer lock on the
thread (
<CODEX_HOME>/thread-writer-locks/<uuid>.lock), andcodex exec resumefails withalready has an active writerwhile it is held, even after the thread is no longer visible in the UI. Preview the plan:
python scripts/repair_session_offline.py --session-id <UUID> --codex-home <CODEX_HOME>Apply it:
python scripts/repair_session_offline.py --session-id <UUID> --codex-home <CODEX_HOME> --apply
The runner backs up the rollout and the root state database beside their
originals, starts scripts/compaction_shim.py on a loopback port, drives one
turn through it with a temporary
-c model_providers.<provider>.base_url=... override, then verifies a new
compacted record, a null task_complete error, and an unchanged session
model. It never edits config.toml and leaves no process behind.
Useful flags: --model pins the repair turn (by default the runner pins the
session's own recorded model, because codex exec resume would otherwise
rewrite the session to the current config default); --compact-token-limit <n>
forces compaction when the session is only just under the threshold; --json
emits a machine-readable summary.
After a verified run, tell the user to reopen Codex and continue the session through the ordinary provider URL — the shim is only needed for the repair turn. If the shim must stay in the request path (for example because the session will cross the threshold again), document the topology and warn that every request fails while the shim is not running.
4. Verify the file and database
Run the script again without --apply, or use its --verify output. Confirm:
- every remaining JSONL line parses;
- zero stale IDs remain as local reasoning items;
- provider values agree with the chosen current provider when provider repair was requested;
- the target
threads.modeland all structured rollout model settings agree with the chosen model when model repair was requested; - the backup path is reported; and
- a new backup was created by this apply, not just a zero exit code; and
- no unrelated session was changed;
- the
Model-turn compactionline showsok(notRISK) andlast_role=userwhen--fix-model-turnwas applied.
For an offline compaction repair, confirm instead that: the compacted record
count increased, the last task_complete error is null, the session model
still matches what it was before the run, and an independent turn succeeds
through the normal provider URL without the shim. The runner prints all four;
verified: true in its JSON output means every check passed.
The report labels log-derived IDs as Historical remote stale IDs (from logs).
That list may remain after a successful repair because it is historical evidence.
The decisive fields are Stale IDs present as local reasoning: [] together with
Local reasoning records: 0. The raw rs_... text may still occur inside a
historical task_complete error event; that text is not a response_item
submitted for compaction and does not need to be deleted.
5. Reload and test
Tell the user to fully quit and relaunch Codex Desktop, then open the exact session. A page refresh is insufficient because the desktop process caches the event stream. A safe smoke test is a short prompt that asks for a confirmation only; do not resume the user's old project task automatically.
If compaction succeeds and the error changes to authentication, transport, or provider availability, stop treating it as a session-file problem and diagnose that separate issue. If a new stale ID appears after a clean reload, re-run the dry-run report before changing anything else.
Bundled tools
Install this skill with npx skills add WardLu/skills --skill codex-cross-provider-session-repair --global --agent codex --yes, or use the platform installer documented in README.md.
scripts/repair.py— deterministic, backup-first diagnosis and target-scoped repair.scripts/start_repair.py— recommended consent-to-terminal launcher; opens a readable 120×36 Terminal tab/window on macOS, hides the long worker command behind a temporary runner, and starts the worker even when Codex was already closed.scripts/wait_and_repair.py— process-aware wait/apply/verify wrapper for use from an independent Terminal. It fails closed if Codex was not detected initially, reappears during the stability window, or changes the rollout while waiting.scripts/compaction_shim.py— optional loopback shim that supplies Codex remote compaction v2 on behalf of a backend that does not implement it. It must remain in the request path while it is in use, otherwise every request through that provider URL fails.scripts/repair_session_offline.py— runs that shim for one over-limit session while Codex is quit, with backup-first writes and count-based verification. It never editsconfig.toml.tests/test_repair.py— offline tests using temporary fake Codex homes and SQLite databases.tests/test_wait_and_repair.py— offline tests for process lifecycle, rollout race protection, status files, and end-to-end verification.tests/test_compaction_shim.py— offline tests for request classification, summary encoding, replay expansion, and a live handler round trip against a fake upstream.tests/test_repair_session_offline.py— offline tests for the repair runner using a fake Codex CLI: dry run, verification, writer-lock blocker, backups, and refusals.README.md— installation, upgrade, release, and troubleshooting guide.
Documentation
The English installation and maintenance guide is README.md; Simplified Chinese users can use the synchronized README.zh-CN.md guide.
Report format
Give the user a concise result with: root cause, exact target session, files changed, backup paths, verification counts, whether the independent process-aware run reached verified, whether an independent smoke test reached Context compacted, and the one required restart step. For an offline compaction repair, state the compacted count before and after, that the last task_complete error is now null, and whether the session model is unchanged. When the wait ends in a timeout, explicitly state that the configured wait limit was reached, no files were changed, and the user must fully quit Codex before retrying. Never include credentials or full JSONL lines.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

