heroforge-core 0.2.2

Pure Rust core library for reading and writing Fossil SCM repositories
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
//! Comprehensive test suite for heroforge using builder pattern
//!
//! Tests many different conditions:
//! - Multiple files in single commit
//! - Deep directory structures
//! - Rapid file changes
//! - Large files
//! - Binary content
//! - Special characters
//! - Empty files
//! - Many files (100+)
//! - File modifications across versions

use heroforge_core::{Repository, Result};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::process::Command;
use std::time::Instant;

fn run_fossil(args: &[&str], cwd: &Path) -> std::result::Result<String, String> {
    let output = Command::new("heroforge")
        .args(args)
        .current_dir(cwd)
        .output()
        .map_err(|e| format!("Failed to run heroforge: {}", e))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("Heroforge command failed: {}", stderr));
    }

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

struct TestResult {
    name: String,
    passed: bool,
    details: String,
    duration_ms: u128,
}

fn main() -> Result<()> {
    let test_dir = Path::new("/tmp/fossil_comprehensive_test");

    // Clean up
    if test_dir.exists() {
        fs::remove_dir_all(test_dir).expect("Failed to clean up");
    }
    fs::create_dir_all(test_dir).expect("Failed to create test dir");

    let mut results: Vec<TestResult> = Vec::new();

    println!("=== heroforge Comprehensive Test Suite ===\n");

    // Run all tests
    results.push(test_multiple_files(test_dir));
    results.push(test_deep_directories(test_dir));
    results.push(test_rapid_changes(test_dir));
    results.push(test_large_files(test_dir));
    results.push(test_binary_content(test_dir));
    results.push(test_special_characters(test_dir));
    results.push(test_empty_files(test_dir));
    results.push(test_many_files(test_dir));
    results.push(test_file_modifications(test_dir));
    results.push(test_mixed_operations(test_dir));

    // Print summary
    println!("\n=== Test Summary ===\n");

    let mut passed = 0;
    let mut failed = 0;

    for result in &results {
        let status = if result.passed { "PASS" } else { "FAIL" };
        println!("[{}] {} ({} ms)", status, result.name, result.duration_ms);
        if !result.passed {
            println!("      {}", result.details);
            failed += 1;
        } else {
            passed += 1;
        }
    }

    println!("\nTotal: {} passed, {} failed", passed, failed);

    if failed > 0 {
        std::process::exit(1);
    }

    Ok(())
}

/// Test 1: Multiple files in a single commit
fn test_multiple_files(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Multiple files in single commit".to_string();

    let repo_path = base_dir.join("test_multiple_files.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let initial = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        // Create 5 files in one commit using builder pattern
        let commit_hash = repo
            .commit_builder()
            .message("Add 5 files")
            .author("testuser")
            .parent(&initial)
            .branch("trunk")
            .file("file1.txt", b"Content of file 1")
            .file("file2.txt", b"Content of file 2")
            .file("file3.txt", b"Content of file 3")
            .file("readme.md", b"# README\nThis is a test")
            .file("data.json", b"{\"key\": \"value\"}")
            .execute()?;

        // Verify all files can be read back using builder pattern
        let files = [
            ("file1.txt", "Content of file 1"),
            ("file2.txt", "Content of file 2"),
            ("file3.txt", "Content of file 3"),
            ("readme.md", "# README\nThis is a test"),
            ("data.json", "{\"key\": \"value\"}"),
        ];

        for (name, expected) in &files {
            let content = repo.files().at_commit(&commit_hash).read(name)?;
            if content != expected.as_bytes() {
                return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                    "Content mismatch for {}",
                    name
                )));
            }
        }

        // Verify with CLI
        let repo_str = repo_path.to_str().unwrap();
        for (name, expected) in &files {
            let cli_content = run_fossil(
                &["cat", name, "-r", &commit_hash[..16], "-R", repo_str],
                base_dir,
            )
            .map_err(|e| heroforge_core::FossilError::InvalidArtifact(e))?;
            if cli_content.as_bytes() != expected.as_bytes() {
                return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                    "CLI content mismatch for {}",
                    name
                )));
            }
        }

        Ok("5 files committed and verified".to_string())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 2: Deep directory structures
