Skip to content

fix(codex): auto-restore the codex shim after external npm updates (#320)#356

Merged
lidge-jun merged 5 commits into
devfrom
codex/260724-shim-autorestore
Jul 24, 2026
Merged

fix(codex): auto-restore the codex shim after external npm updates (#320)#356
lidge-jun merged 5 commits into
devfrom
codex/260724-shim-autorestore

Conversation

@lidge-jun

@lidge-jun lidge-jun commented Jul 23, 2026

Copy link
Copy Markdown
Owner

Summary

Addresses the actionable half of #320: when @openai/codex is updated via external npm, the replaced launcher silently loses the OpenCodex shim until the user manually runs ocx codex-shim install. The CLI now detects the replaced launcher on ordinary ocx startup and restores the shim automatically.

(Part 1 of #320 — the native login gate firing before proxy traffic — remains an upstream Codex CLI limitation and is intentionally out of scope.)

Design

  • Hook point: ordinary CLI startup after help/version early-exits. The healthy path is a bounded read-only probe — measured median 0.026 ms / p95 0.040 ms over 1,000 samples, zero writes, config not even loaded.
  • Restore = the existing install path. Auto-restore reuses the same shim install transaction as ocx codex-shim install; no duplicated logic.
  • All-or-nothing multi-wrapper repair: all wrapper paths are fingerprint-checked before ANY mutation; a mid-sequence failure rolls back already-renamed siblings in reverse order (activation-tested with a second-sibling drift scenario).
  • npm-in-progress safety: a freshly-written launcher defers restore until the binary is stable, so we never fight a running npm install.
  • Fail-safe: any restore failure degrades to a one-line warning; the user's command always proceeds. Missing backup / corrupt state / platform mismatch never triggers a fresh install.
  • Opt-out: config flag + env var (documented in the configuration reference, 5 locales synced).

Tests

+382 test lines across tests/codex-shim.test.ts, tests/codex-shim-autorestore.test.ts, tests/config.test.ts — named activations for: replaced→restore+warn, intact→zero-overhead, failure→warn-only, opt-out, sibling-drift rollback, npm-in-progress defer, and never-fresh-install guards.

  • typecheck exit 0; focused 88 pass / 0 fail; full suite 3876 pass / 0 fail (314 files); privacy:scan pass.
  • Local verification is macOS; Windows wrapper behavior relies on cross-platform CI.

Security review

Credential-path-adjacent (shim wraps the codex launcher): explicit maintainer security review requested before merge per MAINTAINERS.md. No auth flow changes; writes are confined to shim wrapper paths and their backups.

Design/audit trail: devlog/_plan/260724_bugfix_train/030_shim_autorestore.md.

Refs #320.

Summary by CodeRabbit

  • New Features
    • Automatically restores Codex shims after stable external Codex updates on the next regular command.
    • Adds codexShimAutoRestore (default on) and OPENCODEX_CODEX_SHIM_AUTO_RESTORE=0 to disable auto-restore; skips during uninstall/remove flows.
  • Bug Fixes
    • Repair now warns only on failure and never blocks the requested command.
    • Help/usage invocations no longer modify launcher files.
  • Documentation
    • Updated CLI/config/runtime and multilingual docs, including manual fallback via ocx codex-shim install.
  • Tests
    • Expanded unit, integration, concurrency/lock-safety, and help-exit coverage.

@lidge-jun
lidge-jun requested a review from Ingwannu as a code owner July 23, 2026 18:26
@github-actions github-actions Bot added the bug Something isn't working label Jul 23, 2026
@coderabbitai

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The CLI now restores stable external Codex shim replacements before eligible commands. The implementation adds fingerprint probing, guarded transactional rollback, configuration and environment opt-outs, CLI policy handling, tests, and multilingual documentation.

Changes

Codex shim auto-restore

Layer / File(s) Summary
Restore configuration and contracts
src/config.ts, src/types.ts, src/codex/shim.ts, tests/config.test.ts
Adds codexShimAutoRestore, its environment override, default-enabled behavior, diagnostics, and structured restore result statuses.
Probe and transactional restoration
src/codex/shim.ts, tests/codex-shim.test.ts
Detects stable overwritten launchers using bounded fingerprints and prefixes, then performs guarded multi-wrapper refreshes with validation, rollback, and no fresh installation for ineligible state.
CLI startup wiring and validation
src/cli/*.ts, tests/codex-shim-autorestore.test.ts, tests/cli-help.test.ts
Runs restoration before dispatch, preserves help exits, applies subcommand policy, evaluates opt-outs lazily, warns on outcomes, and preserves requested command execution.
Runtime and user documentation
README*.md, docs-site/src/content/docs/**, structure/01_runtime.md
Documents automatic repair on the next ordinary command, stability and retry behavior, warning-only failures, manual installation, and opt-out controls.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant CLI
  participant AutoRestore
  participant ShimStore
  User->>CLI: run eligible ocx command
  CLI->>AutoRestore: check command and configuration
  AutoRestore->>ShimStore: probe launcher fingerprints
  ShimStore-->>AutoRestore: stable replacement detected
  AutoRestore->>ShimStore: backup and guarded restore
  ShimStore-->>AutoRestore: restore result
  AutoRestore-->>CLI: warning if restored or failed
  CLI-->>User: continue requested command
Loading

Possibly related PRs

Suggested reviewers: ingwannu

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: automatic Codex shim auto-restore after external npm updates.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/260724-shim-autorestore

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ec1418b670

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/cli/index.ts
process.exit(0);
}

maybeAutoRestoreCodexShim(command, args);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bypass auto-restore for top-level help

In src/cli/index.ts, ocx --help, ocx -h, bare ocx help, and invocation without arguments do not match any preceding early exit, so this call can rename Codex launchers and write shim state before merely printing usage. Move these top-level help/empty-argument cases ahead of auto-restore or include them in the skip policy so help remains side-effect free.

AGENTS.md reference: AGENTS.md:L19-L20

Useful? React with 👍 / 👎.

Comment thread src/codex/shim.ts Outdated
function fingerprintIsOldEnough(fingerprint: ShimPathFingerprint, nowMs: number): boolean {
const timestamps = [fingerprint.mtimeMs, fingerprint.ctimeMs];
if (fingerprint.target) timestamps.push(fingerprint.target.mtimeMs, fingerprint.target.ctimeMs);
return nowMs - Math.max(...timestamps) >= CODEX_SHIM_REPLACEMENT_STABLE_MS;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Observe replacements for the full stability interval

In fingerprintIsOldEnough, an old mtime/ctime only proves that no recorded metadata change happened recently; it does not prove that this fingerprint remained unchanged for 100 ms. If npm pauses for more than 100 ms midway through writing a launcher and another ocx command runs, the partial launcher is accepted and replaces the known-good backup; a subsequently failed update then leaves the shim executing that partial file. Record two matching fingerprints separated by the interval, or persist the first observation and defer until a later probe confirms it.

AGENTS.md reference: AGENTS.md:L19-L20

Useful? React with 👍 / 👎.

Comment thread src/codex/shim.ts
Comment on lines +860 to +862
if (probe.prefix.includes(SHIM_MARKER)) {
if (!isHealthyShimProbe(probe, state.platform)) return { status: "ineligible" };
continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Defer mixed Windows launcher sets

On Windows, when npm has replaced one tracked launcher but another sibling is still the old healthy shim, this continue treats the mixed set as eligible and the transaction repairs only the replaced path. A slow sequential npm update can therefore be modified while it is still processing the remaining .cmd, .ps1, or extensionless launchers, defeating the documented mixed-sibling safety guard. Defer whenever some non-preserve siblings are external replacements and others are still shims, then repair only after the launcher set is consistent.

AGENTS.md reference: AGENTS.md:L19-L20

Useful? React with 👍 / 👎.

Comment thread src/codex/shim.ts
if (existsSync(entry.stagedOldBackupPath)) unlinkSync(entry.stagedOldBackupPath);
renameSync(operation.file.backupPath, entry.stagedOldBackupPath);
}
renameSync(operation.sourcePath, operation.file.backupPath);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Serialize concurrent auto-restore transactions

If two ordinary ocx processes detect the same replacement concurrently, both can pass the fingerprint check before either reaches this rename. After one process stages the old backup and installs its shim, the other can rename that newly written shim over the replacement backup on POSIX; the resulting wrapper then executes a backup that is itself a shim, causing recursive launches and losing the updated Codex launcher. Protect the complete guarded transaction with an interprocess lock or use conditional no-replace operations that abort when either source or destination has changed.

AGENTS.md reference: AGENTS.md:L19-L20

Useful? React with 👍 / 👎.

Comment thread src/codex/shim.ts Outdated
/** Narrow deterministic race seam for the guarded transaction tests. */
beforeGuardedRefresh?: (wrapperPath: string, index: number) => void;
}): CodexShimAutoRestoreResult {
const state = readState();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound the startup state read

Every ordinary command now enters autoRestoreCodexShim, whose first operation calls readState; that helper uses an unbounded readFileSync followed by JSON.parse. If codex-shim.json becomes oversized or is replaced with a non-regular file, every ocx command can consume unbounded memory or block before dispatch instead of taking the documented bounded probe path. Validate that the state path is a small regular file and cap the bytes read before parsing it.

AGENTS.md reference: AGENTS.md:L19-L20

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs-site/src/content/docs/ru/reference/cli.md`:
- Line 401: Исправьте опечатку в пользовательской документации: в описании
поведения `ocx` замените термин «лончер» на стандартный вариант «лаунчер», не
изменяя остальной текст.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: fb5f8b6b-de03-47da-ae68-fc5dbc2cbf1f

📥 Commits

Reviewing files that changed from the base of the PR and between 05ee9ec and ec1418b.

📒 Files selected for processing (24)
  • README.ja.md
  • README.ko.md
  • README.md
  • README.ru.md
  • README.zh-CN.md
  • docs-site/src/content/docs/ja/reference/cli.md
  • docs-site/src/content/docs/ja/reference/configuration.md
  • docs-site/src/content/docs/ko/reference/cli.md
  • docs-site/src/content/docs/ko/reference/configuration.md
  • docs-site/src/content/docs/reference/cli.md
  • docs-site/src/content/docs/reference/configuration.md
  • docs-site/src/content/docs/ru/reference/cli.md
  • docs-site/src/content/docs/ru/reference/configuration.md
  • docs-site/src/content/docs/zh-cn/reference/cli.md
  • docs-site/src/content/docs/zh-cn/reference/configuration.md
  • src/cli/codex-shim-autorestore.ts
  • src/cli/index.ts
  • src/codex/shim.ts
  • src/config.ts
  • src/types.ts
  • structure/01_runtime.md
  • tests/codex-shim-autorestore.test.ts
  • tests/codex-shim.test.ts
  • tests/config.test.ts

Если обновление Codex перезаписало обёртку, shim автоматически восстанавливается при следующем
вызове `install` — новый бинарный файл резервируется, и записывается свежая обёртка.
Если завершённое внешнее обновление Codex перезаписало установленный shim, следующая обычная команда
`ocx` до запуска сохранит стабильный новый лончер в резервную копию и восстановит shim. Лончер,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Исправьте опечатку в пользовательской документации.

Используйте стандартную транслитерацию лаунчер вместо лончер, чтобы термин совпадал с остальным русским текстом.

Предлагаемое исправление
- до запуска сохранит стабильный новый лончер в резервную копию и восстановит shim. Лончер,
+ до запуска сохранит стабильный новый лаунчер в резервную копию и восстановит shim. Лаунчер,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
`ocx` до запуска сохранит стабильный новый лончер в резервную копию и восстановит shim. Лончер,
`ocx` до запуска сохранит стабильный новый лаунчер в резервную копию и восстановит shim. Лаунчер,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs-site/src/content/docs/ru/reference/cli.md` at line 401, Исправьте
опечатку в пользовательской документации: в описании поведения `ocx` замените
термин «лончер» на стандартный вариант «лаунчер», не изменяя остальной текст.

@Wibias

Wibias commented Jul 23, 2026

Copy link
Copy Markdown
Collaborator

Dual review (security + bugs/edge cases)

Bot review threads are not cleared yet (6 unresolved: 5 Codex P2 + 1 CodeRabbit docs typo). Below is an independent second look. This PR is credential-path-adjacent (mutates Codex launchers that load OPENCODEX_API_AUTH_TOKEN); CI is green, but maintainer security review remains warranted before merge.

Security categories checked

No evidence of malware, backdoor, hidden remote C2, local admission bypass, classic XSS, or credential logging/serialization. Writes stay on shim wrapper / backup paths plus OPENCODEX_HOME/codex-shim.json. Token injection in rewritten wrappers reuses the existing shim templates (pre-existing pattern), not a new auth flow.

Fail-safe shape looks intentional and largely sound: allowFreshInstall: false on the auto path, opt-out via config/OPENCODEX_CODEX_SHIM_AUTO_RESTORE=0, restore failures degrade to a warning, and the healthy path is a bounded prefix probe that does not load config.

Blockers

  1. Concurrent auto-restore can nest shims / lose the real launcher (High)src/codex/shim.ts (applyGuardedRefreshTransaction)
    Two ocx processes can both pass the pre-rename fingerprint check, then both run the rename→writeShim sequence. After process A stages the npm launcher into the backup and writes a shim, process B can rename that new shim onto the backup and rewrite the wrapper again. The backup then becomes a shim, so later launches recurse (shim → ensure → shim…) and the updated Codex binary is lost. Intra-process re-probe / rollback tests do not cover this cross-process race. Needs an interprocess lock around the guarded transaction, or conditional no-clobber ops that abort when source/destination identity changed.

  2. Stability check is mtime-age only, not “unchanged for N ms” (High)fingerprintIsOldEnough
    An old mtime/ctime does not prove the bytes stayed stable for CODEX_SHIM_REPLACEMENT_STABLE_MS (100 ms). npm/tar extracts often preserve package mtimes, so a just-written launcher can look “old enough” immediately while siblings are still being updated. Auto-restore can then snapshot a partial/in-flight launcher into the owned backup. Prefer two matching probes separated by the interval (or persist the first observation and defer).

Should-fix before merge

  1. Mixed Windows launcher sets still repair (Medium)autoRestoreCodexShim
    Healthy shim siblings continue while replaced siblings are collected. On Windows, a sequential npm update of codex.cmd / .ps1 / extensionless codex can therefore be mutated mid-update, contrary to the “all-or-nothing / mixed-sibling safety” story. Defer while the tracked set is mixed (some external replacements, some still shims).

  2. Top-level help / bare ocx can mutate launchers (Medium)src/cli/index.ts
    maybeAutoRestoreCodexShim runs before the --help/-h/empty-argv usage path. Help/version early-exits above it do not cover these cases, so printing usage can rename wrappers and rewrite shim state. Skip auto-restore for top-level help and no-command invocations.

  3. Startup state read is unbounded (Medium)readState via every ordinary command
    readFileSync + JSON.parse on codex-shim.json with no size/type cap. A huge or non-regular state file turns every ocx invocation into an unbounded memory/blocking hit, contradicting the “bounded probe” claim. Stat as a small regular file and cap bytes before parse.

  4. State paths are trusted absolute targets (Medium, security)codex-shim.json
    Auto-restore does not re-bind wrapperPath / backupPath / realPath to current PATH discovery. Anyone who can write OPENCODEX_HOME can point repair at arbitrary paths (same privilege tier as config, but now exercised on every command). Consider path allowlisting / re-resolve against discoverable Codex launchers, or refuse restore when state paths diverge from discovery.

Non-blocking / already covered well

  • Never-fresh-install guards, opt-out laziness, intra-process fingerprint mismatch defer, and multi-wrapper rollback tests look solid.
  • Russian docs typo (лончерлаунчер) matches the open CodeRabbit thread — fix when touching docs.

Aligns with open bot threads

Findings 1–5 match the still-open Codex P2 threads (concurrency lock, stability observation, mixed Windows set, help side effects, bounded state read). Please resolve those after fixing, or reply why a finding does not apply.

Suggested fix order

  1. Serialize the guarded refresh (lock or atomic no-replace) and add a cross-process race test if feasible.
  2. Require two matching fingerprints separated by the stability interval (archive-mtime safe).
  3. Defer on mixed Windows sibling sets.
  4. Skip auto-restore for top-level help / empty argv; bound readState.
  5. Optionally harden state-path trust / re-discovery before merge given the security adjacency.

@lidge-jun

Copy link
Copy Markdown
Owner Author

Maintainer triage review (2026-07-24, post-#359 re-review). Direction is valid and this does NOT fight #359's persisted runtime selection (codex-runtime.json is untouched; configured runtime still wins over the shim candidate). However, merging as-is is blocked by real defects found in the restore transaction:

High — concurrent restore can lose the real launcher / create shim recursion. Two processes both pass the fingerprint check; process A writes the shim while process B renames that shim to backup (src/codex/shim.ts:691-713). There is no interprocess lock or conditional rename between verify and rename. Result: shim -> backup-shim recursion and the updated launcher is lost.

High — the "stable for 100ms" guarantee is only an mtime/ctime age check (src/codex/shim.ts:217-220, :858-865). An updater that stalls >100ms after a partial write gets its partial file promoted over the known-good backup.

Medium — Windows mixed sibling sets are restored piecemeal (.cmd replaced while .ps1/extensionless are still shims), contradicting the doc's own "mixed siblings defer" note (src/codex/shim.ts:638-646, :850-865).

Medium — bare ocx / ocx help / --help can mutate files before early exit (src/cli/index.ts:48-63, src/cli/codex-shim-autorestore.ts:18-32).

Medium — every normal invocation synchronously reads+parses all of codex-shim.json with no size/type bound (src/codex/shim.ts:493-516, :842-843); not a "bounded startup probe" for large or non-regular files.

Also note: the green CI on ec1418b predates the #359 merge, so exact-SHA cross-platform CI is needed after rework.

Suggested path: add an interprocess lock (or compare-and-rename) around the verify->rename transaction, observe real stability (two consecutive identical fingerprints across an interval, not just age), defer mixed sibling sets, move auto-restore behind the help early-exit, and bound the shim-state read. Happy to re-review promptly after a rebuild on current dev.

lidge-jun added a commit that referenced this pull request Jul 24, 2026
lidge-jun added a commit that referenced this pull request Jul 24, 2026
@lidge-jun
lidge-jun force-pushed the codex/260724-shim-autorestore branch from ec1418b to ce65a75 Compare July 24, 2026 03:27

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs-site/src/content/docs/reference/cli.md`:
- Around line 375-379: Clarify that `ocx codex-shim status` may perform
auto-restore and rewrite launcher files before reporting state, while preserving
the existing opt-out and repair behavior. Apply the same side-effect warning to
docs-site/src/content/docs/reference/cli.md:375-379,
docs-site/src/content/docs/ko/reference/cli.md:379-383, and
docs-site/src/content/docs/ru/reference/cli.md:400-405, translating it
appropriately in the Korean and Russian pages.

In `@src/codex/shim.ts`:
- Around line 691-703: The reclaimStaleRestoreLock function must atomically
detach the verified stale lock instead of deleting it by path. Replace
unlinkSync(path) with a renameSync operation to a unique temporary target, and
return true only when that rename succeeds; handle rename failures consistently,
including ENOENT, so a concurrent replacement cannot be removed.

In `@tests/codex-shim-autorestore.test.ts`:
- Around line 142-145: Update the autorestore verification around the wrapper
write and Bun.sleep flow to require two matching launcher-content fingerprints
separated by the stability interval, rather than relying only on elapsed
modification time. Add a regression test that changes the launcher between
observations and asserts the operation is deferred without mutating the launcher
or related state.
- Around line 127-129: Add a Windows-specific test fixture alongside “shim
replaced -> next ocx command auto-restores and warns” that creates mixed
shim/replacement launcher siblings, then asserts restoration is deferred and
every sibling remains unchanged. Exercise the tracked sibling set atomically,
including the .cmd and other launcher paths, rather than restoring any
individual sibling during a partial update.
- Around line 127-155: Serialize shim repair transactions across processes using
an interprocess exclusive lock or equivalent conditional-rename protocol in the
repair flow exercised by installCodexShim and the codex-shim status command.
After acquiring the lock, re-fingerprint the wrapper before modifying it so
stale classifications cannot overwrite the real launcher or create recursive
shims. Extend the existing integration coverage with two concurrent processes
and assert the backup codex.opencodex-real remains the external replacement.
- Around line 103-119: The auto-restore state-loading flow must preflight the
state path before reading contents: require a regular file and reject files
exceeding CODEX_SHIM_STATE_MAX_BYTES without invoking the content reader. Update
autoRestoreCodexShim and its state-read helper to validate size/type before
opening or reading, preferably via an opened descriptor to reduce races, and add
coverage proving oversized and non-regular paths never invoke the content
reader.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 72ac1cb3-97df-4030-b536-71cd611137de

📥 Commits

Reviewing files that changed from the base of the PR and between ec1418b and ce65a75.

📒 Files selected for processing (25)
  • README.ja.md
  • README.ko.md
  • README.md
  • README.ru.md
  • README.zh-CN.md
  • docs-site/src/content/docs/ja/reference/cli.md
  • docs-site/src/content/docs/ja/reference/configuration.md
  • docs-site/src/content/docs/ko/reference/cli.md
  • docs-site/src/content/docs/ko/reference/configuration.md
  • docs-site/src/content/docs/reference/cli.md
  • docs-site/src/content/docs/reference/configuration.md
  • docs-site/src/content/docs/ru/reference/cli.md
  • docs-site/src/content/docs/ru/reference/configuration.md
  • docs-site/src/content/docs/zh-cn/reference/cli.md
  • docs-site/src/content/docs/zh-cn/reference/configuration.md
  • src/cli/codex-shim-autorestore.ts
  • src/cli/index.ts
  • src/codex/shim.ts
  • src/config.ts
  • src/types.ts
  • structure/01_runtime.md
  • tests/cli-help.test.ts
  • tests/codex-shim-autorestore.test.ts
  • tests/codex-shim.test.ts
  • tests/config.test.ts

Comment on lines +375 to +379
If a completed external Codex update overwrites an installed shim, the next ordinary `ocx` command
backs up the stable new launcher and restores the shim before dispatch. A launcher that is still
changing is left untouched and retried later. Repair failures warn without failing the requested
command; manual fallback: `ocx codex-shim install`. Set `codexShimAutoRestore` to `false`, or set
`OPENCODEX_CODEX_SHIM_AUTO_RESTORE=0` for a process-level opt-out.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Clarify the status side effect consistently across locales.

The CLI leaves ocx codex-shim status eligible for auto-restore, so it can rewrite launcher files before reporting state. Update each page to state this explicitly, or change the policy if status must remain read-only.

  • docs-site/src/content/docs/reference/cli.md#L375-L379: document that English status invocations may perform repair.
  • docs-site/src/content/docs/ko/reference/cli.md#L379-L383: add the same side-effect warning to the Korean flow.
  • docs-site/src/content/docs/ru/reference/cli.md#L400-L405: add the same side-effect warning to the Russian flow.

As per path instructions, translated docs must remain synchronized with actual CLI behavior.

📍 Affects 3 files
  • docs-site/src/content/docs/reference/cli.md#L375-L379 (this comment)
  • docs-site/src/content/docs/ko/reference/cli.md#L379-L383
  • docs-site/src/content/docs/ru/reference/cli.md#L400-L405
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs-site/src/content/docs/reference/cli.md` around lines 375 - 379, Clarify
that `ocx codex-shim status` may perform auto-restore and rewrite launcher files
before reporting state, while preserving the existing opt-out and repair
behavior. Apply the same side-effect warning to
docs-site/src/content/docs/reference/cli.md:375-379,
docs-site/src/content/docs/ko/reference/cli.md:379-383, and
docs-site/src/content/docs/ru/reference/cli.md:400-405, translating it
appropriately in the Korean and Russian pages.

Source: Path instructions

Comment thread src/codex/shim.ts Outdated
Comment on lines +691 to +703
function reclaimStaleRestoreLock(path: string): boolean {
const before = statFingerprint(path, false);
if (!before || before.kind !== "file" || Date.now() - before.mtimeMs <= CODEX_SHIM_RESTORE_LOCK_STALE_MS) return false;
const after = statFingerprint(path, false);
if (!after || !sameFingerprint(before, after)) return false;
try {
unlinkSync(path);
return true;
} catch (error) {
if (fileErrorCode(error) === "ENOENT") return true;
return false;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm reclaimStaleRestoreLock is the only site that removes a *live* restore lock by path,
# and inspect every unlink of the restore lock file.
rg -nP -C3 'restoreLockPath|autorestore\.lock|reclaimStaleRestoreLock' src/codex/shim.ts
rg -nP -C2 'unlinkSync' src/codex/shim.ts

Repository: lidge-jun/opencodex

Length of output: 4130


🏁 Script executed:

sed -n '705,737p' src/codex/shim.ts
sed -n '718,734p' src/codex/shim.ts

Repository: lidge-jun/opencodex

Length of output: 2279


Make stale-lock reclamation atomic src/codex/shim.ts:691-703

reclaimStaleRestoreLock() deletes by unlinkSync(path) after two matching stats. If two processes decide the lock is stale before either unlinks it, the first can remove the old inode, reacquire the lock, and the second can then unlink that fresh lock by path. Both processes can then enter restore work at the same time, so this no longer guarantees mutual exclusion.

Use an atomic reclaim instead: move the stale lock aside with a unique renameSync(...) target and only continue if that rename succeeds.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/codex/shim.ts` around lines 691 - 703, The reclaimStaleRestoreLock
function must atomically detach the verified stale lock instead of deleting it
by path. Replace unlinkSync(path) with a renameSync operation to a unique
temporary target, and return true only when that rename succeeds; handle rename
failures consistently, including ENOENT, so a concurrent replacement cannot be
removed.

Comment on lines +103 to +119
test("oversized shim state is bounded, skipped, and warned without loading config", () => {
const home = mkdtempSync(join(tmpdir(), "ocx-shim-oversized-state-"));
const oldHome = process.env.OPENCODEX_HOME;
try {
process.env.OPENCODEX_HOME = home;
const statePath = join(home, "codex-shim.json");
writeFileSync(statePath, Buffer.alloc(CODEX_SHIM_STATE_MAX_BYTES + 1, 0x20));
const before = readFileSync(statePath);
const { deps, warnings, readConfigCalls } = cliDeps({ status: "healthy" }, {
restore: autoRestoreCodexShim,
});

maybeAutoRestoreCodexShim("status", ["status"], deps);

expect(warnings).toEqual([expect.stringContaining("exceeds the 1 MiB startup limit")]);
expect(readConfigCalls()).toBe(0);
expect(readFileSync(statePath)).toEqual(before);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Reject unsafe state files before reading their contents.

This test passes even if autoRestoreCodexShim reads the entire oversized file and only then checks its length. Per the PR objectives, state reads are synchronous and currently lack file-type/size preflight, so an arbitrary-size file can allocate memory and a FIFO can block CLI startup. Validate a regular file and its size before opening/reading it (preferably from the opened descriptor to reduce races), and add a test proving the content reader is never invoked for oversized and non-regular state paths.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/codex-shim-autorestore.test.ts` around lines 103 - 119, The
auto-restore state-loading flow must preflight the state path before reading
contents: require a regular file and reject files exceeding
CODEX_SHIM_STATE_MAX_BYTES without invoking the content reader. Update
autoRestoreCodexShim and its state-read helper to validate size/type before
opening or reading, preferably via an opened descriptor to reduce races, and add
coverage proving oversized and non-regular paths never invoke the content
reader.

Source: Path instructions

Comment on lines +127 to +129
test("shim replaced -> next ocx command auto-restores and warns", async () => {
if (process.platform === "win32") return;
const binDir = mkdtempSync(join(tmpdir(), "ocx-shim-activation-bin-"));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Add Windows sibling-set restoration coverage.

Returning on Windows leaves the .cmd/other launcher-sibling path untested, despite the identified risk of repairing one sibling while another is mid-update. Add a Windows fixture that creates mixed shim/replacement siblings and assert restoration defers without changing any sibling; the implementation must treat the tracked sibling set atomically.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/codex-shim-autorestore.test.ts` around lines 127 - 129, Add a
Windows-specific test fixture alongside “shim replaced -> next ocx command
auto-restores and warns” that creates mixed shim/replacement launcher siblings,
then asserts restoration is deferred and every sibling remains unchanged.
Exercise the tracked sibling set atomically, including the .cmd and other
launcher paths, rather than restoring any individual sibling during a partial
update.

Source: Path instructions

Comment on lines +127 to +155
test("shim replaced -> next ocx command auto-restores and warns", async () => {
if (process.platform === "win32") return;
const binDir = mkdtempSync(join(tmpdir(), "ocx-shim-activation-bin-"));
const home = mkdtempSync(join(tmpdir(), "ocx-shim-activation-home-"));
const wrapper = join(binDir, "codex");
const backup = join(binDir, "codex.opencodex-real");
const replacement = "#!/bin/sh\necho externally updated codex\n";
const oldPath = process.env.PATH;
const oldHome = process.env.OPENCODEX_HOME;
try {
process.env.PATH = binDir;
process.env.OPENCODEX_HOME = home;
writeFileSync(wrapper, "#!/bin/sh\necho original codex\n", "utf8");
chmodSync(wrapper, 0o755);
expect(installCodexShim().installed).toBe(true);
writeFileSync(wrapper, replacement, "utf8");
chmodSync(wrapper, 0o755);
await Bun.sleep(120);

const result = spawnSync(process.execPath, [join(import.meta.dir, "..", "src", "cli", "index.ts"), "codex-shim", "status"], {
encoding: "utf8",
env: { ...process.env, PATH: binDir, OPENCODEX_HOME: home },
});

expect(result.status).toBe(0);
expect(result.stderr).toContain("automatic repair after Codex update");
expect(result.stdout).toContain("wrapper shim present");
expect(readFileSync(wrapper, "utf8")).toContain(SHIM_MARKER);
expect(readFileSync(backup, "utf8")).toBe(replacement);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🔴 Critical | 🏗️ Heavy lift

Serialize concurrent repair transactions.

This integration test exercises only one ocx process. The unresolved concurrent-repair path allows two processes to classify the same replacement, then overwrite the backup with a shim; that loses the real launcher and can produce recursive shims. Add an interprocess exclusive lock (or an equivalent conditional rename protocol), re-fingerprint after acquiring it, and add a two-process regression test asserting the backup remains the external replacement.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/codex-shim-autorestore.test.ts` around lines 127 - 155, Serialize shim
repair transactions across processes using an interprocess exclusive lock or
equivalent conditional-rename protocol in the repair flow exercised by
installCodexShim and the codex-shim status command. After acquiring the lock,
re-fingerprint the wrapper before modifying it so stale classifications cannot
overwrite the real launcher or create recursive shims. Extend the existing
integration coverage with two concurrent processes and assert the backup
codex.opencodex-real remains the external replacement.

Source: Path instructions

Comment on lines +142 to +145
writeFileSync(wrapper, replacement, "utf8");
chmodSync(wrapper, 0o755);
await Bun.sleep(120);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Verify stable content twice, not just elapsed mtime.

Sleeping after one static write only validates timestamp-age gating. A launcher can still be actively written after its timestamp becomes old enough. Require two matching fingerprints separated by the stability interval, and add a regression that changes launcher content between observations and asserts a deferred, non-mutating result.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/codex-shim-autorestore.test.ts` around lines 142 - 145, Update the
autorestore verification around the wrapper write and Bun.sleep flow to require
two matching launcher-content fingerprints separated by the stability interval,
rather than relying only on elapsed modification time. Add a regression test
that changes the launcher between observations and asserts the operation is
deferred without mutating the launcher or related state.

Source: Path instructions

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/codex/shim.ts`:
- Around line 748-767: Update reclaimStaleRestoreLock to handle lock directories
where readShimRestoreLockSnapshot returns no valid snapshot: use the directory
mtime, verify it exceeds CODEX_SHIM_RESTORE_LOCK_STALE_MS, confirm the lock
owner is not active when applicable, then remove the abandoned directory safely.
Preserve the existing snapshot comparison and token-specific unlink path for
valid lock records, and ensure tryAcquireShimRestoreLock can recover from empty
or malformed directories.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 8e3e9cd7-69d3-4419-92d1-1ea9d6078a8c

📥 Commits

Reviewing files that changed from the base of the PR and between ce65a75 and 916351f.

📒 Files selected for processing (3)
  • src/codex/shim.ts
  • structure/01_runtime.md
  • tests/codex-shim.test.ts

Comment thread src/codex/shim.ts
Comment on lines +748 to +767
function reclaimStaleRestoreLock(path: string, beforeDelete?: () => void): boolean {
const observed = readShimRestoreLockSnapshot(path);
if (!observed) return false;
const createdAt = Math.max(observed.record.createdAt, observed.fingerprint.mtimeMs);
if (Date.now() - createdAt <= CODEX_SHIM_RESTORE_LOCK_STALE_MS) return false;
if (isProcessAlive(observed.record.pid)) return false;
const current = readShimRestoreLockSnapshot(path);
if (!current || !sameShimRestoreLock(observed, current)) return false;
beforeDelete?.();
try {
// The token is part of the owner filename. Even if the lock directory is
// replaced after the comparison, this unlink cannot target a successor's
// differently named owner record.
unlinkSync(observed.ownerPath);
rmdirSync(path);
return true;
} catch {
return false;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm the only lock-dir cleanup paths, and that no age/empty-dir reclamation already exists.
rg -nP -C3 'restoreLockPath|reclaimStaleRestoreLock|rmdirSync|readShimRestoreLockSnapshot' src/codex/shim.ts
# Inspect the omitted guarded-refresh range for any hidden lock cleanup.
sed -n '828,967p' src/codex/shim.ts

Repository: lidge-jun/opencodex

Length of output: 8765


Reclaim malformed restore lock directories
src/codex/shim.ts:748-823 can permanently wedge auto-restore after a crash between mkdirSync(path) and owner-file creation at openSync(ownerPath, "wx"): readShimRestoreLockSnapshot() only succeeds when the lock dir contains exactly one *.json owner file, so an empty or malformed directory makes reclaimStaleRestoreLock() return false and tryAcquireShimRestoreLock() defer forever on every later run.

Add a fallback for non-snapshot lock dirs older than CODEX_SHIM_RESTORE_LOCK_STALE_MS (using the directory mtime) so abandoned/garbled lock dirs self-heal instead of blocking restore indefinitely.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/codex/shim.ts` around lines 748 - 767, Update reclaimStaleRestoreLock to
handle lock directories where readShimRestoreLockSnapshot returns no valid
snapshot: use the directory mtime, verify it exceeds
CODEX_SHIM_RESTORE_LOCK_STALE_MS, confirm the lock owner is not active when
applicable, then remove the abandoned directory safely. Preserve the existing
snapshot comparison and token-specific unlink path for valid lock records, and
ensure tryAcquireShimRestoreLock can recover from empty or malformed
directories.

@lidge-jun
lidge-jun merged commit 4f662ef into dev Jul 24, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants