maproom 0.1.0

Semantic code search powered by embeddings and SQLite
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
//! Git-based file change polling.
//!
//! This module implements file change detection using `git status --porcelain`
//! instead of native file watchers. This approach eliminates "too many open files"
//! errors on large repositories while providing consistent cross-platform behavior.
//!
//! # Architecture
//!
//! The GitPoller runs an async loop that:
//! 1. Executes `git status --porcelain` at configurable intervals
//! 2. Parses output into GitState using the git_state module
//! 3. Compares with previous state to detect changes
//! 4. Emits FileEvents for detected changes
//!
//! # Trade-offs
//!
//! - **Latency**: 2-5 second detection latency (acceptable for dev workflows)
//! - **Resources**: Zero file descriptors used (vs thousands with notify)
//! - **Git-aware**: Automatically respects .gitignore patterns
//! - **Requirements**: Must be in a git repository, git must be in PATH
//!
//! # Initial Behavior
//!
//! On first poll, previous_state is empty. This means all dirty files in the
//! first poll emit Modified events, which triggers initial indexing of changed
//! files. This is intentional and acceptable behavior.

use std::path::PathBuf;
use std::time::Duration;

use thiserror::Error;
use tokio::process::Command;
use tokio::sync::{mpsc, watch};
use tracing::{debug, info, warn};

use super::events::FileEvent;
use super::git_state::{GitState, GitStateError};

/// Configuration for the git poller.
#[derive(Debug, Clone)]
pub struct GitPollerConfig {
    /// Polling interval (default: 3 seconds).
    pub poll_interval: Duration,

    /// Include untracked files in detection (default: true).
    /// When true, uses `git status --porcelain` which includes untracked.
    pub include_untracked: bool,

    /// Enable rename detection (default: true).
    /// When true, adds `-M` flag to git status.
    pub detect_renames: bool,

    /// Timeout for git command (default: 10 seconds).
    pub git_timeout: Duration,

    /// Number of retries on transient git failures (default: 3).
    pub retry_count: u32,

    /// Delay between retries (default: 1 second).
    pub retry_delay: Duration,

    /// Channel capacity for events (default: 1000).
    pub channel_capacity: usize,
}

impl Default for GitPollerConfig {
    fn default() -> Self {
        Self {
            poll_interval: Duration::from_secs(3),
            include_untracked: true,
            detect_renames: true,
            git_timeout: Duration::from_secs(10),
            retry_count: 3,
            retry_delay: Duration::from_secs(1),
            channel_capacity: 1000,
        }
    }
}

/// Errors that can occur during git polling.
#[derive(Debug, Error)]
pub enum GitPollerError {
    /// Git command failed with an error.
    #[error("git command failed: {stderr}")]
    GitExecutionError { stderr: String },

    /// Git command timed out.
    #[error("git command timed out after {timeout:?}")]
    GitTimeout { timeout: Duration },

    /// Path is not a git repository.
    #[error("not a git repository: {path}")]
    NotGitRepository { path: PathBuf },

    /// A git operation (rebase, merge, etc.) is in progress.
    #[error("git operation in progress (index.lock exists)")]
    GitOperationInProgress,

    /// Failed to parse git status output.
    #[error("failed to parse git status: {reason}")]
    ParseError { line: String, reason: String },

    /// Event channel was closed.
    #[error("event channel closed")]
    ChannelClosed,

    /// IO error during git execution.
    #[error("io error: {0}")]
    IoError(#[from] std::io::Error),
}

impl From<GitStateError> for GitPollerError {
    fn from(err: GitStateError) -> Self {
        match err {
            GitStateError::InvalidPath { path, reason } => GitPollerError::ParseError {
                line: path.display().to_string(),
                reason,
            },
            GitStateError::ParseError { line, reason } => {
                GitPollerError::ParseError { line, reason }
            }
        }
    }
}

/// Git-based file change poller.
///
/// Monitors a git repository for file changes by periodically running
/// `git status --porcelain` and comparing state between polls. Also tracks
/// HEAD commit changes to detect files that are created/modified and committed
/// within a single poll interval.
pub struct GitPoller {
    /// Root directory of the git repository.
    root: PathBuf,

