testwall 1.0.1

Enforce test immutability for agentic TDD workflows
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
use anyhow::{bail, Context, Result};
use chrono::Utc;
use clap::{Parser, Subcommand};
use colored::Colorize;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use walkdir::WalkDir;

// ── Data Model ──────────────────────────────────────────────────────────────

const MANIFEST_DIR: &str = ".testwall";
const MANIFEST_FILE: &str = ".testwall/manifest.json";
const SNAPSHOT_DIR: &str = ".testwall/snapshot";

/// A record of a single test file at snapshot time.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct FileRecord {
    /// Path relative to the project root.
    relative_path: String,
    /// SHA-256 hex digest of the file contents.
    sha256: String,
    /// File size in bytes.
    size: u64,
}

/// The manifest stored in `.testwall/manifest.json`.
#[derive(Debug, Serialize, Deserialize)]
struct Manifest {
    /// Testwall version that created this manifest.
    version: String,
    /// ISO-8601 timestamp of when `init` was run.
    created_at: String,
    /// Glob patterns used to discover test files.
    patterns: Vec<String>,
    /// The test runner command (e.g. "pytest", "cargo test").
    test_command: Option<String>,
    /// Per-file checksums.
    files: BTreeMap<String, FileRecord>,
}

// ── CLI Definition ──────────────────────────────────────────────────────────

#[derive(Parser)]
#[command(
    name = "testwall",
    version,
    about = "Enforce test immutability for agentic TDD workflows",
    long_about = "testwall prevents implementing agents from cheating test gates by \
                  snapshotting test files, locking them read-only, and verifying \
                  integrity before accepting implementation results."
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Snapshot test files and record their checksums.
    Init {
        /// Glob patterns for test files (can be repeated).
        /// Defaults to common conventions if omitted.
        #[arg(short, long)]
        pattern: Vec<String>,

        /// The command used to run tests (e.g. "pytest", "cargo test").
        #[arg(short = 'c', long = "cmd")]
        test_command: Option<String>,
    },

    /// Set snapshotted test files to read-only in the working tree.
    Lock,

    /// Restore write permissions on test files.
    Unlock,

    /// Run the test suite using the immutable snapshot copies.
    Run {
        /// Override the test command from the manifest.
        #[arg(short = 'c', long = "cmd")]
        test_command: Option<String>,

        /// Extra arguments forwarded to the test runner.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Verify that test files have not been modified since init.
    Verify {
        /// Exit with code 0 even on failure (just print the report).
        #[arg(long)]
        report_only: bool,
    },

    /// Accept implementation results (verify + unlock + clean up snapshot).
    Accept,

    /// Show the current manifest and status.
    Status,
}

// ── Helpers ─────────────────────────────────────────────────────────────────

fn project_root() -> Result<PathBuf> {
    // Walk up from cwd looking for .testwall/ or .git/
    let mut dir = std::env::current_dir()?;
    loop {
        if dir.join(MANIFEST_DIR).exists() || dir.join(".git").exists() {
            return Ok(dir);
        }
        if !dir.pop() {
            bail!("Could not find project root (no .git or .testwall directory found)");
        }
    }
}

fn sha256_file(path: &Path) -> Result<String> {
    let bytes = fs::read(path).with_context(|| format!("reading {}", path.display()))?;
    let mut hasher = Sha256::new();
    hasher.update(&bytes);
    Ok(format!("{:x}", hasher.finalize()))
}

fn load_manifest(root: &Path) -> Result<Manifest> {
    let path = root.join(MANIFEST_FILE);
    let data = fs::read_to_string(&path)
        .with_context(|| format!("Could not read manifest at {}", path.display()))?;
    let manifest: Manifest =
        serde_json::from_str(&data).context("Failed to parse manifest JSON")?;
    Ok(manifest)
}

fn save_manifest(root: &Path, manifest: &Manifest) -> Result<()> {
    let path = root.join(MANIFEST_FILE);
    let json = serde_json::to_string_pretty(manifest)?;
    fs::write(&path, json)?;
    Ok(())
}

/// Default test file patterns for common ecosystems.
fn default_patterns() -> Vec<String> {
    vec![
        // Python
        "test_*.py".into(),
        "*_test.py".into(),
        "tests/**/*.py".into(),
        "conftest.py".into(),
        // Rust
        "tests/**/*.rs".into(),
        // JavaScript / TypeScript
        "**/*.test.js".into(),
        "**/*.test.ts".into(),
        "**/*.test.tsx".into(),
        "**/*.spec.js".into(),
        "**/*.spec.ts".into(),
        "**/*.spec.tsx".into(),
        // Go
        "**/*_test.go".into(),
        // Java / Kotlin
        "src/test/**/*.java".into(),
        "src/test/**/*.kt".into(),
        // Config files that affect test behavior
        "pytest.ini".into(),
        "setup.cfg".into(),
        "jest.config.*".into(),
        "vitest.config.*".into(),
        ".cargo/config.toml".into(),
    ]
}

