Skip to content

Comments

fix: implement cache isolation to resolve OAuth plugin conflicts (Issue #25)#28

Merged
riatzukiza merged 5 commits intostagingfrom
fix/issue-25-oauth-cache-conflicts
Nov 19, 2025
Merged

fix: implement cache isolation to resolve OAuth plugin conflicts (Issue #25)#28
riatzukiza merged 5 commits intostagingfrom
fix/issue-25-oauth-cache-conflicts

Conversation

@riatzukiza
Copy link
Collaborator

Issue 25 – OAuth Cache Conflicts Between Plugins

Issue: #25 (BUG) Plugin fails with confusing errors if started with the other oauth plugin's cache files

Context & Current Behavior

  • Problem: Users switching from opencode-openai-codex-auth to @openhax/codex encounter cache conflicts
  • Root Cause: Both plugins use the same cache directory (~/.opencode/cache/) but with different:
    • Cache file formats
    • Fetch URLs (different GitHub repositories)
    • Metadata structures
  • Error Message: Failed to fetch OpenCode codex.txt: 404 Failed to fetch OpenCode codex.txt from GitHub
  • User Impact: Poor conversion experience, users think our plugin is broken

Current Cache Files

  • lib/prompts/opencode-codex.ts:31-129 - Fetches from sst/opencode repo
  • lib/utils/cache-config.ts:26-35 - Defines cache file names:
    • opencode-codex.txt - OpenCode prompt content
    • opencode-codex-meta.json - ETag and metadata
  • Cache location: ~/.opencode/cache/ (shared with other plugin)

Solution Strategy

1. Plugin-Specific Cache Namespace

Goal: Isolate our cache files from other plugins
Implementation:

  • Add plugin identifier prefix to cache files
  • Use openhax-codex- prefix for all cache files
  • Update cache paths to use plugin-specific subdirectory

2. Graceful Cache Migration & Validation

Goal: Handle existing cache files gracefully
Implementation:

  • Detect incompatible cache formats
  • Provide clear migration messages
  • Fallback to fresh fetch when cache is invalid
  • Don't fail with cryptic errors

3. Enhanced Error Handling

Goal: Better user experience during plugin switching
Implementation:

  • Detect cache conflict scenarios
  • Provide helpful error messages
  • Suggest cache cleanup steps
  • Continue operation when possible

Implementation Plan

Phase 1: Plugin-Specific Cache Files

  1. Update lib/utils/cache-config.ts:
    • Add plugin-specific cache file names
    • Use openhax-codex- prefix
  2. Update lib/prompts/opencode-codex.ts:
    • Use new cache file paths
    • Maintain backward compatibility during migration
  3. Update lib/prompts/codex.ts:
    • Apply same prefix to Codex instruction cache

Phase 2: Cache Validation & Migration

  1. Add cache format validation:
    • Check if cache files are from our plugin
    • Detect incompatible formats
  2. Implement graceful migration:
    • Backup existing cache if needed
    • Create fresh cache files
    • Log migration actions

Phase 3: Enhanced Error Messages

  1. Improve error handling in lib/prompts/opencode-codex.ts:
    • Detect cache conflict scenarios
    • Provide actionable error messages
  2. Add cache cleanup guidance:
    • Suggest manual cleanup steps
    • Include commands for cache reset

Definition of Done / Requirements

Functional Requirements

  • Plugin uses isolated cache files with openhax-codex- prefix
  • Graceful handling of existing cache from other plugins
  • Clear error messages when cache conflicts are detected
  • Automatic cache migration without user intervention
  • Fallback to fresh fetch when cache is incompatible

Non-Functional Requirements

  • No breaking changes for existing users of our plugin
  • Backward compatibility with our current cache format
  • Performance impact is minimal (cache isolation overhead)
  • Error messages are actionable and user-friendly

Test Coverage

  • Tests for cache file isolation
  • Tests for cache migration scenarios
  • Tests for error handling with invalid cache
  • Tests for backward compatibility
  • Integration tests for plugin switching scenarios

Files to Modify

Core Changes

  • lib/utils/cache-config.ts - Plugin-specific cache file names
  • lib/prompts/opencode-codex.ts - Isolated cache paths + validation
  • lib/prompts/codex.ts - Apply prefix to Codex cache files

Test Updates

  • test/prompts-opencode-codex.test.ts - Update cache file paths
  • test/prompts-codex.test.ts - Test cache isolation
  • Add new tests for cache migration and conflict handling

User Experience Improvements

Before (Current)

ERROR Failed to fetch OpenCode codex.txt: 404 Failed to fetch OpenCode codex.txt from GitHub

After (Target)

WARN Detected cache files from different plugin. Creating fresh cache for @openhax/codex...
INFO Cache migration completed successfully.
INFO Ready to use @openhax/codex with isolated cache.

Migration Strategy

For New Users

  • No impact - will start with clean, isolated cache

For Existing Users

  • Automatic migration on first run
  • Preserve existing cache in backup location
  • No manual intervention required
  • Clear communication about migration

For Users Switching Between Plugins

  • Graceful cache conflict detection
  • Actionable error messages
  • Simple cache cleanup commands if needed

Resolves Issue #25 - Plugin fails with confusing errors if started with the other oauth plugin's cache files

**Root Cause**: Both opencode-openai-codex-auth and @openhax/codex plugins used identical cache file names in ~/.opencode/cache/, causing conflicts when switching between plugins.

**Solution**:
1. **Cache Isolation** (lib/utils/cache-config.ts):
   - Added PLUGIN_PREFIX = "openhax-codex" for unique cache namespace
   - Updated cache files to use plugin-specific prefixes:
     - openhax-codex-instructions.md (was codex-instructions.md)
     - openhax-codex-opencode-prompt.txt (was opencode-codex.txt)
     - Corresponding metadata files with -meta.json suffix

2. **Migration Logic** (lib/prompts/opencode-codex.ts):
   - migrateLegacyCache(): Automatically detects and migrates old cache files
   - validateCacheFormat(): Detects incompatible cache formats from other plugins
   - Enhanced error messages with actionable guidance for cache conflicts

3. **Test Updates**:
   - Updated all test files to use new cache file names
   - All 123 tests passing ✅

**User Experience**:
- Seamless migration: Users switching plugins get automatic cache migration
- Clear error messages: When cache conflicts occur, users get actionable guidance
- No data loss: Existing cache content is preserved during migration

Files modified:
- lib/utils/cache-config.ts - Cache isolation configuration
- lib/prompts/opencode-codex.ts - Migration and validation logic
- test/prompts-opencode-codex.test.ts - Updated cache file paths
- test/prompts-codex.test.ts - Updated cache file paths
- spec/issue-25-oauth-cache-conflicts.md - Implementation spec
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 19, 2025

Warning

Rate limit exceeded

@riatzukiza has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 38 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 63c91a6 and 72b7616.

📒 Files selected for processing (2)
  • test/prompts-codex.test.ts (1 hunks)
  • test/prompts-opencode-codex.test.ts (5 hunks)

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced error handling for cache conflicts with detailed error messages and actionable troubleshooting recommendations.
    • Added cache format validation to detect and automatically resolve incompatibilities.
  • Chores

    • Implemented automatic migration of legacy cache data to plugin-specific locations for seamless system upgrades.
    • Improved cache metadata tracking for enhanced reliability and diagnostics.

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

Adds plugin-scoped cache filenames and migration from legacy caches, validates cache metadata (including source URL), updates the OpenCode codex fetch flow to handle conflicts and persistence, improves error messages with cache-clear guidance, and exposes a getCachedPromptPrefix(chars = 50) helper.

Changes

Cohort / File(s) Summary
Cache Configuration Updates
lib/utils/cache-config.ts
Added PLUGIN_PREFIX ("openhax-codex"), prefixed cache file names in CACHE_FILES, added OPENCODE_CODEX_META, and exported LEGACY_CACHE_FILES with legacy names for migration.
OpenCode Codex Core Logic
lib/prompts/opencode-codex.ts
Added legacy→plugin cache migration, cache format validation (checks url and structure), conflict-aware fetch flow using lastChecked, extended cache metadata (url, etag, lastFetch, lastChecked), improved error handling with explicit conflict/clear-cache hints, and exported getCachedPromptPrefix(chars = 50).
Tests
test/prompts-codex.test.ts, test/prompts-opencode-codex.test.ts
Updated tests to use prefixed cache filenames (openhax-codex-*) and added an assertion that mkdir is invoked when accessing cached prompt in one test.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant Logic as OpenCodeFetch
    participant Migrate as Migrator
    participant Cache as CacheStore
    participant Network as Remote

    Caller->>Logic: requestOpenCodeCodex()
    Logic->>Migrate: detect legacy files
    Migrate->>Cache: read legacy files
    Migrate->>Cache: copy → prefixed files & rename legacy → .bak

    Logic->>Cache: validate cache metadata (url & structure)
    alt valid && recent (lastChecked)
        Cache-->>Logic: return cached content
        Logic-->>Caller: cached result
    else invalid/stale
        Logic->>Network: fetch source URL
        Network-->>Logic: response (+etag) / error
        alt success
            Logic->>Cache: write content + metadata (url, etag, lastFetch, lastChecked)
            Logic-->>Caller: fresh result
        else failure & no valid cache
            Logic-->>Caller: error with conflict hint and cache-clear command
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Areas requiring extra attention:

  • Migration logic in lib/prompts/opencode-codex.ts: verify safe handling when both legacy and prefixed files exist and ensure backups (.bak) are correct.
  • Cache validation: confirm url-based incompatibility detection avoids false positives and that reset behavior is appropriate.
  • Error messages for 404/ENOENT and the suggested cache-clear command: ensure accuracy and clarity.
  • Tests: confirm all test expectations and mocked filesystem calls align with new openhax-codex-* filenames.

Poem

🔄 Legacy files move to a new nest,
📦 Prefixed caches tidy their rest,
🔍 Metadata guards the source and time,
🔁 Fetches refresh when the format’s not fine,
🛡️ Conflicts flagged, clear-cache hints in rhyme.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: implement cache isolation to resolve OAuth plugin conflicts (Issue #25)' clearly and specifically describes the main change: isolating cache to resolve plugin conflicts.
Description check ✅ Passed The description provides comprehensive context about the cache conflict issue, implementation strategy, and migration approach, directly addressing the changeset across all modified files.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/prompts/opencode-codex.ts (1)

114-123: Avoid logging expected cache-miss conditions as errors

Two paths currently log at error level for situations that are often normal:

  • Line 121: any failure reading the cache file/metadata logs logError("Failed to read OpenCode prompt cache", ...).
  • Line 239: getCachedPromptPrefix logs logError("Failed to read cached OpenCode prompt prefix", ...) on any read error.

For first-run scenarios (no cache yet) or a missing prefix file, these are expected ENOENTs rather than exceptional failures, and they can add noisy error logs.

You can keep visibility into real problems while avoiding noise by filtering out ENOENT:

-	} catch (error) {
-		// Cache doesn't exist or is invalid, will fetch fresh
-		const err = error as Error;
-		logError("Failed to read OpenCode prompt cache", { error: err.message });
-	}
+	} catch (error) {
+		// Cache doesn't exist or is invalid, will fetch fresh
+		const err = error as Error & { code?: string };
+		if (err.code !== "ENOENT") {
+			logError("Failed to read OpenCode prompt cache", { error: err.message });
+		}
+	}
-	} catch (error) {
-		const err = error as Error;
-		logError("Failed to read cached OpenCode prompt prefix", { error: err.message });
-		return null;
-	}
+	} catch (error) {
+		const err = error as Error & { code?: string };
+		if (err.code !== "ENOENT") {
+			logError("Failed to read cached OpenCode prompt prefix", { error: err.message });
+		}
+		return null;
+	}