    /// Configuration for polling behavior.
    config: GitPollerConfig,

    /// Previous git state for comparison.
    previous_state: GitState,

    /// Previous HEAD commit for detecting commits between polls.
    /// None if we haven't polled yet or if the repo has no commits.
    previous_head: Option<String>,

    /// Channel sender for file events.
    event_tx: mpsc::Sender<FileEvent>,

    /// Receiver for shutdown signal.
    shutdown_rx: watch::Receiver<bool>,
}

impl GitPoller {
    /// Create a new GitPoller for the given repository root.
    ///
    /// Returns the poller instance, an event receiver, and a shutdown sender.
    ///
    /// # Errors
    ///
    /// Returns an error if the path is not a git repository.
    pub fn new(
        root: PathBuf,
        config: GitPollerConfig,
    ) -> Result<(Self, mpsc::Receiver<FileEvent>, watch::Sender<bool>), GitPollerError> {
        // Verify it's a git repository synchronously
        let output = std::process::Command::new("git")
            .args(["rev-parse", "--git-dir"])
            .current_dir(&root)
            .output()
            .map_err(|e| GitPollerError::GitExecutionError {
                stderr: e.to_string(),
            })?;

        if !output.status.success() {
            return Err(GitPollerError::NotGitRepository { path: root });
        }

        let (event_tx, event_rx) = mpsc::channel(config.channel_capacity);
        let (shutdown_tx, shutdown_rx) = watch::channel(false);

        let poller = Self {
            root,
            config,
            previous_state: GitState::default(),
            previous_head: None,
            event_tx,
            shutdown_rx,
        };

        Ok((poller, event_rx, shutdown_tx))
    }

    /// Run the polling loop until shutdown is signaled.
    ///
    /// This method runs indefinitely, polling at the configured interval
    /// and emitting FileEvents for detected changes.
    pub async fn run(&mut self) -> Result<(), GitPollerError> {
        let mut interval = tokio::time::interval(self.config.poll_interval);

        // First tick is immediate, which we want for initial state capture
        loop {
            tokio::select! {
                _ = interval.tick() => {
                    match self.poll_with_retry().await {
                        Ok(events) => {
                            for event in events {
                                // Convert relative paths to absolute paths
                                let absolute_event = self.make_event_absolute(event);
                                if self.event_tx.send(absolute_event).await.is_err() {
                                    // Receiver dropped, stop polling
                                    return Err(GitPollerError::ChannelClosed);
                                }
                            }
                        }
                        Err(GitPollerError::GitOperationInProgress) => {
                            // Skip this cycle, git is busy
                            debug!("git operation in progress, skipping poll cycle");
                        }
                        Err(e) => {
                            // Log but continue - may recover on next poll
                            warn!("git poll error: {}", e);
                        }
                    }
                }
                _ = self.shutdown_rx.changed() => {
                    if *self.shutdown_rx.borrow() {
                        info!("git poller shutting down");
                        return Ok(());
                    }
                }
            }
        }
    }

    /// Execute a single poll cycle without retry logic.
    ///
    /// This is useful for testing and one-off polling. Includes HEAD tracking
    /// to detect files changed in commits between polls.
    pub async fn poll_once(&mut self) -> Result<Vec<FileEvent>, GitPollerError> {
        let events = self.poll_once_inner().await?;
        debug!("poll_once: {} events detected", events.len());
        Ok(events)
    }