/// Collect test files matching the given glob patterns under `root`.
fn collect_test_files(root: &Path, patterns: &[String]) -> Result<BTreeMap<String, FileRecord>> {
    let mut files = BTreeMap::new();

    for entry in WalkDir::new(root)
        .into_iter()
        .filter_entry(|e| {
            let name = e.file_name().to_string_lossy();
            // Skip hidden dirs, node_modules, target, __pycache__, .testwall
            if e.file_type().is_dir() {
                return !name.starts_with('.')
                    && name != "node_modules"
                    && name != "target"
                    && name != "__pycache__"
                    && name != ".testwall";
            }
            true
        })
        .filter_map(|e| e.ok())
    {
        if !entry.file_type().is_file() {
            continue;
        }

        let path = entry.path();
        let rel = path
            .strip_prefix(root)
            .unwrap_or(path)
            .to_string_lossy()
            .to_string();

        // Check if this file matches any pattern
        for pattern in patterns {
            if glob_match(&rel, pattern) {
                let hash = sha256_file(path)?;
                let meta = fs::metadata(path)?;
                files.insert(
                    rel.clone(),
                    FileRecord {
                        relative_path: rel.clone(),
                        sha256: hash,
                        size: meta.len(),
                    },
                );
                break;
            }
        }
    }

    Ok(files)
}

