perl-workspace 0.13.2

Workspace file discovery, indexing, and observability for Perl
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
//! Enhanced index lifecycle state machine for production readiness.
//!
//! This module provides a comprehensive state machine for index lifecycle management
//! with additional states for initialization, updating, invalidation, and error handling.
//! The state machine ensures thread-safe state transitions with proper guards and
//! error recovery mechanisms.
//!
//! # State Machine States
//!
//! - **Idle**: Index is idle and not initialized
//! - **Initializing**: Index is being initialized
//! - **Building**: Index is being built (workspace scan in progress)
//! - **Updating**: Index is being updated (incremental changes)
//! - **Invalidating**: Index is being invalidated
//! - **Ready**: Index is ready for queries
//! - **Degraded**: Index is degraded but partially functional
//! - **Error**: Index is in error state
//!
//! # State Transitions
//!
//! ```text
//! Idle → Initializing → Building → Updating → Ready
//!  ↓         ↓            ↓          ↓         ↓
//! Error ← Error ← Error ← Error ← Error ← Error
//!  ↓         ↓            ↓          ↓         ↓
//! Degraded ← Degraded ← Degraded ← Degraded ← Degraded
//! ```
//!
//! # Thread Safety
//!
//! - All state transitions are protected by RwLock
//! - State reads are lock-free (cloned state)
//! - State writes use exclusive locks
//! - Guards prevent invalid transitions
//!
//! # Usage
//!
//! ```rust,ignore
//! use perl_workspace::state_machine::{IndexStateMachine, IndexState};
//!
//! let machine = IndexStateMachine::new();
//! assert!(matches!(machine.state(), IndexState::Idle));
//!
//! machine.transition_to_initializing();
//! machine.transition_to_building(100); // 100 files to index
//! ```

use parking_lot::RwLock;
use std::sync::Arc;
use std::time::Instant;

/// Enhanced index state with additional production-ready states.
///
/// Extends the original IndexState with Initializing, Updating, Invalidating,
/// and Error states for comprehensive lifecycle management.
#[derive(Clone, Debug)]
pub enum IndexState {
    /// Index is idle and not initialized
    Idle {
        /// When the index entered idle state
        since: Instant,
    },

    /// Index is being initialized
    Initializing {
        /// Initialization progress (0-100)
        progress: u8,
        /// When initialization started
        started_at: Instant,
    },

    /// Index is being built (workspace scan in progress)
    Building {
        /// Current build phase
        phase: BuildPhase,
        /// Files indexed so far
        indexed_count: usize,
        /// Total files discovered
        total_count: usize,
        /// Started at
        started_at: Instant,
    },

    /// Index is being updated (incremental changes)
    Updating {
        /// Number of files being updated
        updating_count: usize,
        /// When update started
        started_at: Instant,
    },

    /// Index is being invalidated
    Invalidating {
        /// Reason for invalidation
        reason: InvalidationReason,
        /// When invalidation started
        started_at: Instant,
    },

    /// Index is ready for queries
    Ready {
        /// Total symbols indexed
        symbol_count: usize,
        /// Total files indexed
        file_count: usize,
        /// Timestamp of last successful index
        completed_at: Instant,
    },

    /// Index is degraded but partially functional
    Degraded {
        /// Why we degraded
        reason: DegradationReason,
        /// What's still available
        available_symbols: usize,
        /// When degradation occurred
        since: Instant,
    },

    /// Index is in error state
    Error {
        /// Error message
        message: String,
        /// When error occurred
        since: Instant,
    },
}

impl IndexState {
    /// Return the coarse state kind for instrumentation and routing decisions.
    pub fn kind(&self) -> IndexStateKind {
        match self {
            IndexState::Idle { .. } => IndexStateKind::Idle,
            IndexState::Initializing { .. } => IndexStateKind::Initializing,
            IndexState::Building { .. } => IndexStateKind::Building,
            IndexState::Updating { .. } => IndexStateKind::Updating,
            IndexState::Invalidating { .. } => IndexStateKind::Invalidating,
            IndexState::Ready { .. } => IndexStateKind::Ready,
            IndexState::Degraded { .. } => IndexStateKind::Degraded,
            IndexState::Error { .. } => IndexStateKind::Error,
        }
    }

    /// Check if the index is ready for queries.
    pub fn is_ready(&self) -> bool {
        matches!(self, IndexState::Ready { .. })
    }

    /// Check if the index is in an error state.
    pub fn is_error(&self) -> bool {
        matches!(self, IndexState::Error { .. })
    }

