# Phase 4 Plan 1: Document Legacy JamTrack Implementation

<objective>
Document legacy JamTrack patterns, jamClient API, and React integration patterns to serve as reference for Phase 5 implementation.
</objective>

<execution_context>
@.planning/STATE.md
@.planning/ROADMAP.md
@.planning/phases/03-backing-track-finalization/03-03-SUMMARY.md
@web/app/assets/javascripts/dialog/openJamTrackDialog.js
@web/app/assets/javascripts/download_jamtrack.js.coffee
@web/app/assets/javascripts/react-components/stores/JamTrackStore.js.coffee
@web/app/assets/javascripts/bridge_api.es6
@jam-ui/src/components/client/JKSessionBackingTrackPlayer.js
@jam-ui/src/hooks/useMediaActions.js
</execution_context>

<context>
## Background

Phase 3 completed the Backing Track player implementation with established patterns:
- Redux-based state management (mediaSlice, sessionUISlice)
- jamClient async integration with error handling
- WebSocket real-time updates (MIXER_CHANGES)
- Modal/popup rendering duality
- Visibility-aware polling for playback monitoring

## Discovery Completed

Comprehensive exploration has identified:

**Legacy Implementation:**
- jQuery dialog for JamTrack selection with search/pagination
- CoffeeScript state machine for download/synchronization (8 states)
- Reflux stores for JamTrack and mixdown management
- jamClient API with 15+ JamTrack-specific methods

**Modern React Patterns:**
- Existing JamTrack components in jam-ui (modal, player, stems)
- Redux migration underway (MediaContext → mediaSlice)
- useMediaActions hook for async operations
- WebSocket integration via useSessionWebSocket

## Phase 4 Goal

Create comprehensive documentation to bridge legacy patterns to modern React architecture, enabling efficient Phase 5 implementation.
</context>

<tasks>
### Task 1: Create Legacy Implementation Documentation

**type:** auto

**files:**
- CREATE `.planning/codebase/JAMTRACK_LEGACY.md`

**action:**
Document the legacy JamTrack implementation patterns discovered during exploration:

1. **Legacy Dialog Patterns**
   - openJamTrackDialog.js: Selection UI with search/pagination
   - File location, initialization pattern, callback structure
   - Data flow: dialog → REST API → selection callback → loadJamTrack()

2. **Download/Sync State Machine**
   - download_jamtrack.js.coffee: 8-state synchronization engine
   - States: no_client, synchronized, packaging, downloading, keying, initial, quiet, errored
   - Key operations: download initiation, progress tracking, encryption key handling
   - Integration with jamClient methods

3. **Store Patterns**
   - JamTrackStore.js.coffee: Mixdown synchronization state management
   - JamTrackMixdownStore.js.coffee: Mixdown CRUD operations
   - pickMyPackage() logic for compatible mixdown selection (ogg vs jkz, sample rate matching)
   - WebSocket subscription patterns (manageWatchedMixdowns)

4. **REST API Endpoints**
   - POST /api/sessions/{sessionId}/jam_tracks/{jamTrackId}/open
   - POST /api/jamtracks/{id}/mixdowns/active
   - POST /api/mixdowns/ (create/edit/delete)
   - POST /api/mixdowns/{id}/enqueue

5. **Integration Points**
   - session.js loadJamTrack() function (lines 2691-2777)
   - Recording conflict detection
   - DIALOG_CLOSED event pattern

**verify:**
- JAMTRACK_LEGACY.md exists and contains all 5 sections
- Code file references include line numbers
- State machine diagram or table included
- API endpoint table with method/path/purpose

**done:**
Legacy implementation patterns documented for reference during React migration.

---

### Task 2: Create jamClient API Reference

**type:** auto

**files:**
- CREATE `.planning/codebase/JAMTRACK_API.md`

**action:**
Document all jamClient JamTrack-related methods with signatures, parameters, return values, and usage patterns:

1. **Playback Methods**
   - `JamTrackPlay(jamTrackId)` - Load and play JamTrack
   - `JamTrackStopPlay()` - Stop playback
   - `JamTrackIsPlaying()` - Query playback state
   - Return types and error handling

2. **Track Data Methods**
   - `JamTrackGetTracks()` - Get stem track list
   - `JamTrackGetTrackDetail(fqId)` - Get sync/key state (returns: key_state, version)
   - `JamTrackGetImage()` - Get album art
   - `GetJamTrackTimeline()` - Get timeline data

3. **Download/Sync Methods**
   - `JamTrackDownload(jamTrackId, mixdownId, userId, progressCallback, successCallback, failCallback)`
   - `JamTrackKeysRequest()` - Request encryption keys
   - `InvalidateJamTrack(fqId)` - Clear cached version
   - Callback patterns and error handling

4. **JMEP (Jam Enhancement Package) Methods**
   - `JamTrackLoadJmep(fqId, jmepData)` - Load tempo/pitch modifications
   - JMEP data structure and usage

5. **Playback Control Methods**
   - `SessionJamTrackSeekMs()` - Seek playback position
   - `SessionCurrrentJamTrackPlayPosMs()` - Get current position
   - `SessionGetJamTracksPlayDurationMs()` - Get total duration

6. **Query Methods**
   - `GetSampleRate()` - Get audio sample rate (44 or 48 kHz)
   - Sample rate implications for fqId format