/// Simple glob matching — supports `*`, `**`, and `?`.
fn glob_match(path: &str, pattern: &str) -> bool {
    // Handle ** prefix patterns like "tests/**/*.py"
    if let Some(rest) = pattern.strip_prefix("**/") {
        // Match at any directory depth
        let parts: Vec<&str> = path.split('/').collect();
        for i in 0..parts.len() {
            let suffix = parts[i..].join("/");
            if simple_glob(&suffix, rest) {
                return true;
            }
        }
        return false;
    }

    // Handle patterns with ** in the middle like "tests/**/*.rs"
    if pattern.contains("/**/") {
        let parts: Vec<&str> = pattern.splitn(2, "/**/").collect();
        if parts.len() == 2 {
            let prefix = parts[0];
            let suffix = parts[1];
            // Path must start with prefix
            if let Some(rest) = path.strip_prefix(prefix) {
                let rest = rest.strip_prefix('/').unwrap_or(rest);
                // And some suffix of the remaining path must match
                let path_parts: Vec<&str> = rest.split('/').collect();
                for i in 0..path_parts.len() {
                    let candidate = path_parts[i..].join("/");
                    if simple_glob(&candidate, suffix) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

    simple_glob(path, pattern)
}

/// Match a single path segment against a simple glob (no **).
fn simple_glob(text: &str, pattern: &str) -> bool {
    let text = text.as_bytes();
    let pattern = pattern.as_bytes();
    let (mut ti, mut pi) = (0, 0);
    let (mut star_p, mut star_t) = (usize::MAX, 0);

    while ti < text.len() {
        if pi < pattern.len() && (pattern[pi] == b'?' || pattern[pi] == text[ti]) {
            ti += 1;
            pi += 1;
        } else if pi < pattern.len() && pattern[pi] == b'*' {
            star_p = pi;
            star_t = ti;
            pi += 1;
        } else if star_p != usize::MAX {
            pi = star_p + 1;
            star_t += 1;
            ti = star_t;
        } else {
            return false;
        }
    }

    while pi < pattern.len() && pattern[pi] == b'*' {
        pi += 1;
    }

    pi == pattern.len()
}

fn set_readonly(path: &Path, readonly: bool) -> Result<()> {
    let meta = fs::metadata(path)?;
    let mut perms = meta.permissions();
    if readonly {
        // Remove write bits: keep read + execute
        let mode = perms.mode() & !0o222;
        perms.set_mode(mode);
    } else {
        // Restore owner write bit
        let mode = perms.mode() | 0o200;
        perms.set_mode(mode);
    }
    fs::set_permissions(path, perms)?;
    Ok(())
}

// ── Subcommand Implementations ──────────────────────────────────────────────

fn cmd_init(patterns: Vec<String>, test_command: Option<String>) -> Result<()> {
    let root = project_root()?;
    let patterns = if patterns.is_empty() {
        default_patterns()
    } else {
        patterns
    };

    println!(
        "{} Scanning for test files...",
        "testwall".bold().cyan()
    );

    let files = collect_test_files(&root, &patterns)?;

    if files.is_empty() {
        println!(
            "{} No test files found matching patterns:",
            "warning:".bold().yellow()
        );
        for p in &patterns {
            println!("  - {}", p);
        }
        println!("\nUse {} to specify custom patterns.", "--pattern".bold());
        return Ok(());
    }

    // Create .testwall directory and snapshot
    let _manifest_dir = root.join(MANIFEST_DIR);
    let snapshot_dir = root.join(SNAPSHOT_DIR);
    fs::create_dir_all(&snapshot_dir)?;

    // Copy test files to snapshot
    for (rel_path, _record) in &files {
        let src = root.join(rel_path);
        let dst = snapshot_dir.join(rel_path);
        if let Some(parent) = dst.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::copy(&src, &dst)?;
    }

    let manifest = Manifest {
        version: env!("CARGO_PKG_VERSION").to_string(),
        created_at: Utc::now().to_rfc3339(),
        patterns,
        test_command,
        files,
    };

    save_manifest(&root, &manifest)?;

    // Add .testwall/snapshot to .gitignore if not already there
    let gitignore_path = root.join(".gitignore");
    let gitignore = fs::read_to_string(&gitignore_path).unwrap_or_default();
    if !gitignore.contains(".testwall/") {
        let mut content = gitignore;
        if !content.ends_with('\n') && !content.is_empty() {
            content.push('\n');
        }
        content.push_str("\n# testwall snapshot (do not commit)\n.testwall/snapshot/\n");
        fs::write(&gitignore_path, content)?;
    }

    let file_count = manifest.files.len();
    println!(
        "\n{} Initialized testwall with {} test file{}.",
        "done:".bold().green(),
        file_count.to_string().bold(),
        if file_count == 1 { "" } else { "s" }
    );
    println!(
        "  Manifest: {}",
        root.join(MANIFEST_FILE).display().to_string().dimmed()
    );
    println!(
        "  Snapshot: {}",
        root.join(SNAPSHOT_DIR).display().to_string().dimmed()
    );
    println!(
        "\nRun {} to make test files read-only.",
        "testwall lock".bold()
    );

    Ok(())
}

fn cmd_lock() -> Result<()> {
    let root = project_root()?;
    let manifest = load_manifest(&root)?;

    let mut locked = 0;
    for (rel_path, _) in &manifest.files {
        let path = root.join(rel_path);
        if path.exists() {
            set_readonly(&path, true)?;
            locked += 1;
        }
    }

    println!(
        "{} Locked {} test file{} (read-only).",
        "testwall".bold().cyan(),
        locked.to_string().bold(),
        if locked == 1 { "" } else { "s" }
    );
    println!(
        "  The implementing agent can {} but not {} these files.",
        "read".green().bold(),
        "modify".red().bold()
    );

    Ok(())
}

fn cmd_unlock() -> Result<()> {
    let root = project_root()?;
    let manifest = load_manifest(&root)?;

    let mut unlocked = 0;
    for (rel_path, _) in &manifest.files {
        let path = root.join(rel_path);
        if path.exists() {
            set_readonly(&path, false)?;
            unlocked += 1;
        }
    }

    println!(
        "{} Unlocked {} test file{} (write restored).",
        "testwall".bold().cyan(),
        unlocked.to_string().bold(),
        if unlocked == 1 { "" } else { "s" }
    );

    Ok(())
}

fn cmd_run(test_command: Option<String>, extra_args: Vec<String>) -> Result<()> {
    let root = project_root()?;
    let manifest = load_manifest(&root)?;
    let snapshot_dir = root.join(SNAPSHOT_DIR);

    // Determine the test command
    let cmd_str = test_command
        .or(manifest.test_command.clone())
        .unwrap_or_else(|| {
            // Auto-detect from project files
            if root.join("Cargo.toml").exists() {
                "cargo test".into()
            } else if root.join("pyproject.toml").exists() || root.join("pytest.ini").exists() {
                "pytest".into()
            } else if root.join("package.json").exists() {
                "npm test".into()
            } else if root.join("go.mod").exists() {
                "go test ./...".into()
            } else {
                "make test".into()
            }
        });

    // First, verify the snapshot is intact
    println!(
        "{} Verifying snapshot integrity...",
        "testwall".bold().cyan()
    );
    for (rel_path, record) in &manifest.files {
        let snap_path = snapshot_dir.join(rel_path);
        if !snap_path.exists() {
            bail!(
                "Snapshot file missing: {}. Run `testwall init` again.",
                rel_path
            );
        }
        let current_hash = sha256_file(&snap_path)?;
        if current_hash != record.sha256 {
            bail!(
                "Snapshot tampered: {} has been modified. Run `testwall init` again.",
                rel_path
            );
        }
    }

    // Restore test files from snapshot before running
    // (in case the agent modified the working copies)
    println!(
        "{} Restoring test files from snapshot...",
        "testwall".bold().cyan()
    );
    for (rel_path, _) in &manifest.files {
        let snap_path = snapshot_dir.join(rel_path);
        let work_path = root.join(rel_path);
        if let Some(parent) = work_path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::copy(&snap_path, &work_path)?;
        set_readonly(&work_path, true)?;
    }

    // Run the test command
    println!(
        "{} Running: {} {}",
        "testwall".bold().cyan(),
        cmd_str.bold(),
        extra_args.join(" ")
    );
    println!();

    let parts: Vec<&str> = cmd_str.split_whitespace().collect();
    let (program, cmd_args) = parts.split_first().context("Empty test command")?;

    let mut all_args: Vec<&str> = cmd_args.to_vec();
    let extra_refs: Vec<&str> = extra_args.iter().map(|s| s.as_str()).collect();
    all_args.extend(extra_refs);

    let status = Command::new(program)
        .args(&all_args)
        .current_dir(&root)
        .status()
        .with_context(|| format!("Failed to execute: {}", cmd_str))?;

    println!();
    if status.success() {
        println!("{} Tests passed.", "PASS".bold().green());
    } else {
        println!(
            "{} Tests failed (exit code: {}).",
            "FAIL".bold().red(),
            status.code().unwrap_or(-1)
        );
    }

    std::process::exit(status.code().unwrap_or(1));
}

fn cmd_verify(report_only: bool) -> Result<()> {
    let root = project_root()?;
    let manifest = load_manifest(&root)?;

    println!(
        "{} Verifying test file integrity...\n",
        "testwall".bold().cyan()
    );

    let mut clean = 0;
    let mut modified = Vec::new();
    let mut missing = Vec::new();

    for (rel_path, record) in &manifest.files {
        let path = root.join(rel_path);
        if !path.exists() {
            missing.push(rel_path.clone());
            continue;
        }

        let current_hash = sha256_file(&path)?;
        if current_hash == record.sha256 {
            clean += 1;
            println!("  {} {}", "ok".green(), rel_path);
        } else {
            modified.push(rel_path.clone());
            println!(
                "  {} {} (checksum mismatch)",
                "MODIFIED".red().bold(),
                rel_path
            );
        }
    }

    for path in &missing {
        println!("  {} {} (file missing)", "MISSING".red().bold(), path);
    }

    println!();

    let tampered = !modified.is_empty() || !missing.is_empty();
    if tampered {
        println!(
            "{} Test integrity check FAILED.",
            "FAIL".bold().red()
        );
        println!(
            "  {} modified, {} missing, {} clean",
            modified.len().to_string().red().bold(),
            missing.len().to_string().red().bold(),
            clean.to_string().green()
        );
        println!(
            "\n  The implementing agent appears to have tampered with test files."
        );
        println!(
            "  Run {} to restore from snapshot.",
            "testwall run".bold()
        );

        if !report_only {
            std::process::exit(1);
        }
    } else {
        println!(
            "{} All {} test file{} verified.",
            "PASS".bold().green(),
            clean.to_string().bold(),
            if clean == 1 { "" } else { "s" }
        );
    }

    Ok(())
}

fn cmd_accept() -> Result<()> {
    let root = project_root()?;

    // First, verify
    println!(
        "{} Running verification before accepting...\n",
        "testwall".bold().cyan()
    );

    let manifest = load_manifest(&root)?;
    let mut tampered = false;

    for (rel_path, record) in &manifest.files {
        let path = root.join(rel_path);
        if !path.exists() {
            println!("  {} {} (missing)", "FAIL".red().bold(), rel_path);
            tampered = true;
            continue;
        }
        let current_hash = sha256_file(&path)?;
        if current_hash != record.sha256 {
            println!("  {} {} (modified)", "FAIL".red().bold(), rel_path);
            tampered = true;
        } else {
            println!("  {} {}", "ok".green(), rel_path);
        }
    }

    if tampered {
        println!(
            "\n{} Cannot accept: test files were tampered with.",
            "REJECTED".bold().red()
        );
        println!(
            "  Restore originals with {} and re-run the implementation.",
            "testwall run".bold()
        );
        std::process::exit(1);
    }

    // Unlock files
    for (rel_path, _) in &manifest.files {
        let path = root.join(rel_path);
        if path.exists() {
            set_readonly(&path, false)?;
        }
    }

    // Clean up snapshot (keep manifest for audit trail)
    let snapshot_dir = root.join(SNAPSHOT_DIR);
    if snapshot_dir.exists() {
        fs::remove_dir_all(&snapshot_dir)?;
    }

    println!(
        "\n{} Implementation accepted. Test files unlocked, snapshot cleaned up.",
        "ACCEPTED".bold().green()
    );
    println!(
        "  Manifest retained at {} for audit trail.",
        root.join(MANIFEST_FILE).display().to_string().dimmed()
    );

    Ok(())
}

fn cmd_status() -> Result<()> {
    let root = project_root()?;
    let manifest_path = root.join(MANIFEST_FILE);

    if !manifest_path.exists() {
        println!(
            "{} No testwall session found. Run {} to start.",
            "testwall".bold().cyan(),
            "testwall init".bold()
        );
        return Ok(());
    }

    let manifest = load_manifest(&root)?;

    println!("{}", "testwall status".bold().cyan());
    println!("  Version:    {}", manifest.version);
    println!("  Created:    {}", manifest.created_at);
    println!(
        "  Test cmd:   {}",
        manifest
            .test_command
            .as_deref()
            .unwrap_or("(auto-detect)")
    );
    println!("  Patterns:   {}", manifest.patterns.join(", "));
    println!("  Files:      {}", manifest.files.len());

    // Check lock status
    let mut locked = 0;
    let mut unlocked = 0;
    let mut missing = 0;
    for (rel_path, _) in &manifest.files {
        let path = root.join(rel_path);
        if !path.exists() {
            missing += 1;
        } else {
            let meta = fs::metadata(&path)?;
            if meta.permissions().mode() & 0o222 == 0 {
                locked += 1;
            } else {
                unlocked += 1;
            }
        }
    }

    println!(
        "  Lock state: {} locked, {} unlocked, {} missing",
        locked.to_string().green(),
        unlocked.to_string().yellow(),
        missing.to_string().red()
    );

    // Check snapshot
    let snapshot_dir = root.join(SNAPSHOT_DIR);
    if snapshot_dir.exists() {
        println!("  Snapshot:   {}", "present".green());
    } else {
        println!("  Snapshot:   {}", "missing (already accepted?)".yellow());
    }

    Ok(())
}

// ── Main ────────────────────────────────────────────────────────────────────

fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Init {
            pattern,
            test_command,
        } => cmd_init(pattern, test_command),
        Commands::Lock => cmd_lock(),
        Commands::Unlock => cmd_unlock(),
        Commands::Run {
            test_command,
            args,
        } => cmd_run(test_command, args),
        Commands::Verify { report_only } => cmd_verify(report_only),
        Commands::Accept => cmd_accept(),
        Commands::Status => cmd_status(),
    }
}

// ── Tests ───────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_sha256_consistency() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "hello world").unwrap();

        let hash1 = sha256_file(&file).unwrap();
        let hash2 = sha256_file(&file).unwrap();
        assert_eq!(hash1, hash2);

        // Known SHA-256 of "hello world"
        assert_eq!(
            hash1,
            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
        );
    }

    #[test]
    fn test_glob_simple() {
        assert!(glob_match("test_foo.py", "test_*.py"));
        assert!(glob_match("bar_test.py", "*_test.py"));
        assert!(!glob_match("foo.py", "test_*.py"));
        assert!(!glob_match("test_foo.rs", "test_*.py"));
    }

    #[test]
    fn test_glob_double_star_prefix() {
        assert!(glob_match("src/components/Button.test.tsx", "**/*.test.tsx"));
        assert!(glob_match("Button.test.tsx", "**/*.test.tsx"));
        assert!(!glob_match("Button.tsx", "**/*.test.tsx"));
    }

    #[test]
    fn test_glob_double_star_middle() {
        assert!(glob_match("tests/unit/test_core.rs", "tests/**/*.rs"));
        assert!(glob_match("tests/test_core.rs", "tests/**/*.rs"));
        assert!(!glob_match("src/core.rs", "tests/**/*.rs"));
    }

    #[test]
    fn test_set_readonly() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "content").unwrap();

        set_readonly(&file, true).unwrap();
        let meta = fs::metadata(&file).unwrap();
        assert_eq!(meta.permissions().mode() & 0o222, 0);

        set_readonly(&file, false).unwrap();
        let meta = fs::metadata(&file).unwrap();
        assert_ne!(meta.permissions().mode() & 0o200, 0);
    }
}