sqry-core 11.0.4

Core library for sqry - semantic code search engine
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
//! Subprocess-backed git implementation
//!
//! This backend executes git commands via subprocess for change detection.
//! It provides robust error handling, timeout protection, and output size limits.

use super::{ChangeSet, GitBackend, GitCapabilities, GitError, Result, parser};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;

/// Maximum allowed git output size (10 MB by default)
///
/// Can be overridden via `SQRY_GIT_MAX_OUTPUT_SIZE` environment variable.
/// Values are clamped to 1 MB - 100 MB range for security (P1-17).
const DEFAULT_MAX_OUTPUT_SIZE: usize = 10 * 1024 * 1024; // 10 MB
const MIN_MAX_OUTPUT_SIZE: usize = 1024 * 1024; // 1 MB minimum
const MAX_MAX_OUTPUT_SIZE: usize = 100 * 1024 * 1024; // 100 MB maximum

/// Default timeout for git commands (3 seconds)
const DEFAULT_TIMEOUT_MS: u64 = 3000;

/// Get maximum git output size, respecting environment variable override
///
/// Reads from `SQRY_GIT_MAX_OUTPUT_SIZE` environment variable.
/// If not set or invalid, returns 10 MB default.
/// Values are clamped between 1 MB and 100 MB for safety (P1-17).
///
/// # Security
///
/// This limit prevents `DoS` attacks from malicious repositories that could
/// produce arbitrarily large git diffs or status output, leading to memory
/// exhaustion and potential OOM kills.
///
/// # Examples
///
/// ```
/// # use sqry_core::git::max_git_output_size;
/// // Default behavior
/// let size = max_git_output_size(); // 10 MB (10485760 bytes)
/// assert_eq!(size, 10 * 1024 * 1024);
/// ```
///
/// ```
/// # use sqry_core::git::max_git_output_size;
/// // With environment override
/// unsafe { std::env::set_var("SQRY_GIT_MAX_OUTPUT_SIZE", "52428800"); } // 50 MB
/// let size = max_git_output_size(); // 50 MB
/// assert_eq!(size, 52428800);
/// # unsafe { std::env::remove_var("SQRY_GIT_MAX_OUTPUT_SIZE"); }
/// ```
///
/// ```
/// # use sqry_core::git::max_git_output_size;
/// // Clamping: value too low
/// unsafe { std::env::set_var("SQRY_GIT_MAX_OUTPUT_SIZE", "500"); } // 500 bytes (too small)
/// let size = max_git_output_size(); // Clamped to 1 MB minimum
/// assert_eq!(size, 1024 * 1024);
/// # unsafe { std::env::remove_var("SQRY_GIT_MAX_OUTPUT_SIZE"); }
/// ```
///
/// ```
/// # use sqry_core::git::max_git_output_size;
/// // Malformed value
/// unsafe { std::env::set_var("SQRY_GIT_MAX_OUTPUT_SIZE", "invalid"); }
/// let size = max_git_output_size(); // Falls back to 10 MB default
/// assert_eq!(size, 10 * 1024 * 1024);
/// # unsafe { std::env::remove_var("SQRY_GIT_MAX_OUTPUT_SIZE"); }
/// ```
#[must_use]
pub fn max_git_output_size() -> usize {
    let size = std::env::var("SQRY_GIT_MAX_OUTPUT_SIZE")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(DEFAULT_MAX_OUTPUT_SIZE);
    size.clamp(MIN_MAX_OUTPUT_SIZE, MAX_MAX_OUTPUT_SIZE)
}

/// Subprocess-backed git integration
///
/// Executes git commands via `Command::new("git")` with array arguments
/// (no shell invocation) to prevent command injection.
///
/// # Security
///
/// - Command injection: Uses `Command::new("git")` with array args, never shell
/// - Path traversal: All paths are canonicalized and validated
/// - Resource exhaustion: Output limited to 10MB, commands timeout after 3s
/// - Process cleanup: Hung processes killed with SIGTERM then SIGKILL
#[derive(Debug, Clone, Copy, Default)]
pub struct SubprocessGit;