    /// Execute a poll cycle with retry logic for transient failures.
    async fn poll_with_retry(&mut self) -> Result<Vec<FileEvent>, GitPollerError> {
        let mut last_error = None;

        for attempt in 0..self.config.retry_count {
            match self.poll_once_inner().await {
                Ok(events) => return Ok(events),
                Err(GitPollerError::GitOperationInProgress) => {
                    // Don't retry for lock errors, just skip this cycle
                    return Err(GitPollerError::GitOperationInProgress);
                }
                Err(e) => {
                    debug!("poll attempt {} failed: {}", attempt + 1, e);
                    last_error = Some(e);
                    if attempt < self.config.retry_count - 1 {
                        tokio::time::sleep(self.config.retry_delay).await;
                    }
                }
            }
        }

        Err(last_error.unwrap_or(GitPollerError::GitExecutionError {
            stderr: "unknown error after retries".to_string(),
        }))
    }

    /// Inner poll logic without public exposure.
    async fn poll_once_inner(&mut self) -> Result<Vec<FileEvent>, GitPollerError> {
        let mut events = Vec::new();

        // Check for HEAD changes (commits that occurred between polls)
        if let Ok(current_head) = self.get_head().await {
            if let Some(ref prev_head) = self.previous_head {
                if &current_head != prev_head {
                    // HEAD changed - commits occurred between polls
                    debug!(
                        "HEAD changed from {} to {}",
                        &prev_head[..8.min(prev_head.len())],
                        &current_head[..8.min(current_head.len())]
                    );
                    match self.get_commit_changes(prev_head, &current_head).await {
                        Ok(changed_files) => {
                            for file in changed_files {
                                events.push(FileEvent::Modified(file));
                            }
                        }
                        Err(e) => {
                            // Log but continue - old HEAD may not exist (force push, shallow clone)
                            warn!("failed to get commit changes: {}", e);
                        }
                    }
                }
            }
            self.previous_head = Some(current_head);
        }
        // If get_head fails (empty repo), just skip HEAD tracking

        // Standard git status polling
        let output = self.run_git_status().await?;
        let new_state = GitState::from_git_status(&output)?;

        let status_events = self.previous_state.diff(&new_state);
        self.previous_state = new_state;

        events.extend(status_events);
        Ok(events)
    }

    /// Get the current HEAD commit hash.
    ///
    /// Returns an error if the repository has no commits (empty repo).
    async fn get_head(&self) -> Result<String, GitPollerError> {
        let output = tokio::time::timeout(
            self.config.git_timeout,
            Command::new("git")
                .args(["rev-parse", "HEAD"])
                .current_dir(&self.root)
                .output(),
        )
        .await
        .map_err(|_| GitPollerError::GitTimeout {
            timeout: self.config.git_timeout,
        })?
        .map_err(|e| GitPollerError::GitExecutionError {
            stderr: e.to_string(),
        })?;

        if !output.status.success() {
            // May fail on empty repo (no commits yet)
            return Err(GitPollerError::GitExecutionError {
                stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            });
        }

        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    /// Get files changed between two commits.
    ///
    /// Returns relative paths of files that changed between the two commits.
    /// If the diff fails (e.g., old commit doesn't exist after force push),
    /// returns an empty vec rather than failing.
    async fn get_commit_changes(
        &self,
        old: &str,
        new: &str,
    ) -> Result<Vec<PathBuf>, GitPollerError> {
        let output = tokio::time::timeout(
            self.config.git_timeout,
            Command::new("git")
                .args(["diff", "--name-only", &format!("{}..{}", old, new)])
                .current_dir(&self.root)
                .output(),
        )
        .await
        .map_err(|_| GitPollerError::GitTimeout {
            timeout: self.config.git_timeout,
        })?
        .map_err(|e| GitPollerError::GitExecutionError {
            stderr: e.to_string(),
        })?;

        if !output.status.success() {
            // Old commit may not exist (force push, shallow clone)
            // Return empty to let the caller continue with status-only events
            debug!(
                "git diff failed (old commit may not exist): {}",
                String::from_utf8_lossy(&output.stderr)
            );
            return Ok(vec![]);
        }

        let files = String::from_utf8_lossy(&output.stdout)
            .lines()
            .filter(|line| !line.is_empty())
            .map(|line| PathBuf::from(line.trim()))
            .collect();

        Ok(files)
    }

    /// Execute git status command with timeout.
    async fn run_git_status(&self) -> Result<String, GitPollerError> {
        let mut cmd = Command::new("git");
        cmd.args(["status", "--porcelain"]);

        if self.config.detect_renames {
            cmd.arg("-M");
        }

        // Use -u to show individual untracked files instead of just directory names
        // This ensures nested files are reported with full paths
        if self.config.include_untracked {
            cmd.arg("-u");
        }

        cmd.current_dir(&self.root);

        let output = tokio::time::timeout(self.config.git_timeout, cmd.output())
            .await
            .map_err(|_| GitPollerError::GitTimeout {
                timeout: self.config.git_timeout,
            })?
            .map_err(|e| GitPollerError::GitExecutionError {
                stderr: e.to_string(),
            })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).to_string();

            // Check for specific error conditions
            if stderr.contains("not a git repository") {
                return Err(GitPollerError::NotGitRepository {
                    path: self.root.clone(),
                });
            }
            if stderr.contains(".git/index.lock") || stderr.contains("index.lock") {
                return Err(GitPollerError::GitOperationInProgress);
            }

            return Err(GitPollerError::GitExecutionError { stderr });
        }

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Get the root directory being watched.
    pub fn root(&self) -> &PathBuf {
        &self.root
    }