    /// Check if the index is in a transitional state.
    pub fn is_transitional(&self) -> bool {
        matches!(
            self,
            IndexState::Initializing { .. }
                | IndexState::Building { .. }
                | IndexState::Updating { .. }
                | IndexState::Invalidating { .. }
        )
    }

    /// Get the timestamp of when the current state began.
    pub fn state_started_at(&self) -> Instant {
        match self {
            IndexState::Idle { since } => *since,
            IndexState::Initializing { started_at, .. } => *started_at,
            IndexState::Building { started_at, .. } => *started_at,
            IndexState::Updating { started_at, .. } => *started_at,
            IndexState::Invalidating { started_at, .. } => *started_at,
            IndexState::Ready { completed_at, .. } => *completed_at,
            IndexState::Degraded { since, .. } => *since,
            IndexState::Error { since, .. } => *since,
        }
    }
}

/// Coarse index state kinds for instrumentation and transition tracking.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum IndexStateKind {
    /// Index is idle
    Idle,
    /// Index is initializing
    Initializing,
    /// Index is building
    Building,
    /// Index is updating
    Updating,
    /// Index is invalidating
    Invalidating,
    /// Index is ready
    Ready,
    /// Index is degraded
    Degraded,
    /// Index is in error state
    Error,
}

/// Build phases for the Building state.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BuildPhase {
    /// No scan has started yet
    Idle,
    /// Workspace file discovery is in progress
    Scanning,
    /// Symbol indexing is in progress
    Indexing,
}

/// Reason for index invalidation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InvalidationReason {
    /// Workspace configuration changed
    ConfigurationChanged,
    /// File system watcher detected significant changes
    FileSystemChanged,
    /// Manual invalidation requested
    ManualRequest,
    /// Cache corruption detected
    CacheCorruption,
    /// Dependency changed
    DependencyChanged,
}

/// Reason for index degradation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DegradationReason {
    /// Parse storm (too many simultaneous changes)
    ParseStorm {
        /// Number of pending parse operations
        pending_parses: usize,
    },

    /// IO error during indexing
    IoError {
        /// Error message for diagnostics
        message: String,
    },

    /// Timeout during workspace scan
    ScanTimeout {
        /// Elapsed time in milliseconds
        elapsed_ms: u64,
    },

    /// Resource limits exceeded
    ResourceLimit {
        /// Which resource limit was exceeded
        kind: ResourceKind,
    },
}

/// Type of resource limit that was exceeded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ResourceKind {
    /// Maximum number of files in index exceeded
    MaxFiles,
    /// Maximum total symbols exceeded
    MaxSymbols,
    /// Maximum AST cache bytes exceeded
    MaxCacheBytes,
}

/// State transition for index lifecycle instrumentation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct IndexStateTransition {
    /// Transition start state
    pub from: IndexStateKind,
    /// Transition end state
    pub to: IndexStateKind,
}

/// A phase transition while building the workspace index.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BuildPhaseTransition {
    /// Transition start phase
    pub from: BuildPhase,
    /// Transition end phase
    pub to: BuildPhase,
}

/// Result of a state transition attempt.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TransitionResult {
    /// Transition succeeded
    Success,
    /// Transition failed - invalid state transition
    InvalidTransition {
        /// Current state
        from: IndexStateKind,
        /// Target state
        to: IndexStateKind,
    },
    /// Transition failed - guard condition not met
    GuardFailed {
        /// Guard condition that failed
        condition: String,
    },
}

/// Thread-safe index state machine.
///
/// Manages index lifecycle with comprehensive state transitions,
/// guards, and error recovery mechanisms.
pub struct IndexStateMachine {
    /// Current index state (RwLock for thread-safe transitions)
    state: Arc<RwLock<IndexState>>,
}

impl IndexStateMachine {
    /// Create a new state machine in Idle state.
    ///
    /// # Returns
    ///
    /// A state machine initialized in `IndexState::Idle`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use perl_workspace::state_machine::IndexStateMachine;
    ///
    /// let machine = IndexStateMachine::new();
    /// ```
    pub fn new() -> Self {
        Self { state: Arc::new(RwLock::new(IndexState::Idle { since: Instant::now() })) }
    }

