homeboy 0.74.0

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

use regex::Regex;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::error::{Error, Result};
use crate::git;

// ============================================================================
// Models
// ============================================================================

/// A production change that may cause test drift.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProductionChange {
    /// Type of change detected.
    pub change_type: ChangeType,
    /// Production file where the change occurred.
    pub file: String,
    /// The old symbol/value (removed/changed from).
    pub old_symbol: String,
    /// The new symbol/value (added/changed to), if applicable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_symbol: Option<String>,
    /// Line number in the diff (approximate).
    #[serde(default)]
    pub line: usize,
}

/// Type of production change detected from git diff.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ChangeType {
    /// Method/function was renamed.
    MethodRename,
    /// Method/function was removed entirely.
    MethodRemoved,
    /// Class/trait was renamed.
    ClassRename,
    /// Class/trait was removed entirely.
    ClassRemoved,
    /// Error code string changed.
    ErrorCodeChange,
    /// Return type annotation changed.
    ReturnTypeChange,
    /// Method signature changed (different parameters).
    SignatureChange,
    /// File was moved/renamed.
    FileMove,
    /// String constant changed.
    StringChange,
}

/// A test file that references a changed symbol.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DriftedTest {
    /// Test file path.
    pub test_file: String,
    /// Line number where the old symbol is referenced.
    pub line: usize,
    /// The line content.
    pub content: String,
    /// Reference to the production change that caused the drift.
    pub change_index: usize,
}

/// Full drift report.
#[derive(Debug, Clone, Serialize)]
pub struct DriftReport {
    /// Component name.
    pub component: String,
    /// Git ref used as baseline (tag, commit, branch).
    pub since: String,
    /// Production changes detected.
    pub production_changes: Vec<ProductionChange>,
    /// Tests that reference changed symbols.
    pub drifted_tests: Vec<DriftedTest>,
    /// Total unique test files affected.
    pub total_drifted_files: usize,
    /// Total drift references found.
    pub total_drift_references: usize,
    /// Changes that could be auto-fixed with refactor transform.
    pub auto_fixable: usize,
}

// ============================================================================
// Git diff parsing
// ============================================================================

/// Options for drift detection.
pub struct DriftOptions<'a> {
    /// Component root directory.
    pub root: &'a Path,
    /// Git ref to compare against (tag, commit, branch).
    pub since: &'a str,
    /// Glob patterns for production files (non-test).
    pub source_patterns: Vec<String>,
    /// Glob patterns for test files.
    pub test_patterns: Vec<String>,
}

impl<'a> DriftOptions<'a> {
    /// Create options with common defaults for a PHP project.
    pub fn php(root: &'a Path, since: &'a str) -> Self {
        Self {
            root,
            since,
            source_patterns: vec![
                "src/**/*.php".into(),
                "inc/**/*.php".into(),
                "lib/**/*.php".into(),
            ],
            test_patterns: vec!["tests/**/*.php".into()],
        }
    }

    /// Create options with common defaults for a Rust project.
    pub fn rust(root: &'a Path, since: &'a str) -> Self {
        Self {
            root,
            since,
            source_patterns: vec!["src/**/*.rs".into()],
            test_patterns: vec!["tests/**/*.rs".into()],
        }
    }
}

/// Detect test drift by cross-referencing git changes with test files.
pub fn detect_drift(component: &str, opts: &DriftOptions) -> Result<DriftReport> {
    // Step 1: Get changed production files from git diff
    let changed_files = get_changed_files(opts.root, opts.since)?;

    // Filter to production files only (exclude tests)
    let prod_files: Vec<&str> = changed_files
        .iter()
        .filter(|f| !is_test_file(f))
        .map(|s| s.as_str())
        .collect();

    if prod_files.is_empty() {
        return Ok(DriftReport {
            component: component.to_string(),
            since: opts.since.to_string(),
            production_changes: Vec::new(),
            drifted_tests: Vec::new(),
            total_drifted_files: 0,
            total_drift_references: 0,
            auto_fixable: 0,
        });
    }

    // Step 2: Parse diffs to extract structural changes
    let mut changes = Vec::new();
    for file in &prod_files {
        let diff = get_file_diff(opts.root, opts.since, file)?;
        let file_changes = extract_changes_from_diff(file, &diff);
        changes.extend(file_changes);
    }

    // Also detect file renames
    let renames = get_renamed_files(opts.root, opts.since)?;
    for (old, new) in &renames {
        if !is_test_file(old) {
            changes.push(ProductionChange {
                change_type: ChangeType::FileMove,
                file: new.clone(),
                old_symbol: old.clone(),
                new_symbol: Some(new.clone()),
                line: 0,
            });
        }
    }

    // Step 3: Scan test files for references to changed symbols
    let test_files = collect_test_files(opts.root);
    let drifted = find_drift_references(&changes, &test_files, opts.root);

    // Step 4: Build report
    let total_drifted_files = {
        let unique: std::collections::HashSet<&str> =
            drifted.iter().map(|d| d.test_file.as_str()).collect();
        unique.len()
    };
    let total_drift_references = drifted.len();

    let auto_fixable = changes.iter().filter(|c| is_auto_fixable(c)).count();

    Ok(DriftReport {
        component: component.to_string(),
        since: opts.since.to_string(),
        production_changes: changes,
        drifted_tests: drifted,
        total_drifted_files,
        total_drift_references,
        auto_fixable,
    })
}