    /// Get the current configuration.
    pub fn config(&self) -> &GitPollerConfig {
        &self.config
    }

    /// Get statistics about the current state.
    pub fn stats(&self) -> GitPollerStats {
        GitPollerStats {
            tracked_files: self.previous_state.len(),
        }
    }

    /// Convert relative paths in a FileEvent to absolute paths.
    ///
    /// Git status returns relative paths from the repository root.
    /// Consumers expect absolute paths, so we need to join with self.root.
    fn make_event_absolute(&self, event: FileEvent) -> FileEvent {
        match event {
            FileEvent::Modified(path) => FileEvent::Modified(self.root.join(path)),
            FileEvent::Deleted(path) => FileEvent::Deleted(self.root.join(path)),
            FileEvent::Renamed(old, new) => {
                FileEvent::Renamed(self.root.join(old), self.root.join(new))
            }
        }
    }
}

/// Statistics about the git poller state.
#[derive(Debug, Clone)]
pub struct GitPollerStats {
    /// Number of files currently tracked as dirty.
    pub tracked_files: usize,
}

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

    /// Helper to create a temporary git repository.
    fn create_temp_git_repo() -> TempDir {
        let dir = TempDir::new().unwrap();
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        dir
    }

    #[test]
    fn test_config_default() {
        let config = GitPollerConfig::default();
        assert_eq!(config.poll_interval, Duration::from_secs(3));
        assert!(config.include_untracked);
        assert!(config.detect_renames);
        assert_eq!(config.git_timeout, Duration::from_secs(10));
        assert_eq!(config.retry_count, 3);
        assert_eq!(config.retry_delay, Duration::from_secs(1));
        assert_eq!(config.channel_capacity, 1000);
    }