    /// Get current state (lock-free read via clone).
    ///
    /// Returns a cloned copy of the current state for lock-free access
    /// in hot path LSP handlers.
    ///
    /// # Returns
    ///
    /// The current `IndexState` snapshot.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use perl_workspace::state_machine::{IndexStateMachine, IndexState};
    ///
    /// let machine = IndexStateMachine::new();
    /// match machine.state() {
    ///     IndexState::Ready { .. } => { /* Full query path */ }
    /// _ => { /* Degraded/building fallback */ }
    /// }
    /// ```
    pub fn state(&self) -> IndexState {
        self.state.read().clone()
    }

    /// Transition to Initializing state.
    ///
    /// # State Transition Guards
    ///
    /// Only valid transitions:
    /// - `Idle` → `Initializing`
    /// - `Error` → `Initializing` (recovery attempt)
    ///
    /// # Returns
    ///
    /// `TransitionResult::Success` if transition succeeded, otherwise an error.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use perl_workspace::state_machine::IndexStateMachine;
    ///
    /// let machine = IndexStateMachine::new();
    /// assert!(matches!(machine.transition_to_initializing(), TransitionResult::Success));
    /// ```
    pub fn transition_to_initializing(&self) -> TransitionResult {
        let mut state = self.state.write();
        let from_kind = state.kind();

        match &*state {
            IndexState::Idle { .. } | IndexState::Error { .. } => {
                *state = IndexState::Initializing { progress: 0, started_at: Instant::now() };
                TransitionResult::Success
            }
            _ => TransitionResult::InvalidTransition {
                from: from_kind,
                to: IndexStateKind::Initializing,
            },
        }
    }

    /// Transition to Building state.
    ///
    /// # State Transition Guards
    ///
    /// Only valid transitions:
    /// - `Initializing` → `Building`
    /// - `Ready` → `Building` (re-index)
    /// - `Degraded` → `Building` (recovery)
    ///
    /// # Arguments
    ///
    /// * `total_count` - Total number of files to index
    ///
    /// # Returns
    ///
    /// `TransitionResult::Success` if transition succeeded, otherwise an error.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use perl_workspace::state_machine::IndexStateMachine;
    ///
    /// let machine = IndexStateMachine::new();
    /// machine.transition_to_initializing();
    /// assert!(matches!(machine.transition_to_building(100), TransitionResult::Success));
    /// ```
    pub fn transition_to_building(&self, total_count: usize) -> TransitionResult {
        let mut state = self.state.write();
        let from_kind = state.kind();

        match &*state {
            IndexState::Initializing { .. }
            | IndexState::Ready { .. }
            | IndexState::Degraded { .. } => {
                *state = IndexState::Building {
                    phase: BuildPhase::Idle,
                    indexed_count: 0,
                    total_count,
                    started_at: Instant::now(),
                };
                TransitionResult::Success
            }
            _ => TransitionResult::InvalidTransition {
                from: from_kind,
                to: IndexStateKind::Building,
            },
        }
    }

    /// Transition to Updating state.
    ///
    /// # State Transition Guards
    ///
    /// Only valid transitions:
    /// - `Ready` → `Updating`
    /// - `Degraded` → `Updating`
    ///
    /// # Arguments
    ///
    /// * `updating_count` - Number of files being updated
    ///
    /// # Returns
    ///
    /// `TransitionResult::Success` if transition succeeded, otherwise an error.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use perl_workspace::state_machine::IndexStateMachine;
    ///
    /// let machine = IndexStateMachine::new();
    /// // ... build index ...
    /// machine.transition_to_ready(100, 5000);
    /// assert!(matches!(machine.transition_to_updating(5), TransitionResult::Success));
    /// ```
    pub fn transition_to_updating(&self, updating_count: usize) -> TransitionResult {
        let mut state = self.state.write();
        let from_kind = state.kind();

        match &*state {
            IndexState::Ready { .. } | IndexState::Degraded { .. } => {
                *state = IndexState::Updating { updating_count, started_at: Instant::now() };
                TransitionResult::Success
            }
            _ => TransitionResult::InvalidTransition {
                from: from_kind,
                to: IndexStateKind::Updating,
            },
        }
    }