// ============================================================================
// Git operations
// ============================================================================

/// Get list of changed files between `since` ref and HEAD.
/// Delegates to the core `git::changes::get_files_changed_since` primitive.
fn get_changed_files(root: &Path, since: &str) -> Result<Vec<String>> {
    let root_str = root.to_string_lossy();
    git::get_files_changed_since(&root_str, since)
}

/// Get diff for a specific file.
fn get_file_diff(root: &Path, since: &str, file: &str) -> Result<String> {
    let output = Command::new("git")
        .args(["diff", since, "HEAD", "--", file])
        .current_dir(root)
        .output()
        .map_err(|e| {
            Error::internal_io(
                format!("Failed to run git diff for {}: {}", file, e),
                Some("test_drift.git".to_string()),
            )
        })?;

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

/// Get renamed files from git diff.
fn get_renamed_files(root: &Path, since: &str) -> Result<Vec<(String, String)>> {
    let output = Command::new("git")
        .args(["diff", "--diff-filter=R", "--name-status", since, "HEAD"])
        .current_dir(root)
        .output()
        .map_err(|e| {
            Error::internal_io(
                format!("Failed to get renamed files: {}", e),
                Some("test_drift.git".to_string()),
            )
        })?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut renames = Vec::new();

    for line in stdout.lines() {
        let parts: Vec<&str> = line.split('\t').collect();
        if parts.len() >= 3 && parts[0].starts_with('R') {
            renames.push((parts[1].to_string(), parts[2].to_string()));
        }
    }

    Ok(renames)
}

// ============================================================================
// Diff parsing — extract structural changes
// ============================================================================

/// Extract production changes from a unified diff.
fn extract_changes_from_diff(file: &str, diff: &str) -> Vec<ProductionChange> {
    let mut changes = Vec::new();

    // Track removed and added method definitions
    let mut removed_methods: Vec<(String, usize)> = Vec::new();
    let mut added_methods: Vec<(String, usize)> = Vec::new();

    // Track removed and added class/trait definitions
    let mut removed_classes: Vec<(String, usize)> = Vec::new();
    let mut added_classes: Vec<(String, usize)> = Vec::new();

    // Track removed and added string literals (for error codes, etc.)
    let mut removed_strings: Vec<(String, usize)> = Vec::new();
    let mut added_strings: Vec<(String, usize)> = Vec::new();

    // PHP patterns
    let method_re = Regex::new(
        r"(?:public|protected|private|static|abstract|final)\s+(?:static\s+)?function\s+(\w+)",
    )
    .unwrap();
    let class_re = Regex::new(r"(?:abstract\s+)?(?:class|trait|interface)\s+(\w+)").unwrap();
    let string_re = Regex::new(r#"'([a-z_]{3,50})'"#).unwrap();

    // Rust patterns
    let rust_fn_re = Regex::new(r"(?:pub(?:\(crate\))?\s+)?(?:async\s+)?fn\s+(\w+)").unwrap();
    let rust_struct_re =
        Regex::new(r"(?:pub(?:\(crate\))?\s+)?(?:struct|enum|trait)\s+(\w+)").unwrap();

    let is_rust = file.ends_with(".rs");
    let fn_re = if is_rust { &rust_fn_re } else { &method_re };
    let cls_re = if is_rust { &rust_struct_re } else { &class_re };
    let hunk_re = Regex::new(r"@@ -\d+(?:,\d+)? \+(\d+)").unwrap();

    let mut line_num: usize = 0;

    for line in diff.lines() {
        // Track line numbers from hunk headers
        if line.starts_with("@@") {
            if let Some(cap) = hunk_re.captures(line) {
                line_num = cap[1].parse().unwrap_or(0);
            }
            continue;
        }

        if line.starts_with('-') && !line.starts_with("---") {
            let content = &line[1..];

            // Check for removed method definitions
            if let Some(cap) = fn_re.captures(content) {
                removed_methods.push((cap[1].to_string(), line_num));
            }

            // Check for removed class definitions
            if let Some(cap) = cls_re.captures(content) {
                removed_classes.push((cap[1].to_string(), line_num));
            }

            // Check for removed string constants (error codes, etc.)
            for cap in string_re.captures_iter(content) {
                removed_strings.push((cap[1].to_string(), line_num));
            }
        } else if line.starts_with('+') && !line.starts_with("+++") {
            let content = &line[1..];

            // Check for added method definitions
            if let Some(cap) = fn_re.captures(content) {
                added_methods.push((cap[1].to_string(), line_num));
            }

            // Check for added class definitions
            if let Some(cap) = cls_re.captures(content) {
                added_classes.push((cap[1].to_string(), line_num));
            }

            // Check for added string constants
            for cap in string_re.captures_iter(content) {
                added_strings.push((cap[1].to_string(), line_num));
            }

            line_num += 1;
        } else if !line.starts_with('\\') {
            line_num += 1;
        }
    }

    // Match removed methods to added methods (renames)
    let mut matched_removed: Vec<bool> = vec![false; removed_methods.len()];
    let mut matched_added: Vec<bool> = vec![false; added_methods.len()];

    for (ri, (removed, rline)) in removed_methods.iter().enumerate() {
        // Look for a close-by addition (same hunk, ≤10 lines apart)
        for (ai, (added, aline)) in added_methods.iter().enumerate() {
            if !matched_added[ai] && removed != added {
                let dist = (*aline as isize - *rline as isize).unsigned_abs();
                if dist <= 10 {
                    changes.push(ProductionChange {
                        change_type: ChangeType::MethodRename,
                        file: file.to_string(),
                        old_symbol: removed.clone(),
                        new_symbol: Some(added.clone()),
                        line: *rline,
                    });
                    matched_removed[ri] = true;
                    matched_added[ai] = true;
                    break;
                }
            }
        }
    }

    // Unmatched removals are pure removals
    for (ri, (removed, rline)) in removed_methods.iter().enumerate() {
        if !matched_removed[ri] {
            changes.push(ProductionChange {
                change_type: ChangeType::MethodRemoved,
                file: file.to_string(),
                old_symbol: removed.clone(),
                new_symbol: None,
                line: *rline,
            });
        }
    }

    // Match removed classes to added classes (renames)
    let mut cls_matched_removed: Vec<bool> = vec![false; removed_classes.len()];
    let mut cls_matched_added: Vec<bool> = vec![false; added_classes.len()];

    for (ri, (removed, rline)) in removed_classes.iter().enumerate() {
        for (ai, (added, aline)) in added_classes.iter().enumerate() {
            if !cls_matched_added[ai] && removed != added {
                let dist = (*aline as isize - *rline as isize).unsigned_abs();
                if dist <= 15 {
                    changes.push(ProductionChange {
                        change_type: ChangeType::ClassRename,
                        file: file.to_string(),
                        old_symbol: removed.clone(),
                        new_symbol: Some(added.clone()),
                        line: *rline,
                    });
                    cls_matched_removed[ri] = true;
                    cls_matched_added[ai] = true;
                    break;
                }
            }
        }
    }

    for (ri, (removed, rline)) in removed_classes.iter().enumerate() {
        if !cls_matched_removed[ri] {
            changes.push(ProductionChange {
                change_type: ChangeType::ClassRemoved,
                file: file.to_string(),
                old_symbol: removed.clone(),
                new_symbol: None,
                line: *rline,
            });
        }
    }

    // Match removed strings to added strings (error code changes, etc.)
    let mut str_matched_removed: Vec<bool> = vec![false; removed_strings.len()];

    for (ri, (removed, rline)) in removed_strings.iter().enumerate() {
        for (added, aline) in &added_strings {
            if removed != added {
                let dist = (*aline as isize - *rline as isize).unsigned_abs();
                if dist <= 5 {
                    changes.push(ProductionChange {
                        change_type: ChangeType::ErrorCodeChange,
                        file: file.to_string(),
                        old_symbol: removed.clone(),
                        new_symbol: Some(added.clone()),
                        line: *rline,
                    });
                    str_matched_removed[ri] = true;
                    break;
                }
            }
        }
    }

    changes
}

// ============================================================================
// Test file scanning
// ============================================================================

/// Check if a file path looks like a test file.
fn is_test_file(path: &str) -> bool {
    path.contains("/tests/") || path.contains("Test.php") || path.contains("_test.rs")
}

/// Collect all test files in the repo.
fn collect_test_files(root: &Path) -> Vec<PathBuf> {
    let tests_dir = root.join("tests");
    if !tests_dir.exists() {
        return Vec::new();
    }

    let mut files = Vec::new();
    collect_files_recursive(&tests_dir, &mut files);
    files
}

fn collect_files_recursive(dir: &Path, files: &mut Vec<PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };

    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            let name = path.file_name().unwrap_or_default().to_string_lossy();
            if name == ".git" || name == "node_modules" || name == "vendor" {
                continue;
            }
            collect_files_recursive(&path, files);
        } else if path.is_file() {
            files.push(path);
        }
    }
}