This keeps genuine IO/parsing problems visible while treating “no cache yet” as a normal condition.

Also applies to: 232-241

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 058f596 and 180f9e4.

⛔ Files ignored due to path filters (2)
  • package.json is excluded by none and included by none
  • spec/issue-25-oauth-cache-conflicts.md is excluded by none and included by none
📒 Files selected for processing (4)
  • lib/prompts/opencode-codex.ts (9 hunks)
  • lib/utils/cache-config.ts (1 hunks)
  • test/prompts-codex.test.ts (1 hunks)
  • test/prompts-opencode-codex.test.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
lib/prompts/opencode-codex.ts (4)
lib/utils/file-system-utils.ts (1)
  • getOpenCodePath (22-24)
lib/utils/cache-config.ts (4)
  • LEGACY_CACHE_FILES (45-54)
  • CACHE_FILES (31-40)
  • PLUGIN_PREFIX (26-26)
  • CACHE_TTL_MS (11-11)
lib/logger.ts (2)
  • logWarn (75-77)
  • logInfo (71-73)
lib/cache/session-cache.ts (1)
  • openCodePromptCache (77-77)
🔇 Additional comments (2)
test/prompts-codex.test.ts (1)

33-34: Codex instructions test cache paths correctly namespaced

The updated cacheFile and cacheMeta names match the new CACHE_FILES prefixing and remain consistent across the test scenarios, including stale cache and fallback checks. No issues here.