impl SubprocessGit {
    /// Create a new subprocess git backend
    #[must_use]
    pub fn new() -> Self {
        Self
    }

    /// Execute a git command with timeout and output size limit
    ///
    /// # Security
    ///
    /// - Uses `Command::new("git")` with array args (no shell)
    /// - Limits output to configurable size (default 10MB, range 1MB-100MB)
    /// - Kills process after timeout (default 3s)
    /// - Captures stderr for error reporting
    ///
    /// # Visibility
    ///
    /// Public within crate to allow `RecencyIndex` and other git modules to use
    /// the same safety mechanisms (output limits, timeouts).
    pub(crate) fn execute_git(args: &[&str], timeout_ms: Option<u64>) -> Result<String> {
        let timeout = Duration::from_millis(timeout_ms.unwrap_or(DEFAULT_TIMEOUT_MS));
        let max_output_size = max_git_output_size(); // P1-17: Configurable limit

        // Build command (no shell invocation)
        let mut cmd = Command::new("git");
        cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());

        // Spawn process
        let mut child = cmd.spawn().map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                GitError::NotFound
            } else {
                GitError::CommandFailed {
                    message: format!("Failed to spawn git: {e}"),
                    stdout: String::new(),
                    stderr: String::new(),
                }
            }
        })?;

        // Wait with timeout
        let start = std::time::Instant::now();
        let result = loop {
            match child.try_wait() {
                Ok(Some(status)) => {
                    // Process exited
                    break status;
                }
                Ok(None) => {
                    // Still running - check timeout
                    if start.elapsed() >= timeout {
                        // Timeout - kill process
                        let _ = child.kill();
                        // Duration beyond u64::MAX ms (~584 million years) is impossible; clamp to max
                        let timeout_ms = timeout.as_millis().try_into().unwrap_or(u64::MAX);
                        return Err(GitError::Timeout(timeout_ms));
                    }
                    // Sleep briefly to avoid busy-wait
                    std::thread::sleep(Duration::from_millis(10));
                }
                Err(e) => {
                    return Err(GitError::CommandFailed {
                        message: format!("Failed to wait for git: {e}"),
                        stdout: String::new(),
                        stderr: String::new(),
                    });
                }
            }
        };

        let status = result;

        // Read stdout (with size limit)
        // P1-17: Read +1 byte to detect if limit was exceeded
        let mut stdout = Vec::new();
        if let Some(out) = child.stdout.take() {
            let mut limited = out.take((max_output_size + 1) as u64);
            limited
                .read_to_end(&mut stdout)
                .map_err(|e| GitError::CommandFailed {
                    message: format!("Failed to read stdout: {e}"),
                    stdout: String::new(),
                    stderr: String::new(),
                })?;

            // P1-17: Hard error if limit exceeded (not silent truncation)
            if stdout.len() > max_output_size {
                return Err(GitError::OutputExceededLimit {
                    limit_bytes: max_output_size,
                    actual_bytes: stdout.len(), // Exact size (we read it all)
                });
            }
        }

        // Read stderr (for error messages)
        let mut stderr = Vec::new();
        if let Some(err) = child.stderr.take() {
            let mut limited = err.take((max_output_size + 1) as u64);
            limited
                .read_to_end(&mut stderr)
                .map_err(|e| GitError::CommandFailed {
                    message: format!("Failed to read stderr: {e}"),
                    stdout: String::new(),
                    stderr: String::new(),
                })?;
        }

        // Check exit status
        if !status.success() {
            let stdout_str = String::from_utf8_lossy(&stdout);
            let stderr_str = String::from_utf8_lossy(&stderr);
            return Err(GitError::CommandFailed {
                message: format!("Exit code {}", status.code().unwrap_or(-1)),
                stdout: stdout_str.to_string(),
                stderr: stderr_str.to_string(),
            });
        }

        // Convert stdout to string
        String::from_utf8(stdout)
            .map_err(|e| GitError::InvalidOutput(format!("Git output is not valid UTF-8: {e}")))
    }

    /// Get timeout from environment variable (clamped to 100-60000ms)
    fn get_timeout_ms() -> Option<u64> {
        std::env::var("SQRY_GIT_TIMEOUT_MS")
            .ok()
            .and_then(|s| s.parse::<u64>().ok())
            .map(|t| t.clamp(100, 60000))
    }

    /// Get rename similarity threshold from environment (clamped to 0-100)
    #[allow(dead_code)]
    fn get_rename_similarity() -> u8 {
        std::env::var("SQRY_GIT_RENAME_SIMILARITY")
            .ok()
            .and_then(|s| s.parse::<u8>().ok())
            .map_or(50, |s| s.min(100))
    }

    /// Check if untracked files should be included (default: true)
    #[allow(dead_code)]
    fn should_include_untracked() -> bool {
        std::env::var("SQRY_GIT_INCLUDE_UNTRACKED")
            .ok()
            .and_then(|s| s.parse::<u8>().ok())
            != Some(0)
    }
}