    #[test]
    fn test_new_valid_repo() {
        let dir = create_temp_git_repo();
        let config = GitPollerConfig::default();
        let result = GitPoller::new(dir.path().to_path_buf(), config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_new_invalid_repo() {
        let dir = TempDir::new().unwrap();
        let config = GitPollerConfig::default();
        let result = GitPoller::new(dir.path().to_path_buf(), config);
        assert!(matches!(
            result,
            Err(GitPollerError::NotGitRepository { .. })
        ));
    }

    #[tokio::test]
    async fn test_poll_once_empty_repo() {
        let dir = create_temp_git_repo();
        let config = GitPollerConfig::default();
        let (mut poller, _rx, _shutdown) =
            GitPoller::new(dir.path().to_path_buf(), config).unwrap();

        let events = poller.poll_once().await.unwrap();
        // Empty repo should have no dirty files
        assert!(events.is_empty());
    }

    #[tokio::test]
    async fn test_poll_once_detects_new_file() {
        let dir = create_temp_git_repo();

        // Initial poll to capture baseline
        let config = GitPollerConfig::default();
        let (mut poller, _rx, _shutdown) =
            GitPoller::new(dir.path().to_path_buf(), config).unwrap();
        let _ = poller.poll_once().await.unwrap();

        // Create a new file
        std::fs::write(dir.path().join("test.txt"), "hello").unwrap();

        // Second poll should detect the new file
        let events = poller.poll_once().await.unwrap();
        assert_eq!(events.len(), 1);
        match &events[0] {
            FileEvent::Modified(path) => {
                assert_eq!(path.file_name().unwrap(), "test.txt");
            }
            _ => panic!("Expected Modified event"),
        }
    }

    #[tokio::test]
    async fn test_poll_once_detects_modification() {
        let dir = create_temp_git_repo();

        // Create and commit a file
        let file_path = dir.path().join("test.txt");
        std::fs::write(&file_path, "initial").unwrap();
        std::process::Command::new("git")
            .args(["add", "test.txt"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "initial"])
            .current_dir(dir.path())
            .output()
            .unwrap();

        // Initial poll
        let config = GitPollerConfig::default();
        let (mut poller, _rx, _shutdown) =
            GitPoller::new(dir.path().to_path_buf(), config).unwrap();
        let _ = poller.poll_once().await.unwrap();

        // Modify the file
        std::fs::write(&file_path, "modified").unwrap();

        // Second poll should detect modification
        let events = poller.poll_once().await.unwrap();
        assert_eq!(events.len(), 1);
        match &events[0] {
            FileEvent::Modified(path) => {
                assert_eq!(path.file_name().unwrap(), "test.txt");
            }
            _ => panic!("Expected Modified event"),
        }
    }

    #[tokio::test]
    async fn test_poll_once_detects_deletion() {
        let dir = create_temp_git_repo();

        // Create an untracked file
        let file_path = dir.path().join("test.txt");
        std::fs::write(&file_path, "content").unwrap();

        // Initial poll captures the untracked file
        let config = GitPollerConfig::default();
        let (mut poller, _rx, _shutdown) =
            GitPoller::new(dir.path().to_path_buf(), config).unwrap();
        let _ = poller.poll_once().await.unwrap();

        // Delete the file
        std::fs::remove_file(&file_path).unwrap();

        // Second poll should detect deletion
        let events = poller.poll_once().await.unwrap();
        assert_eq!(events.len(), 1);
        match &events[0] {
            FileEvent::Deleted(path) => {
                assert_eq!(path.file_name().unwrap(), "test.txt");
            }
            _ => panic!("Expected Deleted event"),
        }
    }

    #[tokio::test]
    async fn test_shutdown_signal() {
        let dir = create_temp_git_repo();
        let config = GitPollerConfig {
            poll_interval: Duration::from_millis(50),
            ..Default::default()
        };

        let (mut poller, _rx, shutdown_tx) =
            GitPoller::new(dir.path().to_path_buf(), config).unwrap();

        // Spawn the poller
        let handle = tokio::spawn(async move { poller.run().await });

        // Give it time to start
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Send shutdown signal
        shutdown_tx.send(true).unwrap();

        // Should complete without error
        let result = tokio::time::timeout(Duration::from_secs(1), handle)
            .await
            .expect("poller should stop within timeout");

        assert!(result.is_ok());
        assert!(result.unwrap().is_ok());
    }

    #[test]
    fn test_stats() {
        let dir = create_temp_git_repo();
        let config = GitPollerConfig::default();
        let (poller, _rx, _shutdown) = GitPoller::new(dir.path().to_path_buf(), config).unwrap();

        let stats = poller.stats();
        assert_eq!(stats.tracked_files, 0);
    }

    #[test]
    fn test_error_conversion_from_git_state_error() {
        let git_state_err = GitStateError::InvalidPath {
            path: PathBuf::from("/test"),
            reason: "test reason".to_string(),
        };
        let poller_err: GitPollerError = git_state_err.into();
        assert!(matches!(poller_err, GitPollerError::ParseError { .. }));
    }

    // ===== HEAD commit detection tests =====

    #[tokio::test]
    async fn test_detects_file_created_and_committed_within_poll_interval() {
        let dir = create_temp_git_repo();

        // Create initial commit so repo has a HEAD
        let initial_file = dir.path().join("initial.txt");
        std::fs::write(&initial_file, "initial").unwrap();
        std::process::Command::new("git")
            .args(["add", "initial.txt"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "initial commit"])
            .current_dir(dir.path())
            .output()
            .unwrap();

        // Create poller and do initial poll to capture baseline HEAD
        let config = GitPollerConfig::default();
        let (mut poller, _rx, _shutdown) =
            GitPoller::new(dir.path().to_path_buf(), config).unwrap();
        let _ = poller.poll_once().await.unwrap();

        // Simulate "create and commit within poll interval" scenario:
        // Create a new file, add it, and commit - all before next poll
        let new_file = dir.path().join("new_file.txt");
        std::fs::write(&new_file, "new content").unwrap();
        std::process::Command::new("git")
            .args(["add", "new_file.txt"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "add new file"])
            .current_dir(dir.path())
            .output()
            .unwrap();

        // Now poll - should detect the new file through HEAD tracking
        let events = poller.poll_once().await.unwrap();

        // Should have exactly one Modified event for the new file
        assert!(
            !events.is_empty(),
            "Expected events for committed file, got none"
        );

        let has_new_file_event = events.iter().any(|e| match e {
            FileEvent::Modified(path) => path.file_name().unwrap() == "new_file.txt",
            _ => false,
        });
        assert!(
            has_new_file_event,
            "Expected Modified event for new_file.txt, got: {:?}",
            events
        );
    }

    #[tokio::test]
    async fn test_detects_file_modified_and_committed_within_poll_interval() {
        let dir = create_temp_git_repo();

        // Create and commit initial file
        let file_path = dir.path().join("test.txt");
        std::fs::write(&file_path, "initial").unwrap();
        std::process::Command::new("git")
            .args(["add", "test.txt"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "initial commit"])
            .current_dir(dir.path())
            .output()
            .unwrap();

        // Initial poll to capture baseline
        let config = GitPollerConfig::default();
        let (mut poller, _rx, _shutdown) =
            GitPoller::new(dir.path().to_path_buf(), config).unwrap();
        let _ = poller.poll_once().await.unwrap();

        // Modify, stage, and commit - all before next poll
        std::fs::write(&file_path, "modified content").unwrap();
        std::process::Command::new("git")
            .args(["add", "test.txt"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "modify file"])
            .current_dir(dir.path())
            .output()
            .unwrap();

        // Poll should detect the modification through HEAD tracking
        let events = poller.poll_once().await.unwrap();

        let has_test_file_event = events.iter().any(|e| match e {
            FileEvent::Modified(path) => path.file_name().unwrap() == "test.txt",
            _ => false,
        });
        assert!(
            has_test_file_event,
            "Expected Modified event for test.txt, got: {:?}",
            events
        );
    }

    #[tokio::test]
    async fn test_multiple_commits_within_poll_interval() {
        let dir = create_temp_git_repo();

        // Create initial commit
        let initial = dir.path().join("initial.txt");
        std::fs::write(&initial, "initial").unwrap();
        std::process::Command::new("git")
            .args(["add", "initial.txt"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "initial"])
            .current_dir(dir.path())
            .output()
            .unwrap();

        // Initial poll
        let config = GitPollerConfig::default();
        let (mut poller, _rx, _shutdown) =
            GitPoller::new(dir.path().to_path_buf(), config).unwrap();
        let _ = poller.poll_once().await.unwrap();

        // Multiple commits before next poll
        std::fs::write(dir.path().join("file1.txt"), "content1").unwrap();
        std::process::Command::new("git")
            .args(["add", "file1.txt"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "add file1"])
            .current_dir(dir.path())
            .output()
            .unwrap();

        std::fs::write(dir.path().join("file2.txt"), "content2").unwrap();
        std::process::Command::new("git")
            .args(["add", "file2.txt"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "add file2"])
            .current_dir(dir.path())
            .output()
            .unwrap();

        // Poll should detect both files
        let events = poller.poll_once().await.unwrap();

        let file_names: Vec<String> = events
            .iter()
            .filter_map(|e| match e {
                FileEvent::Modified(path) => {
                    path.file_name().map(|n| n.to_string_lossy().to_string())
                }
                _ => None,
            })
            .collect();

        assert!(
            file_names.contains(&"file1.txt".to_string()),
            "Expected file1.txt in events: {:?}",
            file_names
        );
        assert!(
            file_names.contains(&"file2.txt".to_string()),
            "Expected file2.txt in events: {:?}",
            file_names
        );
    }

    #[tokio::test]
    async fn test_empty_repo_no_head_tracking() {
        let dir = create_temp_git_repo();

        // Repo has no commits, so no HEAD
        let config = GitPollerConfig::default();
        let (mut poller, _rx, _shutdown) =
            GitPoller::new(dir.path().to_path_buf(), config).unwrap();

        // Should not crash on empty repo
        let events = poller.poll_once().await.unwrap();
        assert!(events.is_empty());

        // Still shouldn't crash on subsequent poll
        let events = poller.poll_once().await.unwrap();
        assert!(events.is_empty());
    }

    #[tokio::test]
    async fn test_first_poll_records_head_no_diff() {
        let dir = create_temp_git_repo();

        // Create initial commit
        std::fs::write(dir.path().join("initial.txt"), "content").unwrap();
        std::process::Command::new("git")
            .args(["add", "initial.txt"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "initial"])
            .current_dir(dir.path())
            .output()
            .unwrap();

        // First poll should not emit events for the existing commit
        // (we only track changes, not initial state)
        let config = GitPollerConfig::default();
        let (mut poller, _rx, _shutdown) =
            GitPoller::new(dir.path().to_path_buf(), config).unwrap();

        let events = poller.poll_once().await.unwrap();
        // No events because nothing changed and we just recorded the HEAD
        assert!(
            events.is_empty(),
            "Expected no events on first poll, got: {:?}",
            events
        );

        // Verify previous_head was recorded
        assert!(poller.previous_head.is_some());
    }

    #[tokio::test]
    async fn test_head_unchanged_no_extra_events() {
        let dir = create_temp_git_repo();

        // Create initial commit
        std::fs::write(dir.path().join("initial.txt"), "content").unwrap();
        std::process::Command::new("git")
            .args(["add", "initial.txt"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "initial"])
            .current_dir(dir.path())
            .output()
            .unwrap();

        let config = GitPollerConfig::default();
        let (mut poller, _rx, _shutdown) =
            GitPoller::new(dir.path().to_path_buf(), config).unwrap();

        // First poll
        let _ = poller.poll_once().await.unwrap();

        // Create untracked file (no commit)
        std::fs::write(dir.path().join("untracked.txt"), "untracked").unwrap();

        // Second poll - HEAD hasn't changed, should only get status-based events
        let events = poller.poll_once().await.unwrap();

        // Should have exactly one event for the untracked file
        assert_eq!(events.len(), 1, "Expected 1 event, got: {:?}", events);
        match &events[0] {
            FileEvent::Modified(path) => {
                assert_eq!(path.file_name().unwrap(), "untracked.txt");
            }
            _ => panic!("Expected Modified event for untracked.txt"),
        }
    }
}