test/prompts-opencode-codex.test.ts (1)

41-42: OpenCode prompt cache tests aligned with plugin-prefixed paths and mkdir behavior

The renamed cacheFile/cacheMetaFile values and the added mkdirMock expectation are consistent with the new CACHE_FILES configuration and getOpenCodeCodexPrompt’s unconditional mkdir call. The tests exercise both session-cache and file-cache flows without gaps.

Also applies to: 73-73

@riatzukiza
Copy link
Collaborator Author

Fixed the logging issues identified in the review:

  • Updated cache read error handling to filter out ENOENT errors (lines 121-123)
  • Updated getCachedPromptPrefix to avoid logging ENOENT errors (lines 241-243)

This prevents noisy error logs for expected first-run scenarios while preserving visibility into genuine I/O or parsing problems. All tests pass.

@riatzukiza
Copy link
Collaborator Author

✅ Review comments addressed

The logging improvements have been implemented:

  • ENOENT errors are now filtered out from cache read operations
  • Only genuine I/O/parsing problems are logged as errors
  • Expected first-run scenarios no longer generate noise

All tests pass and the cache isolation functionality remains intact.

- Add ENOENT filtering in getOpenCodeCodexPrompt cache read error handling
- Add ENOENT filtering in getCachedPromptPrefix error handling
- Prevents noisy error logs for expected first-run scenarios
- Preserves visibility into genuine I/O/parsing problems
- Addresses CodeRabbit review feedback on PR #28
- Keep plugin-prefixed cache file names from our branch
- Preserve cache isolation functionality
- Merge staging changes while maintaining Issue #25 fixes
@riatzukiza
Copy link
Collaborator Author