impl GitBackend for SubprocessGit {
    fn is_repo(&self, root: &Path) -> Result<bool> {
        let result = Self::execute_git(
            &["-C", &root.display().to_string(), "rev-parse", "--git-dir"],
            Self::get_timeout_ms(),
        );

        match result {
            Ok(_) => Ok(true),
            Err(GitError::CommandFailed { stderr, .. })
                if stderr.contains("not a git repository") =>
            {
                Ok(false)
            }
            Err(GitError::NotFound) => Ok(false),
            Err(e) => Err(e),
        }
    }

    fn repo_root(&self, root: &Path) -> Result<PathBuf> {
        let output = Self::execute_git(
            &[
                "-C",
                &root.display().to_string(),
                "rev-parse",
                "--show-toplevel",
            ],
            Self::get_timeout_ms(),
        )?;

        Ok(PathBuf::from(output.trim()))
    }

    fn head(&self, root: &Path) -> Result<Option<String>> {
        let result = Self::execute_git(
            &["-C", &root.display().to_string(), "rev-parse", "HEAD"],
            Self::get_timeout_ms(),
        );

        match result {
            Ok(output) => Ok(Some(output.trim().to_string())),
            Err(GitError::CommandFailed { message, .. }) if message.contains("128") => {
                // HEAD-less repo (no commits yet)
                Ok(None)
            }
            Err(e) => Err(e),
        }
    }

    fn uncommitted(
        &self,
        root: &Path,
        include_untracked: bool,
    ) -> Result<(ChangeSet, Option<String>)> {
        // Get current HEAD before querying status (to avoid race)
        let head = self.head(root)?;

        // Convert path to string (needed for lifetime)
        let root_str = root.display().to_string();

        // Execute git status with null-terminated output
        let args = if include_untracked {
            vec![
                "-C",
                &root_str,
                "status",
                "--porcelain=v1",
                "-z",
                "--ignore-submodules=all",
            ]
        } else {
            vec![
                "-C",
                &root_str,
                "status",
                "--porcelain=v1",
                "-z",
                "--ignore-submodules=all",
                "--untracked-files=no",
            ]
        };

        let output = Self::execute_git(&args, Self::get_timeout_ms())?;

        // Parse porcelain output
        let changeset = parser::parse_porcelain(&output)?;

        Ok((changeset, head))
    }

    fn since(
        &self,
        root: &Path,
        baseline: &str,
        rename_similarity: u8,
    ) -> Result<(ChangeSet, Option<String>)> {
        // Get current HEAD before querying diff (to avoid race)
        let head = self.head(root)?;

        // Build diff range (baseline..HEAD)
        let range = format!("{baseline}..HEAD");

        // Execute git diff with null-terminated output
        let similarity = format!("-M{rename_similarity}");
        let output = Self::execute_git(
            &[
                "-C",
                &root.display().to_string(),
                "diff",
                "--name-status",
                "-z",
                &similarity,
                "--ignore-submodules=all",
                &range, // range before path separator per git syntax
                "--",
            ],
            Self::get_timeout_ms(),
        )?;

        // Parse diff output
        let changeset = parser::parse_diff_name_status(&output)?;

        Ok((changeset, head))
    }