    /// Transition to Invalidating state.
    ///
    /// # State Transition Guards
    ///
    /// Valid from any non-transitional state.
    ///
    /// # Arguments
    ///
    /// * `reason` - Reason for invalidation
    ///
    /// # Returns
    ///
    /// `TransitionResult::Success` if transition succeeded, otherwise an error.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use perl_workspace::state_machine::{IndexStateMachine, InvalidationReason};
    ///
    /// let machine = IndexStateMachine::new();
    /// assert!(matches!(
    ///     machine.transition_to_invalidating(InvalidationReason::ManualRequest),
    ///     TransitionResult::Success
    /// ));
    /// ```
    pub fn transition_to_invalidating(&self, reason: InvalidationReason) -> TransitionResult {
        let mut state = self.state.write();
        let from_kind = state.kind();

        // Can transition from any non-transitional state
        match &*state {
            IndexState::Initializing { .. }
            | IndexState::Building { .. }
            | IndexState::Updating { .. }
            | IndexState::Invalidating { .. } => TransitionResult::InvalidTransition {
                from: from_kind,
                to: IndexStateKind::Invalidating,
            },
            _ => {
                *state = IndexState::Invalidating { reason, started_at: Instant::now() };
                TransitionResult::Success
            }
        }
    }

    /// Transition to Ready state.
    ///
    /// # State Transition Guards
    ///
    /// Only valid transitions:
    /// - `Building` → `Ready` (normal completion)
    /// - `Updating` → `Ready` (update complete)
    /// - `Invalidating` → `Ready` (invalidation complete)
    /// - `Degraded` → `Ready` (recovery after fix)
    ///
    /// # Arguments
    ///
    /// * `file_count` - Total number of files indexed
    /// * `symbol_count` - Total number of symbols extracted
    ///
    /// # Returns
    ///
    /// `TransitionResult::Success` if transition succeeded, otherwise an error.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use perl_workspace::state_machine::IndexStateMachine;
    ///
    /// let machine = IndexStateMachine::new();
    /// machine.transition_to_building(100);
    /// assert!(matches!(machine.transition_to_ready(100, 5000), TransitionResult::Success));
    /// ```
    pub fn transition_to_ready(&self, file_count: usize, symbol_count: usize) -> TransitionResult {
        let mut state = self.state.write();
        let from_kind = state.kind();

        match &*state {
            IndexState::Building { .. }
            | IndexState::Updating { .. }
            | IndexState::Invalidating { .. }
            | IndexState::Degraded { .. } => {
                *state =
                    IndexState::Ready { symbol_count, file_count, completed_at: Instant::now() };
                TransitionResult::Success
            }
            IndexState::Ready { .. } => {
                // Already Ready - update metrics but don't log as transition
                *state =
                    IndexState::Ready { symbol_count, file_count, completed_at: Instant::now() };
                TransitionResult::Success
            }
            _ => TransitionResult::InvalidTransition { from: from_kind, to: IndexStateKind::Ready },
        }
    }

    /// Transition to Degraded state.
    ///
    /// # State Transition Guards
    ///
    /// Valid from any state except Error.
    ///
    /// # Arguments
    ///
    /// * `reason` - Why the index degraded
    ///
    /// # Returns
    ///
    /// `TransitionResult::Success` if transition succeeded, otherwise an error.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use perl_workspace::state_machine::{IndexStateMachine, DegradationReason};
    ///
    /// let machine = IndexStateMachine::new();
    /// machine.transition_to_ready(100, 5000);
    /// assert!(matches!(
    ///     machine.transition_to_degraded(DegradationReason::IoError {
    ///         message: "IO error".to_string()
    ///     }),
    ///     TransitionResult::Success
    /// ));
    /// ```
    pub fn transition_to_degraded(&self, reason: DegradationReason) -> TransitionResult {
        let mut state = self.state.write();
        let from_kind = state.kind();

        // Get available symbols count from current state
        let available_symbols = match &*state {
            IndexState::Ready { symbol_count, .. } => *symbol_count,
            IndexState::Degraded { available_symbols, .. } => *available_symbols,
            _ => 0,
        };

        match &*state {
            IndexState::Error { .. } => TransitionResult::InvalidTransition {
                from: from_kind,
                to: IndexStateKind::Degraded,
            },
            _ => {
                *state = IndexState::Degraded { reason, available_symbols, since: Instant::now() };
                TransitionResult::Success
            }
        }
    }

    /// Transition to Error state.
    ///
    /// # State Transition Guards
    ///
    /// Valid from any state.
    ///
    /// # Arguments
    ///
    /// * `message` - Error message
    ///
    /// # Returns
    ///
    /// `TransitionResult::Success` if transition succeeded, otherwise an error.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use perl_workspace::state_machine::IndexStateMachine;
    ///
    /// let machine = IndexStateMachine::new();
    /// assert!(matches!(
    ///     machine.transition_to_error("Critical error".to_string()),
    ///     TransitionResult::Success
    /// ));
    /// ```
    pub fn transition_to_error(&self, message: String) -> TransitionResult {
        let mut state = self.state.write();
        let _from_kind = state.kind();

        *state = IndexState::Error { message, since: Instant::now() };
        TransitionResult::Success
    }