✅ Review Comment Resolution

Issue: Avoid logging expected cache-miss conditions as errors (lines 114-123, 232-241)

Root Cause: Cache read operations were logging ALL failures as errors, including expected ENOENT errors for first-run scenarios.

Solution Implemented:

  1. Line 121-123: Added ENOENT filtering in getOpenCodeCodexPrompt cache read error handling
  2. Line 241-243: Added ENOENT filtering in getCachedPromptPrefix error handling

Code Changes:
Before: Logged all errors
const err = error as Error;
logError("Failed to read OpenCode prompt cache", { error: err.message });

After: Filter ENOENT errors
const err = error as Error & { code?: string };
if (err.code !== "ENOENT") {
logError("Failed to read OpenCode prompt cache", { error: err.message });
}

Benefits:

  • ✅ Eliminates noisy error logs for expected first-run scenarios
  • ✅ Preserves visibility into genuine I/O/parsing problems
  • ✅ Maintains debugging capability for real issues
  • ✅ Follows logging best practices (don't log expected conditions as errors)

Verification:

  • All 381 tests pass
  • Cache isolation functionality intact
  • No breaking changes
  • Merge conflicts resolved

The review feedback has been fully addressed and tested.

@riatzukiza riatzukiza merged commit 601ee1b into staging Nov 19, 2025
11 checks passed
@riatzukiza riatzukiza deleted the fix/issue-25-oauth-cache-conflicts branch November 19, 2025 23:46
riatzukiza added a commit that referenced this pull request Nov 20, 2025
* device/stealth: commit local changes in submodule

* Docs: fix test README package name (#18)

* docs: reference @openhax/codex in test README

* Delete spec/issue-11-docs-package.md

* Add fork-aware prompt_cache_key derivation (#19)

* Refactor: Eliminate code duplication and improve maintainability

- Create shared clone utility (lib/utils/clone.ts) to eliminate 3+ duplicate implementations
- Create InputItemUtils (lib/utils/input-item-utils.ts) for centralized text extraction
- Centralize magic numbers in constants with SESSION_CONFIG, CONVERSATION_CONFIG, PERFORMANCE_CONFIG
- Add ESLint cognitive complexity rules (max: 15) to prevent future issues
- Refactor large functions to use shared utilities, reducing complexity
- Update all modules to use centralized utilities and constants
- Remove dead code and unused imports
- All 123 tests pass, no regressions introduced

Code quality improved from B+ to A- with better maintainability.

* testing!

* Address review: plugin config errors, compaction gating, cache key fallback

* Style and metrics cleanup for auth, cache, and sessions

* linting and formatting

* Finalize PR 20 review: shared clone utils and tests

* Fix CI workflow YAML syntax and quoting

* update lint rules

* allow lint warnings without masking errors

* seperate linting and formatting ci

* seperated formatting workflow from ci yaml and gave it permissions to edit workflow files

* opencode can respond to all pr comments

* Fix test/README.md documentation: update test counts and config file paths

- Update stale test counts to reflect actual numbers:
  * auth.test.ts: 16 → 27 tests
  * config.test.ts: 13 → 16 tests
  * request-transformer.test.ts: 30 → 123 tests
  * logger.test.ts: 5 → 7 tests
  * response-handler.test.ts: unchanged at 10 tests

- Fix broken configuration file paths:
  * config/minimal-opencode.json (was config/minimal-opencode.json)
  * config/full-opencode.json (was config/full-opencode.json)

Both configuration files exist in the config/ directory at repository root.

* 0.1.0

* 0.2.0

* docs: update AGENTS.md for gpt-5.1-codex-max support

- Update overview to reflect new gpt-5.1-codex-max model as default
- Add note about xhigh reasoning effort exclusivity to gpt-5.1-codex-max
- Document expanded model lineup matching Codex CLI

* chore: add v3.3.0 changelog entry for gpt-5.1-codex-max

- Document new Codex Max support with xhigh reasoning
- Note configuration changes and sample updates
- Record automatic reasoning effort downgrade fix for compatibility

* docs: update README for gpt-5.1-codex-max integration

- Add gpt-5.1-codex-max configuration with xhigh reasoning support
- Update model count from 20 to 21 variants
- Expand model comparison table with Codex Max as flagship default
- Add note about xhigh reasoning exclusivity and auto-downgrade behavior

* config: add gpt-5.1-codex-max to full-opencode.json

- Add flagship Codex Max model with 400k context and 128k output limits
- Configure with medium reasoning effort as default
- Include encrypted_content for stateless operation
- Set store: false for ChatGPT backend compatibility

* config: update minimal-opencode.json default to gpt-5.1-codex-max

- Change default model from gpt-5.1-codex to gpt-5.1-codex-max
- Align minimal config with new flagship Codex Max model
- Provide users with best-in-class default experience

* docs: update CONFIG_FIELDS.md for gpt-5.1-codex-max

- Add gpt-5.1-codex-max example configuration
- Document xhigh reasoning effort exclusivity and auto-clamping
- Remove outdated duplicate key example section
- Clean up reasoning effort notes with new xhigh behavior

* docs: add persistent logging note to TESTING.md

- Document new per-request JSON logging and rolling log files
- Note environment variables for enabling live console output
- Help developers debug with comprehensive logging capabilities

* feat: implement persistent rolling logging in logger.ts

- Add rolling log file under ~/.opencode/logs/codex-plugin/
- Write structured JSON entries with timestamps for all log levels
- Maintain per-request stage files for detailed debugging
- Improve error handling and log forwarding to OpenCode app
- Separate console logging controls from file logging

* feat: add gpt-5.1-codex-max support to request transformer

- Add model normalization for all codex-max variants
- Implement xhigh reasoning effort with auto-downgrade for non-max models
- Add Codex Max specific reasoning effort validation and normalization
- Ensure compatibility with existing model configurations

* types: add xhigh reasoning effort to TypeScript interfaces

- Add xhigh to ConfigOptions.reasoningEffort union type
- Add xhigh to ReasoningConfig.effort union type
- Enable type-safe usage of extra high reasoning for gpt-5.1-codex-max

* test: add gpt-5.1-codex-max to test-all-models.sh

- Add test case for new flagship Codex Max model
- Verify medium reasoning effort with auto summary and medium verbosity
- Ensure comprehensive testing coverage for all model variants

* test: fix codex-fetcher test headers mock

- Add default Authorization header to createCodexHeaders mock
- Prevent test failures due to missing required headers
- Ensure consistent test environment across all test runs

* test: update logger tests for persistent rolling logging

- Add tests for rolling log file functionality
- Update test structure to handle module caching properly
- Test console logging behavior with environment variables
- Verify error handling for file write failures
- Ensure appendFileSync is called for all log entries

* test: add appendFileSync mock to plugin-config tests

- Add missing appendFileSync mock to prevent test failures
- Ensure all file system operations are properly mocked
- Maintain test isolation and consistency

* test: add appendFileSync mock to prompts-codex tests

- Add appendFileSync mock to prevent test failures from logger changes
- Clear all mocks properly in beforeEach setup
- Ensure test isolation and consistency across test runs

* test: add comprehensive fs mocks to prompts-opencode-codex tests

- Add existsSync, appendFileSync, writeFileSync, mkdirSync mocks
- Clear all mocks in beforeEach for proper test isolation
- Prevent test failures from logger persistent logging changes
- Ensure consistent test environment across all test files

* test: add comprehensive gpt-5.1-codex-max test coverage

- Add model normalization tests for all codex-max variants
- Test xhigh reasoning effort behavior for codex-max vs other models
- Verify reasoning effort downgrade logic (minimal/none → low, xhigh → high)
- Add integration tests for transformRequestBody with xhigh reasoning
- Ensure complete test coverage for new Codex Max functionality

* docs: add specification files for gpt-5.1-codex-max and persistent logging

- Add comprehensive spec for Codex Max integration with xhigh reasoning
- Document persistent logging requirements and implementation plan
- Track requirements, references, and change logs for both features

* fix failing tests

* fix: implement cache isolation to resolve OAuth plugin conflicts

Resolves Issue #25 - Plugin fails with confusing errors if started with the other oauth plugin's cache files

**Root Cause**: Both opencode-openai-codex-auth and @openhax/codex plugins used identical cache file names in ~/.opencode/cache/, causing conflicts when switching between plugins.

**Solution**:
1. **Cache Isolation** (lib/utils/cache-config.ts):
   - Added PLUGIN_PREFIX = "openhax-codex" for unique cache namespace
   - Updated cache files to use plugin-specific prefixes:
     - openhax-codex-instructions.md (was codex-instructions.md)
     - openhax-codex-opencode-prompt.txt (was opencode-codex.txt)
     - Corresponding metadata files with -meta.json suffix

2. **Migration Logic** (lib/prompts/opencode-codex.ts):
   - migrateLegacyCache(): Automatically detects and migrates old cache files
   - validateCacheFormat(): Detects incompatible cache formats from other plugins
   - Enhanced error messages with actionable guidance for cache conflicts

3. **Test Updates**:
   - Updated all test files to use new cache file names
   - All 123 tests passing ✅

**User Experience**:
- Seamless migration: Users switching plugins get automatic cache migration
- Clear error messages: When cache conflicts occur, users get actionable guidance
- No data loss: Existing cache content is preserved during migration

Files modified:
- lib/utils/cache-config.ts - Cache isolation configuration
- lib/prompts/opencode-codex.ts - Migration and validation logic
- test/prompts-opencode-codex.test.ts - Updated cache file paths
- test/prompts-codex.test.ts - Updated cache file paths
- spec/issue-25-oauth-cache-conflicts.md - Implementation spec

* fixed minor type error

* test: remove redundant env reset and header mock

* Reduce console logging to debug flag

* fix: filter ENOENT errors from cache logging to reduce noise

- Add ENOENT filtering in getOpenCodeCodexPrompt cache read error handling
- Add ENOENT filtering in getCachedPromptPrefix error handling
- Prevents noisy error logs for expected first-run scenarios
- Preserves visibility into genuine I/O/parsing problems
- Addresses CodeRabbit review feedback on PR #28

* Use openhax/codex as plugin identifier

* Add fallback sources for OpenCode codex prompt

* Refresh OpenCode prompt cache metadata

* Refactor metrics response helpers and fix JWT decoding

* Tighten session tail slice to user/assistant only

* Improve compaction resilience and cache metrics safety

* Add release process documentation and open issues triage guide

- Add comprehensive RELEASE_PROCESS.md with step-by-step release workflow
- Add open-issues-triage.md for systematic issue management
- Both documents support better project governance and maintenance

* Strengthen tests for cache keys and gpt-5.1 cases

* Soften first-session cache warnings and sync transformed body

* Preseed session prompt cache keys

* Memoize config loading and keep bridge prompts stable

* Code cleanup: removed redundancy, improved tests

Co-authored-by: riatzukiza <riatzukiza@users.noreply.github.com>

* Fixed test shallow copy issue with deep copy.

Co-authored-by: riatzukiza <riatzukiza@users.noreply.github.com>

* chore(codex-max): memoize config loading, stabilize bridge prompts, and prep for Codex Max release; update request transforms and auth/session utilities; add lint-warnings spec

* stabilize oauth server tests by completing mocks

* fix: improve token refresh error handling and add debug logging

- Add debug logging to token refresh process in session-manager
- Improve error handling in codex-fetcher for 401 responses
- Fix fetch helper error handling for failed token refresh
- Add comprehensive test coverage for token refresh scenarios
- Add refresh-access-token spec documentation

* Fix test to assert on returned auth object instead of in-place mutation

- Update test/fetch-helpers.test.ts to properly validate refreshAndUpdateToken return value
- Add type guard for OAuth auth type checking
- Aligns test expectations with function's design of returning updated auth object
- All 396 tests pass with no TypeScript errors

* test: add negative test for host-provided prompt_cache_key; fix: ensure explicit Content-Type headers in OAuth server responses

- Add test to verify host-provided prompt_cache_key is preserved over session cache key
- Update OAuth server send helper to always include default Content-Type: text/plain; charset=utf-8
- Change headers parameter type to http.OutgoingHttpHeaders for stronger typing
- Preserve existing HTML response Content-Type override behavior

* fix: clone auth refresh and tighten console logging

* chore: guard disk logging and strengthen clones/roles

* fix: simplify role validation in formatRole function

- Remove hardcoded role whitelist in formatRole()
- Return normalized role directly without validation
- Add PR review documentation for CodeRabbit feedback

* Fix all CodeRabbit review issues from PR #29

## Critical Bug Fixes
- Fix content-type header bug in fetch-helpers.ts - preserve original content-type for non-JSON responses
- Fix cache fallback bug in codex.ts - wrap getLatestReleaseTag() in try/catch to ensure fallback chain works

## Test Improvements
- Remove unused mocks in cache-warming.test.ts areCachesWarm tests
- Fix mock leakage in index.test.ts by resetting sessionManager instance mocks
- Add missing compactionDecision test case in codex-fetcher.test.ts
- Remove redundant test case in codex-fetcher.test.ts

## Code Quality
- Harden logger against JSON.stringify failures with try/catch fallback
- Remove unused error parameter from logToConsole function
- Update type signatures to match new function signatures

## Documentation
- Add comprehensive PR analysis document in spec/pr-29-review-analysis.md

All tests pass (398 passed, 2 skipped) with 82.73% coverage.

* 📝 Add docstrings to `release/review-comments`

Docstrings generation was requested by @riatzukiza.

* #34 (comment)

The following files were modified:

* `lib/auth/server.ts`
* `lib/logger.ts`
* `lib/request/fetch-helpers.ts`

* Enhance compaction test coverage and fix linter warning

## Test Improvements
- Enhance compaction decision test in codex-fetcher.test.ts to validate full flow:
  - Verify recordSessionResponseFromHandledResponse called with compacted response
  - Verify fetcher returns the compacted response with correct status/body
  - Ensure complete end-to-end compaction flow validation

## Code Quality
- Fix linter warning in lib/auth/server.ts by prefixing unused parameter with underscore
- Update corresponding type definition in lib/types.ts to match

All tests continue to pass (398 passed, 2 skipped).

* Replace unsafe any cast with type-safe client access in logger

## Type Safety Improvements
- Add OpencodeApp type with proper notify/toast method signatures
- Add OpencodeClientWithApp intersection type for type-safe app access
- Create isOpencodeClientWithApp type guard function
- Replace (loggerClient as any)?.app with type-safe guarded access
- Update emit function to use type guard for loggerClient.app access

## Benefits
- Eliminates unsafe any type casting
- Provides compile-time type checking for app property access
- Maintains backward compatibility with existing OpencodeClient interface
- Follows TypeScript best practices for type guards

All tests continue to pass (398 passed, 2 skipped).

* Fix type safety in logger module

- Replace unsafe type casting with proper optional chaining
- Update notifyToast to use correct Opencode SDK API structure
- Use client.tui.showToast with proper body object format
- Remove unnecessary type guard function
- All tests pass and TypeScript compilation succeeds

* Clarify waitForCode state validation docs

---------

Co-authored-by: opencode-agent[bot] <opencode-agent[bot]@users.noreply.github.com>
Co-authored-by: riatzukiza <riatzukiza@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant