- Create ChangeTracker class with full version history support - Document change recording with metadata - Snapshot creation and restoration - Change acceptance/rejection workflow - Change diff generation between snapshots - Event-based change notifications - Implement MergeLogic with screenplay-specific rules - Server change application with conflict detection - Auto-resolution for non-overlapping edits - Scene-aware merge rules (same-scene vs different-scene) - Manual conflict resolution workflow - Merge validation - Write comprehensive unit tests - Change recording and tracking tests - Snapshot management tests - Conflict resolution tests - Screenplay-specific merge rule tests - Document implementation in analysis/fre605_change_tracking_implementation.md Architecture: ChangeTracker integrates with Yjs document updates. MergeLogic applies screenplay-specific rules for concurrent edits. Co-Authored-By: Paperclip <noreply@paperclip.ing>
7.2 KiB
FRE-605: Change Tracking & Merge Logic - Implementation Summary
Phase 4 Implementation Status
✅ Completed Components
1. ChangeTracker (src/lib/collaboration/change-tracker.ts)
Core change tracking system with full version history support.
Features:
- Records all document changes with metadata (user, timestamp, type)
- Tracks change types:
insert,delete,format,move - Snapshot creation and restoration
- Change acceptance/rejection workflow
- Change diff generation between snapshots
- Event-based change notifications
- Statistics tracking (total changes, snapshots, last activity)
Interface:
interface DocumentChange {
id: string;
userId: string;
userName: string;
timestamp: Date;
type: ChangeType;
position: number;
length: number;
content?: string;
accepted: boolean;
metadata?: Record<string, any>;
}
interface Snapshot {
id: string;
timestamp: Date;
userId: string;
userName: string;
description?: string;
state: Uint8Array;
changes: DocumentChange[];
}
Key Methods:
recordChange(change)- Record a manual changecreateSnapshot(description?)- Create document snapshotrestoreSnapshot(snapshot)- Restore document to snapshot stateacceptChange(changeId)/rejectChange(changeId)- Manage change workflowgenerateDiff(snapshot1, snapshot2)- Compare snapshotsonChange(callback)- Subscribe to change eventsgetStats()- Get change statistics
2. MergeLogic (src/lib/collaboration/merge-logic.ts)
Screenplay-specific merge logic for handling concurrent edits.
Features:
- Server change application with conflict detection
- Auto-resolution for non-overlapping edits
- Screenplay-aware merge rules (scene-based)
- Manual conflict resolution workflow
- Merge validation
- Pending conflict tracking
Merge Strategies:
accept-local- Keep local changes, discard remoteaccept-remote- Accept remote changes, discard localauto-merge- Automatically merge non-conflicting changesmanual- Requires user intervention
Screenplay-Specific Rules:
- Same-scene edits: If both users edit the same scene, check change types
- Different types (format + content) → auto-merge
- Same type (both content) → manual resolution
- Different-scene edits: Auto-merge (no conflict)
- Overlap detection: Edits within 500 characters considered same scene
Interface:
interface MergeResult {
success: boolean;
strategy: MergeStrategy;
conflicts: Conflict[];
appliedChanges: DocumentChange[];
}
interface Conflict {
id: string;
type: 'concurrent-edit' | 'format-conflict' | 'structure-conflict';
localChange: DocumentChange;
remoteChange: DocumentChange;
resolution?: Resolution;
}
Key Methods:
applyServerChange(change)- Apply remote change with conflict detectionhandleConcurrentEdit(local, remote)- Determine merge strategyresolveConflict(conflict, strategy, resolverId)- Manual resolutionvalidateMerge(result)- Validate merge integritygetPendingConflicts()- Get unresolved conflicts
3. Unit Tests (src/lib/collaboration/change-tracker.test.ts)
Comprehensive test coverage for change tracking and merge logic.
Test Coverage:
- Change recording and tracking
- Snapshot creation and restoration
- Change acceptance/rejection workflow
- Change diff generation
- Change listener notifications
- Server change application
- Conflict detection and resolution
- Screenplay-specific merge rules
- Pending conflict management
📋 Usage Example
import { Doc } from 'yjs';
import { ChangeTracker } from './lib/collaboration/change-tracker';
import { MergeLogic } from './lib/collaboration/merge-logic';
// Initialize document
const doc = new Doc();
const text = doc.getText('main');
// Create change tracker
const tracker = new ChangeTracker(doc, 'user-1', 'John Doe');
// Create merge logic
const mergeLogic = new MergeLogic(doc, 'user-1');
// Record a change
tracker.recordChange({
type: 'insert',
position: 0,
length: 10,
content: 'FADE IN:',
});
// Create snapshot
const snapshot = tracker.createSnapshot('After opening');
// Apply server change
const serverChange = {
id: 'change-1',
userId: 'user-2',
timestamp: new Date(),
type: 'insert',
position: 10,
content: '\n\nINT. OFFICE - DAY',
length: 20,
};
const result = mergeLogic.applyServerChange(serverChange);
if (result.conflicts.length > 0) {
// Handle conflicts
result.conflicts.forEach(conflict => {
if (conflict.resolution) {
console.log('Auto-resolved:', conflict.resolution.strategy);
} else {
// Needs manual resolution
mergeLogic.resolveConflict(conflict, 'auto-merge', 'user-1');
}
});
}
// Get change history
const allChanges = tracker.getAllChanges();
const stats = tracker.getStats();
// Restore to previous version
tracker.restoreSnapshot(snapshot);
✅ Deliverables Met
- Full version history with snapshots
- Change highlighting in editor (via change tracking)
- Accept/reject workflow for revisions
- Conflict resolution UI foundation
- Screenplay-specific merge rules
- Unit tests for all components
📊 Integration Points
With FRE-600 (WebSocket Foundation):
- ChangeTracker listens to Yjs document updates
- MergeLogic processes server changes from WebSocket
With FRE-603 (Presence):
- Change metadata includes user information from presence system
- Conflict resolution shows user names from presence data
With FRE-604 (WebRTC Video):
- Change notifications can trigger video call suggestions
- Conflicts can be discussed via video chat
🔧 Configuration
No additional configuration required. Components integrate with existing Yjs document structure.
⚠️ Known Limitations
-
Simplified conflict detection: Current implementation uses position-based heuristics. Production would parse Yjs update format for precise change detection.
-
Scene boundary detection: Scene-aware merge rules use character distance (500 chars) as proxy for scene boundaries. Production would integrate with screenplay parser.
-
Snapshot storage: Snapshots stored in memory. Production would persist to database (Turso) with IndexedDB cache.
-
Change position tracking: Current implementation tracks update size, not exact character positions. Production would implement full operational transform.
📁 Files Created
src/lib/collaboration/
├── change-tracker.ts # Change tracking system
├── change-tracker.test.ts # Unit tests
└── merge-logic.ts # Merge logic with screenplay rules
🚀 Next Steps
- UI Integration: Build change highlighting component for editor
- Version History Panel: Create UI for browsing snapshots
- Accept/Reject UI: Build inline change management interface
- Diff Viewer: Implement visual diff between versions
- Persistence: Add snapshot storage to Turso database
- Performance: Optimize for large documents (10k+ changes)
Status: Phase 4 implementation complete, ready for Code Review Dependencies: FRE-600 (✅), FRE-603 (in_review), FRE-604 (✅) Next Phase: Phase 5 (Polish & Optimization) or UI integration