    fn capabilities(&self) -> GitCapabilities {
        GitCapabilities {
            supports_blame: false,         // Blame not yet implemented
            supports_time_travel: false,   // Time-travel not yet implemented
            supports_history_index: false, // Historical indexing not yet implemented
        }
    }
}

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

    fn tempdir_outside_git_repo() -> tempfile::TempDir {
        #[cfg(unix)]
        fn is_in_git_repo(path: &std::path::Path) -> bool {
            path.ancestors()
                .any(|ancestor| ancestor.join(".git").is_dir())
        }

        #[cfg(unix)]
        {
            for base in [
                std::path::Path::new("/var/tmp"),
                std::path::Path::new("/dev/shm"),
            ] {
                if base.is_dir()
                    && !is_in_git_repo(base)
                    && let Ok(tmpdir) = tempfile::TempDir::new_in(base)
                {
                    return tmpdir;
                }
            }
        }

        tempfile::tempdir().expect("create temp dir")
    }

    /// Helper to create a temporary git repo for testing
    fn create_test_repo() -> tempfile::TempDir {
        let tmpdir = tempfile::tempdir().unwrap();
        let path = tmpdir.path();

        // Initialize git repo
        let init = Command::new("git")
            .args(["init"])
            .current_dir(path)
            .output()
            .expect("Failed to init git repo");
        assert!(init.status.success(), "git init failed: {init:?}");

        // Configure git user for commits
        let cfg1 = Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(path)
            .output()
            .expect("Failed to config user.name");
        assert!(
            cfg1.status.success(),
            "git config user.name failed: {cfg1:?}"
        );

        let cfg2 = Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(path)
            .output()
            .expect("Failed to config user.email");
        assert!(
            cfg2.status.success(),
            "git config user.email failed: {cfg2:?}"
        );

        // Disable GPG signing to avoid global config interference
        let cfg3 = Command::new("git")
            .args(["config", "commit.gpgSign", "false"])
            .current_dir(path)
            .output()
            .expect("Failed to config commit.gpgSign");
        assert!(
            cfg3.status.success(),
            "git config commit.gpgSign failed: {cfg3:?}"
        );

        // Disable CRLF conversion for consistent line endings across platforms
        let cfg4 = Command::new("git")
            .args(["config", "core.autocrlf", "false"])
            .current_dir(path)
            .output()
            .expect("Failed to config core.autocrlf");
        assert!(
            cfg4.status.success(),
            "git config core.autocrlf failed: {cfg4:?}"
        );

        tmpdir
    }

    #[test]
    fn test_is_repo_true() {
        let tmpdir = create_test_repo();
        let backend = SubprocessGit::new();

        let result = backend.is_repo(tmpdir.path());
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_is_repo_false() {
        let tmpdir = tempdir_outside_git_repo();
        let backend = SubprocessGit::new();

        let result = backend.is_repo(tmpdir.path());
        assert!(result.is_ok());
        assert!(!result.unwrap());
    }

    #[test]
    fn test_repo_root() {
        let tmpdir = create_test_repo();
        let backend = SubprocessGit::new();

        let result = backend.repo_root(tmpdir.path());
        assert!(result.is_ok());

        let root = result.unwrap();
        assert!(root.ends_with(tmpdir.path().file_name().unwrap()));
    }

    #[test]
    fn test_head_no_commits() {
        let tmpdir = create_test_repo();
        let backend = SubprocessGit::new();

        let result = backend.head(tmpdir.path());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), None); // No commits yet
    }

    #[test]
    fn test_head_with_commit() {
        let tmpdir = create_test_repo();
        let path = tmpdir.path();

        // Create and commit a file
        fs::write(path.join("test.txt"), "hello").unwrap();
        let add = Command::new("git")
            .args(["add", "test.txt"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(add.status.success(), "git add failed: {add:?}");
        let commit = Command::new("git")
            .args(["commit", "-m", "Initial commit"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(commit.status.success(), "git commit failed: {commit:?}");

        let backend = SubprocessGit::new();
        let result = backend.head(path);
        assert!(result.is_ok());

        let head = result.unwrap();
        assert!(head.is_some());
        assert_eq!(head.unwrap().len(), 40); // SHA-1 hash length
    }

    #[test]
    fn test_uncommitted_empty() {
        let tmpdir = create_test_repo();
        let path = tmpdir.path();

        // Create initial commit
        fs::write(path.join("test.txt"), "hello").unwrap();
        let add = Command::new("git")
            .args(["add", "test.txt"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(add.status.success());
        let commit = Command::new("git")
            .args(["commit", "-m", "Initial"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(commit.status.success());

        let backend = SubprocessGit::new();
        let result = backend.uncommitted(path, true);
        assert!(result.is_ok());

        let (changeset, head) = result.unwrap();
        assert!(changeset.is_empty());
        assert!(head.is_some());
    }

    #[test]
    fn test_uncommitted_modified() {
        let tmpdir = create_test_repo();
        let path = tmpdir.path();

        // Create initial commit
        fs::write(path.join("test.txt"), "hello").unwrap();
        let add = Command::new("git")
            .args(["add", "test.txt"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(add.status.success());
        let commit = Command::new("git")
            .args(["commit", "-m", "Initial"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(commit.status.success());

        // Modify file
        fs::write(path.join("test.txt"), "modified").unwrap();

        let backend = SubprocessGit::new();
        let result = backend.uncommitted(path, true);
        assert!(result.is_ok());

        let (changeset, _) = result.unwrap();
        assert_eq!(changeset.modified.len(), 1);
        assert_eq!(changeset.modified[0], PathBuf::from("test.txt"));
    }

    #[test]
    fn test_uncommitted_untracked() {
        let tmpdir = create_test_repo();
        let path = tmpdir.path();

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

        // Add untracked file
        fs::write(path.join("new.txt"), "new").unwrap();

        let backend = SubprocessGit::new();

        // With untracked
        let result = backend.uncommitted(path, true);
        assert!(result.is_ok());
        let (changeset, _) = result.unwrap();
        assert_eq!(changeset.added.len(), 1);

        // Without untracked
        let result = backend.uncommitted(path, false);
        assert!(result.is_ok());
        let (changeset, _) = result.unwrap();
        assert!(changeset.is_empty());
    }

    #[test]
    fn test_since() {
        let tmpdir = create_test_repo();
        let path = tmpdir.path();

        // Create first commit
        fs::write(path.join("file1.txt"), "hello").unwrap();
        let add = Command::new("git")
            .args(["add", "file1.txt"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(add.status.success());
        let commit = Command::new("git")
            .args(["commit", "-m", "First"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(commit.status.success());

        // Get baseline commit
        let backend = SubprocessGit::new();
        let baseline = backend.head(path).unwrap().unwrap();

        // Create second commit
        fs::write(path.join("file2.txt"), "world").unwrap();
        let add2 = Command::new("git")
            .args(["add", "file2.txt"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(add2.status.success());
        let commit2 = Command::new("git")
            .args(["commit", "-m", "Second"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(commit2.status.success());

        // Check changes since baseline
        let result = backend.since(path, &baseline, 50);
        assert!(result.is_ok());

        let (changeset, head) = result.unwrap();
        assert_eq!(changeset.added.len(), 1);
        assert_eq!(changeset.added[0], PathBuf::from("file2.txt"));
        assert!(head.is_some());
        assert_ne!(head.unwrap(), baseline); // HEAD moved
    }

    #[test]
    fn test_capabilities() {
        let backend = SubprocessGit::new();
        let caps = backend.capabilities();

        assert!(!caps.supports_blame);
        assert!(!caps.supports_time_travel);
        assert!(!caps.supports_history_index);
    }

    // P1-17: Tests for max_git_output_size() configuration function
    mod p1_17_git_output_limit {
        use super::*;
        use serial_test::serial;

        #[test]
        #[serial]
        fn test_max_git_output_size_default() {
            unsafe {
                std::env::remove_var("SQRY_GIT_MAX_OUTPUT_SIZE");
            }
            assert_eq!(max_git_output_size(), 10 * 1024 * 1024); // 10 MB
        }

        #[test]
        #[serial]
        fn test_max_git_output_size_env_override() {
            unsafe {
                std::env::set_var("SQRY_GIT_MAX_OUTPUT_SIZE", "52428800"); // 50 MB
            }
            assert_eq!(max_git_output_size(), 52_428_800);
            unsafe {
                std::env::remove_var("SQRY_GIT_MAX_OUTPUT_SIZE");
            }
        }

        #[test]
        #[serial]
        fn test_max_git_output_size_clamping_min() {
            unsafe {
                std::env::set_var("SQRY_GIT_MAX_OUTPUT_SIZE", "500"); // Below min (1 MB)
            }
            assert_eq!(max_git_output_size(), 1024 * 1024); // Clamped to 1 MB
            unsafe {
                std::env::remove_var("SQRY_GIT_MAX_OUTPUT_SIZE");
            }
        }

        #[test]
        #[serial]
        fn test_max_git_output_size_clamping_max() {
            unsafe {
                std::env::set_var("SQRY_GIT_MAX_OUTPUT_SIZE", "999000000000"); // Above max (100 MB)
            }
            assert_eq!(max_git_output_size(), 100 * 1024 * 1024); // Clamped to 100 MB
            unsafe {
                std::env::remove_var("SQRY_GIT_MAX_OUTPUT_SIZE");
            }
        }

        #[test]
        #[serial]
        fn test_max_git_output_size_malformed() {
            unsafe {
                std::env::set_var("SQRY_GIT_MAX_OUTPUT_SIZE", "invalid");
            }
            assert_eq!(max_git_output_size(), 10 * 1024 * 1024); // Falls back to default
            unsafe {
                std::env::remove_var("SQRY_GIT_MAX_OUTPUT_SIZE");
            }
        }

        #[test]
        fn test_output_exceeded_error_formatting() {
            let err = GitError::OutputExceededLimit {
                limit_bytes: 10 * 1024 * 1024,  // 10 MB
                actual_bytes: 15 * 1024 * 1024, // 15 MB
            };

            let msg = err.detailed_message();
            assert!(
                msg.contains("10.0 MB"),
                "Error message should show limit in MB"
            );
            assert!(
                msg.contains(">15.0 MB"),
                "Error message should show actual size in MB"
            );
            assert!(
                msg.contains("SQRY_GIT_MAX_OUTPUT_SIZE"),
                "Error message should mention env var"
            );
            assert!(
                msg.contains("git diff --stat"),
                "Error message should suggest investigation command"
            );
        }

        #[test]
        fn test_output_exceeded_error_suggested_limit() {
            let err = GitError::OutputExceededLimit {
                limit_bytes: 10 * 1024 * 1024,  // 10 MB
                actual_bytes: 15 * 1024 * 1024, // 15 MB
            };

            let suggested = err.suggested_limit();
            // Should suggest 2× actual, rounded up to nearest MB
            // 15MB × 2 = 30MB = 31457280 bytes
            // Rounded up to nearest MB: (30/1)+1 = 31MB = 32505856 bytes
            assert_eq!(suggested, 32_505_856); // 31 MB in bytes

            let msg = err.detailed_message();
            assert!(
                msg.contains("32505856"),
                "Error message should show suggested limit in bytes (31 MB = 32505856)"
            );
            assert!(
                msg.contains("31 MB"),
                "Error message should show suggested limit in MB"
            );
        }
    }
}