fn test_deep_directories(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Deep directory structures".to_string();

    let repo_path = base_dir.join("test_deep_dirs.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let initial = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        // Create files in deep directory structures using builder pattern
        let commit_hash = repo
            .commit_builder()
            .message("Add deep directory structure")
            .author("testuser")
            .parent(&initial)
            .branch("trunk")
            .file("src/main.rs", b"fn main() {}")
            .file("src/lib.rs", b"pub mod utils;")
            .file("src/utils/mod.rs", b"pub fn helper() {}")
            .file("src/utils/helpers/string.rs", b"pub fn trim() {}")
            .file("src/utils/helpers/number.rs", b"pub fn parse() {}")
            .file(
                "tests/integration/api/v1/test_users.rs",
                b"#[test] fn test() {}",
            )
            .file("docs/api/v1/users/readme.md", b"# Users API")
            .file("a/b/c/d/e/f/g/deep.txt", b"Very deep file")
            .execute()?;

        // Verify all files using builder pattern
        let files = repo.files().at_commit(&commit_hash).list()?;
        if files.len() != 8 {
            return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                "Expected 8 files, got {}",
                files.len()
            )));
        }

        // Verify a deep file
        let deep_content = repo
            .files()
            .at_commit(&commit_hash)
            .read("a/b/c/d/e/f/g/deep.txt")?;
        if deep_content != b"Very deep file" {
            return Err(heroforge_core::FossilError::InvalidArtifact(
                "Deep file content mismatch".into(),
            ));
        }

        Ok(format!(
            "{} files in deep directories verified",
            files.len()
        ))
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 3: Rapid file changes (many quick commits)
fn test_rapid_changes(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Rapid file changes (50 quick commits)".to_string();

    let repo_path = base_dir.join("test_rapid.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let mut parent = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        let num_commits = 50;
        let mut hashes: Vec<String> = Vec::new();

        // Make 50 rapid commits using builder pattern
        for i in 1..=num_commits {
            let content = format!("Version {} - timestamp {}", i, i * 1000);

            let hash = repo
                .commit_builder()
                .message(&format!("Update {}", i))
                .author("testuser")
                .parent(&parent)
                .branch("trunk")
                .file("counter.txt", content.as_bytes())
                .execute()?;
            hashes.push(hash.clone());
            parent = hash;
        }

        // Verify random samples using builder pattern
        for i in [0, 10, 25, 40, 49] {
            let expected = format!("Version {} - timestamp {}", i + 1, (i + 1) * 1000);
            let content = repo
                .files()
                .at_commit(&hashes[i])
                .read_string("counter.txt")?;
            if content != expected {
                return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                    "Version {} mismatch",
                    i + 1
                )));
            }
        }

        // Check history using builder pattern
        let checkins = repo.history().recent(60)?;
        if checkins.len() != num_commits + 1 {
            return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                "Expected {} checkins, got {}",
                num_commits + 1,
                checkins.len()
            )));
        }

        Ok(format!("{} rapid commits verified", num_commits))
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 4: Large files
fn test_large_files(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Large files (1MB, 5MB)".to_string();

    let repo_path = base_dir.join("test_large.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let initial = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        // Create 1MB file
        let one_mb: Vec<u8> = (0..1024 * 1024).map(|i| (i % 256) as u8).collect();

        let hash1 = repo
            .commit_builder()
            .message("Add 1MB file")
            .author("testuser")
            .parent(&initial)
            .branch("trunk")
            .file("large_1mb.bin", &one_mb)
            .execute()?;

        // Verify 1MB file using builder pattern
        let content = repo.files().at_commit(&hash1).read("large_1mb.bin")?;
        if content.len() != one_mb.len() {
            return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                "1MB file size mismatch: {} vs {}",
                content.len(),
                one_mb.len()
            )));
        }
        if content != one_mb {
            return Err(heroforge_core::FossilError::InvalidArtifact(
                "1MB content mismatch".into(),
            ));
        }

        // Create 5MB file
        let five_mb: Vec<u8> = (0..5 * 1024 * 1024)
            .map(|i| ((i * 7) % 256) as u8)
            .collect();
        let hash2 = repo
            .commit_builder()
            .message("Add 5MB file")
            .author("testuser")
            .parent(&hash1)
            .branch("trunk")
            .file("large_5mb.bin", &five_mb)
            .execute()?;

        // Verify 5MB file
        let content = repo.files().at_commit(&hash2).read("large_5mb.bin")?;
        if content.len() != five_mb.len() {
            return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                "5MB file size mismatch: {} vs {}",
                content.len(),
                five_mb.len()
            )));
        }
        if content != five_mb {
            return Err(heroforge_core::FossilError::InvalidArtifact(
                "5MB content mismatch".into(),
            ));
        }

        Ok("1MB and 5MB files verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 5: Binary content
fn test_binary_content(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Binary content (all byte values)".to_string();

    let repo_path = base_dir.join("test_binary.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let initial = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        // Create file with all 256 byte values
        let all_bytes: Vec<u8> = (0..=255).collect();

        // Create file with null bytes and special patterns
        let mut special_binary: Vec<u8> = Vec::new();
        special_binary.extend(&[0x00, 0x00, 0x00]); // null bytes
        special_binary.extend(&[0xFF, 0xFF, 0xFF]); // all ones
        special_binary.extend(&[0x89, 0x50, 0x4E, 0x47]); // PNG header
        special_binary.extend(&[0x1F, 0x8B]); // gzip header
        special_binary.extend(&[0x78, 0x9C]); // zlib header (tricky - same as compression!)
        special_binary.extend(&[0x50, 0x4B, 0x03, 0x04]); // zip header
        for i in 0..1000 {
            special_binary.push((i % 256) as u8);
        }

        let hash = repo
            .commit_builder()
            .message("Add binary files")
            .author("testuser")
            .parent(&initial)
            .branch("trunk")
            .file("all_bytes.bin", &all_bytes)
            .file("special.bin", &special_binary)
            .execute()?;

        // Verify using builder pattern
        let content1 = repo.files().at_commit(&hash).read("all_bytes.bin")?;
        if content1 != all_bytes {
            return Err(heroforge_core::FossilError::InvalidArtifact(
                "all_bytes mismatch".into(),
            ));
        }

        let content2 = repo.files().at_commit(&hash).read("special.bin")?;
        if content2 != special_binary {
            return Err(heroforge_core::FossilError::InvalidArtifact(
                "special.bin mismatch".into(),
            ));
        }

        Ok("Binary content with all byte values verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 6: Special characters in content
fn test_special_characters(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Special characters in content".to_string();

    let repo_path = base_dir.join("test_special.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let initial = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        // Various special content
        let unicode_content =
            "Hello 世界! 🎉 Emoji test: 🚀🔥💯\nCyrillic: Привет\nArabic: مرحبا\n";
        let escape_content = "Backslash: \\ Quote: \" Tab:\tNewline:\nCarriage:\r";
        let whitespace_content = "   leading spaces\ntrailing spaces   \n\t\ttabs\t\t\n";

        let hash = repo
            .commit_builder()
            .message("Add special character files")
            .author("testuser")
            .parent(&initial)
            .branch("trunk")
            .file("unicode.txt", unicode_content.as_bytes())
            .file("escapes.txt", escape_content.as_bytes())
            .file("whitespace.txt", whitespace_content.as_bytes())
            .execute()?;

        // Verify using builder pattern
        let content = repo.files().at_commit(&hash).read("unicode.txt")?;
        if content != unicode_content.as_bytes() {
            return Err(heroforge_core::FossilError::InvalidArtifact(
                "unicode mismatch".into(),
            ));
        }

        let content = repo.files().at_commit(&hash).read("escapes.txt")?;
        if content != escape_content.as_bytes() {
            return Err(heroforge_core::FossilError::InvalidArtifact(
                "escapes mismatch".into(),
            ));
        }

        let content = repo.files().at_commit(&hash).read("whitespace.txt")?;
        if content != whitespace_content.as_bytes() {
            return Err(heroforge_core::FossilError::InvalidArtifact(
                "whitespace mismatch".into(),
            ));
        }

        Ok("Special characters verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 7: Empty files
fn test_empty_files(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Empty files".to_string();

    let repo_path = base_dir.join("test_empty.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let initial = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        let hash = repo
            .commit_builder()
            .message("Add empty files")
            .author("testuser")
            .parent(&initial)
            .branch("trunk")
            .file("empty1.txt", b"")
            .file("empty2.dat", b"")
            .file(".gitkeep", b"")
            .execute()?;

        // Verify empty files using builder pattern
        for name in &["empty1.txt", "empty2.dat", ".gitkeep"] {
            let content = repo.files().at_commit(&hash).read(name)?;
            if !content.is_empty() {
                return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                    "{} should be empty",
                    name
                )));
            }
        }

        Ok("Empty files verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 8: Many files (100+)
fn test_many_files(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Many files (150 files in one commit)".to_string();

    let repo_path = base_dir.join("test_many.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let initial = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        // Create 150 files
        let mut files_data: Vec<(String, Vec<u8>)> = Vec::new();
        for i in 0..150 {
            let name = format!("file_{:03}.txt", i);
            let content = format!("Content of file {}\nWith multiple lines\nLine 3", i);
            files_data.push((name, content.into_bytes()));
        }

        let files: Vec<(&str, &[u8])> = files_data
            .iter()
            .map(|(n, c)| (n.as_str(), c.as_slice()))
            .collect();

        let hash = repo
            .commit_builder()
            .message("Add 150 files")
            .author("testuser")
            .parent(&initial)
            .branch("trunk")
            .files(&files)
            .execute()?;

        // Verify file count using builder pattern
        let all_files = repo.files().at_commit(&hash).list()?;
        if all_files.len() != 150 {
            return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                "Expected 150 files, got {}",
                all_files.len()
            )));
        }

        // Verify random samples
        for i in [0, 50, 100, 149] {
            let name = format!("file_{:03}.txt", i);
            let expected = format!("Content of file {}\nWith multiple lines\nLine 3", i);
            let content = repo.files().at_commit(&hash).read_string(&name)?;
            if content != expected {
                return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                    "Content mismatch for {}",
                    name
                )));
            }
        }

        Ok("150 files committed and verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 9: File modifications across versions
fn test_file_modifications(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "File modifications across versions".to_string();

    let repo_path = base_dir.join("test_mods.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let mut parent = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        let mut versions: HashMap<String, Vec<(String, String)>> = HashMap::new();

        // Version 1: Create initial files
        let v1_files = vec![
            ("config.json", r#"{"version": 1}"#),
            ("data.txt", "Initial data"),
            ("stable.txt", "This file never changes"),
        ];
        let hash1 = repo
            .commit_builder()
            .message("Version 1")
            .author("testuser")
            .parent(&parent)
            .branch("trunk")
            .file("config.json", v1_files[0].1.as_bytes())
            .file("data.txt", v1_files[1].1.as_bytes())
            .file("stable.txt", v1_files[2].1.as_bytes())
            .execute()?;
        versions.insert(
            hash1.clone(),
            v1_files
                .iter()
                .map(|(n, c)| (n.to_string(), c.to_string()))
                .collect(),
        );
        parent = hash1;

        // Version 2: Modify config.json
        let v2_files = vec![
            ("config.json", r#"{"version": 2, "updated": true}"#),
            ("data.txt", "Initial data"),
            ("stable.txt", "This file never changes"),
        ];
        let hash2 = repo
            .commit_builder()
            .message("Version 2 - update config")
            .author("testuser")
            .parent(&parent)
            .branch("trunk")
            .file("config.json", v2_files[0].1.as_bytes())
            .file("data.txt", v2_files[1].1.as_bytes())
            .file("stable.txt", v2_files[2].1.as_bytes())
            .execute()?;
        versions.insert(
            hash2.clone(),
            v2_files
                .iter()
                .map(|(n, c)| (n.to_string(), c.to_string()))
                .collect(),
        );
        parent = hash2;

        // Version 3: Modify data.txt, add new file
        let v3_files = vec![
            ("config.json", r#"{"version": 2, "updated": true}"#),
            ("data.txt", "Modified data content"),
            ("stable.txt", "This file never changes"),
            ("new_file.txt", "Added in version 3"),
        ];
        let hash3 = repo
            .commit_builder()
            .message("Version 3 - modify data, add file")
            .author("testuser")
            .parent(&parent)
            .branch("trunk")
            .file("config.json", v3_files[0].1.as_bytes())
            .file("data.txt", v3_files[1].1.as_bytes())
            .file("stable.txt", v3_files[2].1.as_bytes())
            .file("new_file.txt", v3_files[3].1.as_bytes())
            .execute()?;
        versions.insert(
            hash3.clone(),
            v3_files
                .iter()
                .map(|(n, c)| (n.to_string(), c.to_string()))
                .collect(),
        );

        // Verify each version has correct content using builder pattern
        for (hash, expected_files) in &versions {
            for (name, expected) in expected_files {
                let content = repo.files().at_commit(hash).read_string(name)?;
                if content != *expected {
                    return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                        "Mismatch in {} at {}",
                        name,
                        &hash[..8]
                    )));
                }
            }
        }

        Ok("File modifications across 3 versions verified".into())
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}

/// Test 10: Mixed operations
fn test_mixed_operations(base_dir: &Path) -> TestResult {
    let start = Instant::now();
    let name = "Mixed operations stress test".to_string();

    let repo_path = base_dir.join("test_mixed.forge");

    let result = (|| -> Result<String> {
        let repo = Repository::init(&repo_path)?;
        let mut parent = repo
            .commit_builder()
            .message("initial empty check-in")
            .author("testuser")
            .initial()
            .execute()?;

        let mut all_hashes: Vec<String> = vec![parent.clone()];

        // Do 20 commits with various operations
        for i in 1..=20 {
            let mut files_data: Vec<(String, Vec<u8>)> = Vec::new();

            // Add some consistent files
            files_data.push((
                format!("commit_{}/info.txt", i),
                format!("Commit {}", i).into_bytes(),
            ));

            // Add varying number of files
            for j in 0..(i % 5 + 1) {
                let name = format!("commit_{}/file_{}.dat", i, j);
                let content: Vec<u8> = (0..((i * 100 + j * 10) % 1000))
                    .map(|x| (x % 256) as u8)
                    .collect();
                files_data.push((name, content));
            }

            // Sometimes add deep paths
            if i % 3 == 0 {
                let name = format!("deep/path/level_{}/data.bin", i);
                files_data.push((name, vec![i as u8; 100]));
            }

            let files: Vec<(&str, &[u8])> = files_data
                .iter()
                .map(|(n, c)| (n.as_str(), c.as_slice()))
                .collect();

            let hash = repo
                .commit_builder()
                .message(&format!("Mixed commit {}", i))
                .author("testuser")
                .parent(&parent)
                .branch("trunk")
                .files(&files)
                .execute()?;
            all_hashes.push(hash.clone());
            parent = hash;
        }

        // Verify we can read from all commits using history builder
        let checkins = repo.history().recent(25)?;
        if checkins.len() != 21 {
            // initial + 20 commits
            return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                "Expected 21 checkins, got {}",
                checkins.len()
            )));
        }

        // Verify some random files using files builder
        let files = repo.files().at_commit(&all_hashes[10]).list()?;
        if files.is_empty() {
            return Err(heroforge_core::FossilError::InvalidArtifact(
                "No files in commit 10".into(),
            ));
        }

        // Verify CLI compatibility for last commit - use cat to read a file
        let repo_str = repo_path.to_str().unwrap();
        let last_hash = all_hashes.last().unwrap();
        let cli_content = run_fossil(
            &[
                "cat",
                "commit_20/info.txt",
                "-r",
                &last_hash[..16],
                "-R",
                repo_str,
            ],
            base_dir,
        )
        .map_err(|e| heroforge_core::FossilError::InvalidArtifact(e))?;

        if !cli_content.contains("Commit 20") {
            return Err(heroforge_core::FossilError::InvalidArtifact(format!(
                "CLI content unexpected: {}",
                cli_content
            )));
        }

        Ok(format!(
            "20 mixed commits with {} total checkins verified",
            checkins.len()
        ))
    })();

    TestResult {
        name,
        passed: result.is_ok(),
        details: result.unwrap_or_else(|e| e.to_string()),
        duration_ms: start.elapsed().as_millis(),
    }
}