    /// Transition to Idle state.
    ///
    /// # State Transition Guards
    ///
    /// Valid from any state.
    ///
    /// # Returns
    ///
    /// `TransitionResult::Success` if transition succeeded, otherwise an error.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use perl_workspace::state_machine::IndexStateMachine;
    ///
    /// let machine = IndexStateMachine::new();
    /// machine.transition_to_ready(100, 5000);
    /// assert!(matches!(machine.transition_to_idle(), TransitionResult::Success));
    /// ```
    pub fn transition_to_idle(&self) -> TransitionResult {
        let mut state = self.state.write();

        *state = IndexState::Idle { since: Instant::now() };
        TransitionResult::Success
    }

    /// Update building progress.
    ///
    /// # Arguments
    ///
    /// * `indexed_count` - Number of files indexed so far
    /// * `phase` - Current build phase
    ///
    /// # Returns
    ///
    /// `TransitionResult::Success` if update succeeded, otherwise an error.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use perl_workspace::state_machine::{IndexStateMachine, BuildPhase};
    ///
    /// let machine = IndexStateMachine::new();
    /// machine.transition_to_building(100);
    /// assert!(matches!(
    ///     machine.update_building_progress(50, BuildPhase::Indexing),
    ///     TransitionResult::Success
    /// ));
    /// ```
    pub fn update_building_progress(
        &self,
        indexed_count: usize,
        phase: BuildPhase,
    ) -> TransitionResult {
        let mut state = self.state.write();

        match &mut *state {
            IndexState::Building { total_count, started_at, .. } => {
                *state = IndexState::Building {
                    phase,
                    indexed_count,
                    total_count: *total_count,
                    started_at: *started_at,
                };
                TransitionResult::Success
            }
            _ => TransitionResult::InvalidTransition {
                from: state.kind(),
                to: IndexStateKind::Building,
            },
        }
    }

    /// Update initialization progress.
    ///
    /// # Arguments
    ///
    /// * `progress` - Progress percentage (0-100)
    ///
    /// # Returns
    ///
    /// `TransitionResult::Success` if update succeeded, otherwise an error.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use perl_workspace::state_machine::IndexStateMachine;
    ///
    /// let machine = IndexStateMachine::new();
    /// machine.transition_to_initializing();
    /// assert!(matches!(machine.update_initialization_progress(50), TransitionResult::Success));
    /// ```
    pub fn update_initialization_progress(&self, progress: u8) -> TransitionResult {
        let mut state = self.state.write();

        match &mut *state {
            IndexState::Initializing { started_at, .. } => {
                *state = IndexState::Initializing {
                    progress: progress.min(100),
                    started_at: *started_at,
                };
                TransitionResult::Success
            }
            _ => TransitionResult::InvalidTransition {
                from: state.kind(),
                to: IndexStateKind::Initializing,
            },
        }
    }
}

impl Default for IndexStateMachine {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_initial_state() {
        let machine = IndexStateMachine::new();
        assert!(matches!(machine.state(), IndexState::Idle { .. }));
    }

    #[test]
    fn test_idle_to_initializing() {
        let machine = IndexStateMachine::new();
        assert!(matches!(machine.transition_to_initializing(), TransitionResult::Success));
        assert!(matches!(machine.state(), IndexState::Initializing { .. }));
    }

    #[test]
    fn test_initializing_to_building() {
        let machine = IndexStateMachine::new();
        machine.transition_to_initializing();
        assert!(matches!(machine.transition_to_building(100), TransitionResult::Success));
        assert!(matches!(machine.state(), IndexState::Building { .. }));
    }

    #[test]
    fn test_building_to_ready() {
        let machine = IndexStateMachine::new();
        machine.transition_to_initializing();
        machine.transition_to_building(100);
        assert!(matches!(machine.transition_to_ready(100, 5000), TransitionResult::Success));
        assert!(matches!(machine.state(), IndexState::Ready { .. }));
    }

    #[test]
    fn test_ready_to_updating() {
        let machine = IndexStateMachine::new();
        machine.transition_to_initializing();
        machine.transition_to_building(100);
        machine.transition_to_ready(100, 5000);
        assert!(matches!(machine.transition_to_updating(5), TransitionResult::Success));
        assert!(matches!(machine.state(), IndexState::Updating { .. }));
    }