7. **Backing Track Comparison**
   - Native dialog: `ShowSelectBackingTrackDialog(callbackFunctionName)`
   - File-based vs JamTrack ID-based patterns
   - Shared methods: SessionStartPlay(), SessionStopPlay(), SessionPausePlay()

**verify:**
- JAMTRACK_API.md exists with all 7 sections
- Each method documented with signature and return type
- Async/Promise patterns noted
- Code examples for common operations (download, play, seek)
- Comparison table: JamTrack vs Backing Track methods

**done:**
Complete jamClient API reference created for implementation use.

---

### Task 3: Document Modern React Integration Patterns

**type:** checkpoint:human-verify

**files:**
- CREATE `.planning/codebase/JAMTRACK_REACT_PATTERNS.md`

**action:**
Document existing React patterns in jam-ui that will be extended for JamTrack:

1. **Component Architecture**
   - JKSessionJamTrackModal: Selection UI (already exists)
   - JKSessionJamTrackStems: Stem mixer view (already exists)
   - JKJamTrackPlayer: Public player with master/stems dropdown (already exists)
   - Missing components: Session JamTrack player with playback controls

2. **Redux State Structure**
   - Current mediaSlice structure (backingTracks, jamTracks, jamTrackState)
   - Current activeSessionSlice structure (selectedJamTrack, jamTrackStems)
   - Current sessionUISlice structure (modal visibility)
   - Gaps identified for JamTrack player state

3. **Hook Patterns**
   - useMediaActions: async operation wrappers (openBackingTrack, loadJamTrack, closeMedia)
   - useJamTrack: Redux selectors + mixdown operations
   - useSessionWebSocket: WebSocket message dispatchers
   - Pattern to follow for new JamTrack hooks

4. **Data Flow**
   - User action → Modal selection → Redux dispatch → jamClient call
   - WebSocket MIXER_CHANGES → Redux update → UI sync
   - WebSocket JAM_TRACK_CHANGES → jamTrackState update → Real-time UI
   - Flowchart or sequence diagram

5. **Error Handling Strategy**
   - Backing Track Player error types: file, network, playback, general
   - Error UI patterns: banner with dismiss/retry
   - Async error handling via rejectWithValue in thunks
   - Apply same patterns to JamTrack

6. **Performance Patterns**
   - Visibility-aware polling (500ms visible, 2000ms hidden)
   - useCallback for all handlers
   - Lazy state updates (only update if value changed)
   - Consecutive error tracking with refs

7. **Established Patterns from Phase 3**
   - jamClient returns Promises (always async/await)
   - jamClient returns strings (parseInt before math)
   - Non-serializable objects (jamClient) passed as props, not stored in Redux
   - Cleanup on unmount to prevent stale state

**verify:**
- JAMTRACK_REACT_PATTERNS.md exists with all 7 sections
- File references to existing implementations
- Flowchart or sequence diagram for data flow
- Comparison to Backing Track patterns highlighted
- Gaps identified for Phase 5 implementation

**done:**
Modern React integration patterns documented, ready for architecture design.

---

### CHECKPOINT: Verify Documentation Completeness

**type:** human-verify

**prompt:**
Review the three documentation files created:

1. `.planning/codebase/JAMTRACK_LEGACY.md` - Legacy implementation patterns
2. `.planning/codebase/JAMTRACK_API.md` - jamClient API reference
3. `.planning/codebase/JAMTRACK_REACT_PATTERNS.md` - Modern React patterns

**Verification criteria:**
- All discovery findings captured
- Code file references accurate with line numbers
- API methods have signatures and return types
- React patterns reference existing implementations
- Documentation is clear and actionable for Phase 5

**Actions:**
- If gaps found: Identify missing sections and add them
- If complete: Approve to proceed to Plan 04-02 (Design React Architecture)

</tasks>

<verification>
Documentation completeness verified through:

1. **Coverage Check**
   - Compare documentation sections to discovery findings
   - Verify all legacy files explored are referenced
   - Confirm all jamClient methods documented
   - Check all React patterns captured

2. **Reference Accuracy**
   - File paths are absolute and correct
   - Line numbers match actual code locations
   - API signatures match bridge_api.es6 definitions

3. **Actionability Test**
   - Documentation provides enough detail for Phase 5 implementation
   - Code examples clarify complex patterns
   - Gaps clearly identified for new development
</verification>

<success_criteria>
- [ ] JAMTRACK_LEGACY.md created with 5 sections
- [ ] JAMTRACK_API.md created with 7 sections
- [ ] JAMTRACK_REACT_PATTERNS.md created with 7 sections
- [ ] All documentation files committed to git
- [ ] User verification checkpoint passed
- [ ] Documentation gaps identified or confirmed complete
</success_criteria>

<output>
**Artifacts:**
- `.planning/codebase/JAMTRACK_LEGACY.md` - Legacy implementation reference
- `.planning/codebase/JAMTRACK_API.md` - jamClient API documentation
- `.planning/codebase/JAMTRACK_REACT_PATTERNS.md` - React integration patterns

**Purpose:**
Comprehensive documentation bridging legacy JamTrack patterns to modern React architecture, enabling efficient Phase 5 implementation without repeated codebase exploration.
</output>