/// Scan test files for references to changed production symbols.
fn find_drift_references(
    changes: &[ProductionChange],
    test_files: &[PathBuf],
    root: &Path,
) -> Vec<DriftedTest> {
    let mut drifted = Vec::new();

    for (ci, change) in changes.iter().enumerate() {
        // Skip changes with very short symbols (likely false positives)
        if change.old_symbol.len() < 3 {
            continue;
        }

        // Build search pattern for the old symbol
        let search = &change.old_symbol;

        for test_file in test_files {
            let Ok(content) = std::fs::read_to_string(test_file) else {
                continue;
            };

            let relative = test_file
                .strip_prefix(root)
                .unwrap_or(test_file)
                .to_string_lossy()
                .to_string();

            for (i, line) in content.lines().enumerate() {
                if line.contains(search) {
                    // Skip if it's a comment-only line
                    let trimmed = line.trim();
                    if trimmed.starts_with("//")
                        || trimmed.starts_with('#')
                        || trimmed.starts_with('*')
                        || trimmed.starts_with("/*")
                    {
                        continue;
                    }

                    drifted.push(DriftedTest {
                        test_file: relative.clone(),
                        line: i + 1,
                        content: line.trim().to_string(),
                        change_index: ci,
                    });
                }
            }
        }
    }

    drifted
}