    #[test]
    fn test_ready_to_degraded() {
        let machine = IndexStateMachine::new();
        machine.transition_to_initializing();
        machine.transition_to_building(100);
        machine.transition_to_ready(100, 5000);
        assert!(matches!(
            machine.transition_to_degraded(DegradationReason::IoError {
                message: "error".to_string()
            }),
            TransitionResult::Success
        ));
        assert!(matches!(machine.state(), IndexState::Degraded { .. }));
    }

    #[test]
    fn test_any_to_error() {
        let machine = IndexStateMachine::new();
        assert!(matches!(
            machine.transition_to_error("error".to_string()),
            TransitionResult::Success
        ));
        assert!(matches!(machine.state(), IndexState::Error { .. }));
    }

    #[test]
    fn test_invalid_transition() {
        let machine = IndexStateMachine::new();
        // Can't go from Idle to Ready without building
        assert!(matches!(
            machine.transition_to_ready(0, 0),
            TransitionResult::InvalidTransition { .. }
        ));
    }

    #[test]
    fn test_update_building_progress() {
        let machine = IndexStateMachine::new();
        machine.transition_to_initializing();
        machine.transition_to_building(100);
        assert!(matches!(
            machine.update_building_progress(50, BuildPhase::Indexing),
            TransitionResult::Success
        ));
    }

    #[test]
    fn test_update_initialization_progress() {
        let machine = IndexStateMachine::new();
        machine.transition_to_initializing();
        assert!(matches!(machine.update_initialization_progress(50), TransitionResult::Success));
    }

    #[test]
    fn test_update_initialization_progress_clamps_at_100() {
        let machine = IndexStateMachine::new();
        machine.transition_to_initializing();

        assert!(matches!(machine.update_initialization_progress(250), TransitionResult::Success));
        assert!(matches!(machine.state(), IndexState::Initializing { progress: 100, .. }));
    }

    #[test]
    fn test_transition_to_invalidating_rejects_transitional_states() {
        let machine = IndexStateMachine::new();
        machine.transition_to_initializing();

        assert!(matches!(
            machine.transition_to_invalidating(InvalidationReason::ManualRequest),
            TransitionResult::InvalidTransition {
                from: IndexStateKind::Initializing,
                to: IndexStateKind::Invalidating
            }
        ));
    }

    #[test]
    fn test_transition_to_degraded_keeps_available_symbols_from_ready() {
        let machine = IndexStateMachine::new();
        machine.transition_to_initializing();
        machine.transition_to_building(100);
        machine.transition_to_ready(42, 777);

        assert!(matches!(
            machine.transition_to_degraded(DegradationReason::ParseStorm { pending_parses: 3 }),
            TransitionResult::Success
        ));
        assert!(matches!(machine.state(), IndexState::Degraded { available_symbols: 777, .. }));
    }

    #[test]
    fn test_transition_to_degraded_from_error_is_invalid() {
        let machine = IndexStateMachine::new();
        machine.transition_to_error("fatal".to_string());

        assert!(matches!(
            machine.transition_to_degraded(DegradationReason::ResourceLimit {
                kind: ResourceKind::MaxFiles
            }),
            TransitionResult::InvalidTransition {
                from: IndexStateKind::Error,
                to: IndexStateKind::Degraded
            }
        ));
    }

    #[test]
    fn test_update_building_progress_preserves_total_count() {
        let machine = IndexStateMachine::new();
        machine.transition_to_initializing();
        machine.transition_to_building(123);

        assert!(matches!(
            machine.update_building_progress(10, BuildPhase::Scanning),
            TransitionResult::Success
        ));
        assert!(matches!(
            machine.state(),
            IndexState::Building {
                indexed_count: 10,
                total_count: 123,
                phase: BuildPhase::Scanning,
                ..
            }
        ));
    }

    #[test]
    fn test_state_helpers_report_expected_flags() {
        let machine = IndexStateMachine::new();
        let idle = machine.state();
        assert_eq!(idle.kind(), IndexStateKind::Idle);
        assert!(!idle.is_ready());
        assert!(!idle.is_error());
        assert!(!idle.is_transitional());
        assert!(idle.state_started_at() <= Instant::now());

        machine.transition_to_initializing();
        let initializing = machine.state();
        assert_eq!(initializing.kind(), IndexStateKind::Initializing);
        assert!(initializing.is_transitional());

        machine.transition_to_error("boom".to_string());
        let error = machine.state();
        assert_eq!(error.kind(), IndexStateKind::Error);
        assert!(error.is_error());
        assert!(!error.is_ready());
    }
}