/// Check if a change type is auto-fixable with refactor transform.
fn is_auto_fixable(change: &ProductionChange) -> bool {
    match change.change_type {
        ChangeType::MethodRename => change.new_symbol.is_some(),
        ChangeType::ClassRename => change.new_symbol.is_some(),
        ChangeType::ErrorCodeChange => change.new_symbol.is_some(),
        ChangeType::FileMove => change.new_symbol.is_some(),
        ChangeType::StringChange => change.new_symbol.is_some(),
        ChangeType::MethodRemoved => false,
        ChangeType::ClassRemoved => false,
        ChangeType::ReturnTypeChange => false,
        ChangeType::SignatureChange => false,
    }
}

/// Generate transform rules from a drift report.
///
/// For each auto-fixable change, creates a TransformRule that replaces
/// the old symbol with the new one in test files.
pub fn generate_transform_rules(report: &DriftReport) -> Vec<crate::refactor::TransformRule> {
    let mut rules = Vec::new();

    for change in &report.production_changes {
        if !is_auto_fixable(change) {
            continue;
        }

        let new_symbol = match &change.new_symbol {
            Some(s) => s,
            None => continue,
        };

        let id = format!("{:?}_{}", change.change_type, change.old_symbol)
            .to_lowercase()
            .replace(' ', "_");

        let description = match change.change_type {
            ChangeType::MethodRename => {
                format!(
                    "Rename {}{} ({})",
                    change.old_symbol, new_symbol, change.file
                )
            }
            ChangeType::ClassRename => {
                format!(
                    "Rename class {}{} ({})",
                    change.old_symbol, new_symbol, change.file
                )
            }
            ChangeType::ErrorCodeChange => {
                format!(
                    "Error code {}{} ({})",
                    change.old_symbol, new_symbol, change.file
                )
            }
            ChangeType::FileMove => {
                format!("File moved {}{}", change.old_symbol, new_symbol)
            }
            _ => format!("{}{} ({})", change.old_symbol, new_symbol, change.file),
        };

        let (find, replace) = match change.change_type {
            // Identifier renames should use word boundaries to avoid partial matches.
            ChangeType::MethodRename | ChangeType::ClassRename => {
                if !is_identifier(&change.old_symbol) || !is_identifier(new_symbol) {
                    continue;
                }
                (
                    format!(r"\b{}\b", regex::escape(&change.old_symbol)),
                    new_symbol.clone(),
                )
            }
            // Error/string changes are prone to false positives when symbols are too generic
            // (e.g. old="name", new="assistant"). Only auto-fix token-like literals.
            ChangeType::ErrorCodeChange | ChangeType::StringChange => {
                if !is_safe_literal_token(&change.old_symbol) || !is_safe_literal_token(new_symbol)
                {
                    continue;
                }
                (regex::escape(&change.old_symbol), new_symbol.clone())
            }
            // File moves should look like path-ish values.
            ChangeType::FileMove => {
                if !looks_like_path(&change.old_symbol) || !looks_like_path(new_symbol) {
                    continue;
                }
                (regex::escape(&change.old_symbol), new_symbol.clone())
            }
            _ => continue,
        };

        rules.push(crate::refactor::TransformRule {
            id,
            description,
            find,
            replace,
            files: "tests/**/*".to_string(),
            context: "line".to_string(),
        });
    }

    rules
}

fn is_identifier(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c == '_' || c.is_ascii_alphabetic() => {}
        _ => return false,
    }
    chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
}

fn is_safe_literal_token(s: &str) -> bool {
    if s.len() < 4 {
        return false;
    }

    // Path-ish and namespaced/string tokens are usually safe for literal replacement.
    if s.contains('/') || s.contains('\\') || s.contains(':') || s.contains('.') || s.contains('-')
    {
        return true;
    }

    // For underscore tokens, constrain to error-code-like vocabulary.
    // This avoids unsafe schema/field rewrites (e.g. flow_id -> pipeline_id).
    if s.contains('_') {
        let lower = s.to_ascii_lowercase();
        return lower.starts_with("rest_")
            || lower.starts_with("ability_")
            || lower.contains("error")
            || lower.contains("invalid")
            || lower.contains("forbidden")
            || lower.contains("denied")
            || lower.contains("not_found")
            || lower.contains("failed");
    }

    false
}

fn looks_like_path(s: &str) -> bool {
    s.len() >= 5 && (s.contains('/') || s.contains('\\'))
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn extract_method_rename() {
        let diff = r#"@@ -10,7 +10,7 @@
-    public function executeRunFlow($id) {
+    public function executeWorkflow($id) {
         return $this->doWork($id);
     }
"#;
        let changes = extract_changes_from_diff("src/Abilities/JobAbilities.php", diff);
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].change_type, ChangeType::MethodRename);
        assert_eq!(changes[0].old_symbol, "executeRunFlow");
        assert_eq!(changes[0].new_symbol.as_deref(), Some("executeWorkflow"));
    }

    #[test]
    fn extract_method_removed() {
        let diff = r#"@@ -20,5 +20,0 @@
-    public function oldHelper() {
-        return true;
-    }
"#;
        let changes = extract_changes_from_diff("src/Helper.php", diff);
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].change_type, ChangeType::MethodRemoved);
        assert_eq!(changes[0].old_symbol, "oldHelper");
        assert!(changes[0].new_symbol.is_none());
    }

    #[test]
    fn extract_error_code_change() {
        let diff = r#"@@ -5,7 +5,7 @@
-        return new WP_Error('rest_forbidden', 'Access denied');
+        return new WP_Error('ability_invalid_permissions', 'Access denied');
"#;
        let changes = extract_changes_from_diff("src/REST/Auth.php", diff);

        let code_changes: Vec<_> = changes
            .iter()
            .filter(|c| c.change_type == ChangeType::ErrorCodeChange)
            .collect();

        assert!(!code_changes.is_empty());
        assert_eq!(code_changes[0].old_symbol, "rest_forbidden");
        assert_eq!(
            code_changes[0].new_symbol.as_deref(),
            Some("ability_invalid_permissions")
        );
    }

    #[test]
    fn extract_class_rename() {
        let diff = r#"@@ -1,5 +1,5 @@
-class FlowsCommand extends BaseCommand {
+class FlowCommand extends BaseCommand {
     public function handle() {
"#;
        let changes = extract_changes_from_diff("src/Commands/FlowsCommand.php", diff);

        let cls = changes
            .iter()
            .find(|c| c.change_type == ChangeType::ClassRename)
            .unwrap();
        assert_eq!(cls.old_symbol, "FlowsCommand");
        assert_eq!(cls.new_symbol.as_deref(), Some("FlowCommand"));
    }

    #[test]
    fn extract_rust_fn_rename() {
        let diff = r#"@@ -10,7 +10,7 @@
-pub fn load_config(path: &Path) -> Config {
+pub fn read_config(path: &Path) -> Config {
     let data = fs::read_to_string(path).unwrap();
"#;
        let changes = extract_changes_from_diff("src/config.rs", diff);
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].change_type, ChangeType::MethodRename);
        assert_eq!(changes[0].old_symbol, "load_config");
        assert_eq!(changes[0].new_symbol.as_deref(), Some("read_config"));
    }

    #[test]
    fn is_test_file_detection() {
        assert!(is_test_file("tests/Unit/FooTest.php"));
        assert!(is_test_file("tests/integration/bar_test.rs"));
        assert!(!is_test_file("src/Foo.php"));
        assert!(!is_test_file("src/config.rs"));
    }

    #[test]
    fn auto_fixable_detection() {
        let rename = ProductionChange {
            change_type: ChangeType::MethodRename,
            file: "src/Foo.php".into(),
            old_symbol: "oldMethod".into(),
            new_symbol: Some("newMethod".into()),
            line: 10,
        };
        assert!(is_auto_fixable(&rename));

        let removed = ProductionChange {
            change_type: ChangeType::MethodRemoved,
            file: "src/Foo.php".into(),
            old_symbol: "deadMethod".into(),
            new_symbol: None,
            line: 10,
        };
        assert!(!is_auto_fixable(&removed));
    }

    #[test]
    fn generate_rules_from_rename() {
        let report = DriftReport {
            component: "test".into(),
            since: "v1.0".into(),
            production_changes: vec![ProductionChange {
                change_type: ChangeType::MethodRename,
                file: "src/Foo.php".into(),
                old_symbol: "executeRunFlow".into(),
                new_symbol: Some("executeWorkflow".into()),
                line: 10,
            }],
            drifted_tests: Vec::new(),
            total_drifted_files: 0,
            total_drift_references: 0,
            auto_fixable: 1,
        };

        let rules = generate_transform_rules(&report);
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].find, r"\bexecuteRunFlow\b");
        assert_eq!(rules[0].replace, "executeWorkflow");
        assert_eq!(rules[0].files, "tests/**/*");
    }

    #[test]
    fn generate_rules_skips_unsafe_generic_string_changes() {
        let report = DriftReport {
            component: "test".into(),
            since: "v1.0".into(),
            production_changes: vec![ProductionChange {
                change_type: ChangeType::ErrorCodeChange,
                file: "src/Foo.php".into(),
                old_symbol: "name".into(),
                new_symbol: Some("assistant".into()),
                line: 10,
            }],
            drifted_tests: Vec::new(),
            total_drifted_files: 0,
            total_drift_references: 0,
            auto_fixable: 1,
        };

        let rules = generate_transform_rules(&report);
        assert!(rules.is_empty());
    }

    #[test]
    fn generate_rules_keeps_safe_error_code_tokens() {
        let report = DriftReport {
            component: "test".into(),
            since: "v1.0".into(),
            production_changes: vec![ProductionChange {
                change_type: ChangeType::ErrorCodeChange,
                file: "src/Foo.php".into(),
                old_symbol: "rest_forbidden".into(),
                new_symbol: Some("ability_invalid_permissions".into()),
                line: 10,
            }],
            drifted_tests: Vec::new(),
            total_drifted_files: 0,
            total_drift_references: 0,
            auto_fixable: 1,
        };

        let rules = generate_transform_rules(&report);
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].find, "rest_forbidden");
        assert_eq!(rules[0].replace, "ability_invalid_permissions");
    }

    #[test]
    fn generate_rules_skips_non_error_underscore_tokens() {
        let report = DriftReport {
            component: "test".into(),
            since: "v1.0".into(),
            production_changes: vec![ProductionChange {
                change_type: ChangeType::ErrorCodeChange,
                file: "src/Foo.php".into(),
                old_symbol: "flow_id".into(),
                new_symbol: Some("pipeline_id".into()),
                line: 10,
            }],
            drifted_tests: Vec::new(),
            total_drifted_files: 0,
            total_drift_references: 0,
            auto_fixable: 1,
        };

        let rules = generate_transform_rules(&report);
        assert!(rules.is_empty());
    }

    #[test]
    fn skip_short_symbols() {
        let changes = vec![ProductionChange {
            change_type: ChangeType::MethodRename,
            file: "src/X.php".into(),
            old_symbol: "ab".into(), // too short
            new_symbol: Some("cd".into()),
            line: 1,
        }];

        let test_content = "line with ab in it\n";
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let tests_dir = root.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        std::fs::write(tests_dir.join("FooTest.php"), test_content).unwrap();

        let test_files = vec![tests_dir.join("FooTest.php")];
        let drifted = find_drift_references(&changes, &test_files, root);
        assert!(drifted.is_empty()); // Skipped because symbol < 3 chars
    }

    #[test]
    fn find_references_in_test_files() {
        let changes = vec![ProductionChange {
            change_type: ChangeType::MethodRename,
            file: "src/Foo.php".into(),
            old_symbol: "executeRunFlow".into(),
            new_symbol: Some("executeWorkflow".into()),
            line: 10,
        }];

        let test_content = r#"<?php
class FooTest extends TestCase {
    public function testRunFlow() {
        $result = $this->foo->executeRunFlow(1);
        $this->assertNotNull($result);
    }
}
"#;

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let tests_dir = root.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        std::fs::write(tests_dir.join("FooTest.php"), test_content).unwrap();

        let test_files = vec![tests_dir.join("FooTest.php")];
        let drifted = find_drift_references(&changes, &test_files, root);
        assert_eq!(drifted.len(), 1);
        assert_eq!(drifted[0].line, 4);
        assert!(drifted[0].content.contains("executeRunFlow"));
    }

    #[test]
    fn multiple_changes_multiple_tests() {
        let changes = vec![
            ProductionChange {
                change_type: ChangeType::MethodRename,
                file: "src/A.php".into(),
                old_symbol: "oldMethodA".into(),
                new_symbol: Some("newMethodA".into()),
                line: 5,
            },
            ProductionChange {
                change_type: ChangeType::ErrorCodeChange,
                file: "src/B.php".into(),
                old_symbol: "rest_forbidden".into(),
                new_symbol: Some("access_denied".into()),
                line: 10,
            },
        ];

        let test1 = "<?php\n$this->oldMethodA();\n";
        let test2 = "<?php\nassertEquals('rest_forbidden', $code);\n";

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let tests_dir = root.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        std::fs::write(tests_dir.join("ATest.php"), test1).unwrap();
        std::fs::write(tests_dir.join("BTest.php"), test2).unwrap();

        let test_files = vec![tests_dir.join("ATest.php"), tests_dir.join("BTest.php")];
        let drifted = find_drift_references(&changes, &test_files, root);
        assert_eq!(drifted.len(), 2);
    }

    #[test]
    fn skip_comment_lines() {
        let changes = vec![ProductionChange {
            change_type: ChangeType::MethodRename,
            file: "src/Foo.php".into(),
            old_symbol: "oldMethod".into(),
            new_symbol: Some("newMethod".into()),
            line: 5,
        }];

        let test_content =
            "<?php\n// oldMethod was renamed\n/* oldMethod docs */\n$this->oldMethod();\n";

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let tests_dir = root.join("tests");
        std::fs::create_dir_all(&tests_dir).unwrap();
        std::fs::write(tests_dir.join("FooTest.php"), test_content).unwrap();

        let test_files = vec![tests_dir.join("FooTest.php")];
        let drifted = find_drift_references(&changes, &test_files, root);
        assert_eq!(drifted.len(), 1); // Only the actual code line, not comments
        assert_eq!(drifted[0].line, 4);
    }
}