le-change 0.3.1

Ultra-fast Git change detection library with zero-cost abstractions
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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
//! Core type definitions with zero-copy design

use std::borrow::Cow;

/// Interned string handle - just an index into the interner
///
/// This is Copy-able and has zero overhead
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct InternedString(pub(crate) u32);

/// Change type for a file (matches git diff output)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum ChangeType {
    /// Added file
    Added = b'A',
    /// Copied file
    Copied = b'C',
    /// Deleted file
    Deleted = b'D',
    /// Modified file
    Modified = b'M',
    /// Renamed file
    Renamed = b'R',
    /// Type changed (permissions/mode)
    TypeChanged = b'T',
    /// Unmerged (conflict)
    Unmerged = b'U',
    /// Unknown change type
    Unknown = b'X',
}

impl ChangeType {
    /// Parse from git diff-filter character - zero allocation
    #[inline]
    pub const fn from_byte(b: u8) -> Option<Self> {
        match b {
            b'A' => Some(Self::Added),
            b'C' => Some(Self::Copied),
            b'D' => Some(Self::Deleted),
            b'M' => Some(Self::Modified),
            b'R' => Some(Self::Renamed),
            b'T' => Some(Self::TypeChanged),
            b'U' => Some(Self::Unmerged),
            b'X' => Some(Self::Unknown),
            _ => None,
        }
    }

    /// Convert to git diff-filter byte character
    #[inline]
    pub const fn as_byte(&self) -> u8 {
        match self {
            Self::Added => b'A',
            Self::Copied => b'C',
            Self::Deleted => b'D',
            Self::Modified => b'M',
            Self::Renamed => b'R',
            Self::TypeChanged => b'T',
            Self::Unmerged => b'U',
            Self::Unknown => b'X',
        }
    }

    /// Get string representation
    #[inline]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Added => "added",
            Self::Copied => "copied",
            Self::Deleted => "deleted",
            Self::Modified => "modified",
            Self::Renamed => "renamed",
            Self::TypeChanged => "type_changed",
            Self::Unmerged => "unmerged",
            Self::Unknown => "unknown",
        }
    }
}

/// A single changed file entry with minimal allocations
#[derive(Debug, Clone)]
pub struct ChangedFile {
    /// Path - interned for deduplication
    pub path: InternedString,
    /// Change type
    pub change_type: ChangeType,
    /// Previous path for renames/copies (also interned)
    pub previous_path: Option<InternedString>,
    /// Is this a symlink?
    pub is_symlink: bool,
    /// Submodule depth (0 = root)
    pub submodule_depth: u8,
    /// File origin tracking (current changes vs previous failures vs previous successes)
    pub origin: FileOrigin,
}

/// Result of a diff operation - owns minimal data
#[derive(Debug, Default)]
pub struct DiffResult {
    /// All changed files
    pub files: Vec<ChangedFile>,
    /// Total additions (lines)
    pub additions: u32,
    /// Total deletions (lines)
    pub deletions: u32,
}

/// A file that was added within base..head history but no longer exists at
/// head — invisible to the two-endpoint diff. Both fields are interned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VanishedFile {
    /// Path at last existence (post-rename name if renamed before deletion)
    pub path: InternedString,
    /// Last commit where the file existed (parent of the deleting commit)
    pub last_seen_sha: InternedString,
}

/// Processed result of the full detection pipeline (index-based partitioning)
#[derive(Debug, Default)]
pub struct ProcessedResult {
    /// All files from the diff (unfiltered superset)
    pub all_files: Vec<ChangedFile>,
    /// Indices into all_files matching pattern filter
    pub filtered_indices: Vec<u32>,
    /// Indices into all_files NOT matching pattern filter
    pub unmatched_indices: Vec<u32>,
    /// Whether a pattern filter was applied
    pub pattern_applied: bool,
    /// Per-YAML-group index results
    pub group_results: Vec<GroupResult>,
    /// Total additions (lines)
    pub additions: u32,
    /// Total deletions (lines)
    pub deletions: u32,
    /// Pipeline diagnostics (warnings, soft errors)
    pub diagnostics: Vec<Diagnostic>,
    /// Enhanced workflow check result
    pub workflow_result: Option<WorkflowCheckResult>,
    /// CI rebuild/skip decision
    pub ci_decision: Option<CiDecision>,
    /// Files added then removed within base..head (detect_vanished),
    /// ordered newest-deletion-first
    pub vanished_files: Vec<VanishedFile>,
    /// Resolved base SHA (interned); reconstruct_sha for endpoint-deleted groups
    pub base_sha: Option<InternedString>,
    /// Resolved head SHA (interned)
    pub head_sha: Option<InternedString>,
}

impl ProcessedResult {
    /// Get files matching the pattern filter
    pub fn matched_files(&self) -> Vec<&ChangedFile> {
        self.filtered_indices
            .iter()
            .map(|&i| &self.all_files[i as usize])
            .collect()
    }

    /// Get files NOT matching the pattern filter ("other" files)
    pub fn other_files(&self) -> Vec<&ChangedFile> {
        self.unmatched_indices
            .iter()
            .map(|&i| &self.all_files[i as usize])
            .collect()
    }

    /// Create from an unfiltered DiffResult (no pattern applied)
    pub fn from_unfiltered(diff: DiffResult) -> Self {
        let n = diff.files.len() as u32;
        Self {
            filtered_indices: (0..n).collect(),
            unmatched_indices: Vec::new(),
            pattern_applied: false,
            all_files: diff.files,
            group_results: Vec::new(),
            additions: diff.additions,
            deletions: diff.deletions,
            diagnostics: Vec::new(),
            workflow_result: None,
            ci_decision: None,
            vanished_files: Vec::new(),
            base_sha: None,
            head_sha: None,
        }
    }
}

/// Workflow run status from GitHub Actions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum WorkflowStatus {
    /// Workflow is queued
    Queued,
    /// Workflow is in progress
    InProgress,
    /// Workflow completed (check conclusion for pass/fail)
    Completed,
}

/// Workflow run conclusion (only valid when status = Completed)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum WorkflowConclusion {
    /// Workflow succeeded
    Success,
    /// Workflow failed
    Failure,
    /// Workflow was cancelled
    Cancelled,
    /// Workflow was skipped
    Skipped,
    /// Workflow timed out
    TimedOut,
    /// Other/unknown
    Neutral,
}

/// Failure tracking granularity level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FailureTrackingLevel {
    /// Track at workflow run level (all commit files attributed to run result)
    #[default]
    Run,
    /// Track at individual job level (files partitioned by job pattern matching)
    Job,
}

/// File origin - tracks whether a file is in current changes, failed workflows, successful workflows, or combinations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct FileOrigin {
    /// File is in current diff
    pub in_current_changes: bool,
    /// File was in previous workflow failure
    pub in_previous_failure: bool,
    /// File was in a successful prior workflow
    pub in_previous_success: bool,
}

/// Workflow run metadata (minimal, following zero-copy design)
///
/// All fields are Copy types, so the struct itself is Copy.
#[derive(Debug, Clone, Copy)]
pub struct WorkflowRun {
    /// Workflow run ID (GitHub API)
    pub id: u64,
    /// Workflow name (interned string)
    pub name: InternedString,
    /// Status
    pub status: WorkflowStatus,
    /// Conclusion (if completed)
    pub conclusion: Option<WorkflowConclusion>,
    /// Branch (interned string)
    pub branch: InternedString,
    /// Head SHA (interned string)
    pub head_sha: InternedString,
    /// Commit timestamp (Unix epoch seconds)
    pub created_at: i64,
}

/// Individual job within a workflow run
///
/// All fields are Copy types, so the struct itself is Copy.
#[derive(Debug, Clone, Copy)]
pub struct WorkflowJob {
    /// Job ID
    pub id: u64,
    /// Job name (interned)
    pub name: InternedString,
    /// Job status
    pub status: WorkflowStatus,
    /// Job conclusion (if completed)
    pub conclusion: Option<WorkflowConclusion>,
    /// Parent workflow run ID
    pub run_id: u64,
    /// Started at (Unix epoch seconds)
    pub started_at: i64,
    /// Completed at (Unix epoch seconds)
    pub completed_at: i64,
}

/// Workflow failure context with affected files
#[derive(Debug)]
pub struct WorkflowFailure {
    /// The failed workflow run
    pub run: WorkflowRun,
    /// Files that were changed in the commit that failed
    pub files: Vec<InternedString>,
    /// Individual failed jobs (populated when failure_tracking_level is Job)
    pub failed_jobs: Vec<WorkflowJob>,
}

/// Successful workflow with its verified files
#[derive(Debug)]
pub struct WorkflowSuccess {
    /// The successful workflow run
    pub run: WorkflowRun,
    /// Individual job results (populated when failure_tracking_level is Job)
    pub jobs: Vec<WorkflowJob>,
    /// Files verified by this success
    pub files: Vec<InternedString>,
}

/// Result of workflow checking process
#[derive(Debug, Default)]
pub struct WorkflowCheckResult {
    /// Workflows currently running that overlap with our files
    pub blocking_runs: Vec<WorkflowRun>,
    /// Recent failures on this branch
    pub failures: Vec<WorkflowFailure>,
    /// Recent successes on this branch
    pub successes: Vec<WorkflowSuccess>,
    /// Did we wait for blocking workflows?
    pub waited: bool,
    /// Wait time in milliseconds
    pub wait_time_ms: u64,
    /// Groups blocked by concurrent workflows: group_key → blocking run IDs
    pub blocked_groups: std::collections::HashMap<InternedString, Vec<u64>>,
}

/// CI rebuild/skip decision computed from workflow analysis
#[derive(Debug, Default)]
pub struct CiDecision {
    /// Files that need CI attention (current changes + previous failures - verified successes)
    pub files_to_rebuild: Vec<InternedString>,
    /// Files from prior commits verified as successful (skip these)
    pub files_to_skip: Vec<InternedString>,
    /// Job names that failed in recent workflows
    pub failed_jobs: Vec<InternedString>,
    /// Job names that succeeded in recent workflows
    pub successful_jobs: Vec<InternedString>,
    /// Per-file rebuild reason for debugging
    pub rebuild_reasons: Vec<RebuildReason>,
}

/// Reason why a file needs to be rebuilt
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum RebuildReasonKind {
    /// File is in current diff
    NewChange,
    /// File was in a failed workflow
    PreviousFailure,
    /// Both new change and previous failure
    BothNewAndFailed,
}

impl RebuildReasonKind {
    /// Canonical string form used by every output surface (CLI, action, python).
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::NewChange => "new_change",
            Self::PreviousFailure => "previous_failure",
            Self::BothNewAndFailed => "both_new_and_failed",
        }
    }
}

/// Detailed rebuild reason for a single file
#[derive(Debug, Clone)]
pub struct RebuildReason {
    /// File path
    pub file: InternedString,
    /// Why this file needs rebuild
    pub kind: RebuildReasonKind,
    /// Which workflow run failed (if applicable)
    pub failed_run_id: Option<u64>,
    /// Which specific job failed (if applicable)
    pub failed_job_name: Option<InternedString>,
}

/// Pipeline diagnostic message
#[derive(Debug, Clone)]
pub struct Diagnostic {
    /// Severity level
    pub severity: DiagnosticSeverity,
    /// Category of the diagnostic
    pub category: DiagnosticCategory,
    /// Human-readable message
    pub message: String,
}

/// Diagnostic severity level
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum DiagnosticSeverity {
    /// Non-fatal warning
    Warning,
    /// Soft error (recoverable)
    SoftError,
}

impl DiagnosticSeverity {
    /// Canonical string form used by every output surface (CLI, action, python).
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Warning => "warning",
            Self::SoftError => "soft_error",
        }
    }
}

/// Diagnostic category for filtering
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum DiagnosticCategory {
    /// Error during initial diff computation
    InitialDiff,
    /// Error during submodule diff
    SubmoduleDiff,
    /// Skipped because base and head SHA are the same
    SkippedSameSha,
    /// Shallow clone depth insufficient
    ShallowClone,
    /// Error loading pattern file
    PatternLoad,
    /// Error during symlink detection
    SymlinkDetection,
    /// Workflow API error (non-fatal)
    WorkflowApi,
    /// Ancestor directory file recovery
    AncestorRecovery,
    /// Vanished-file detection (history walk)
    VanishedDetection,
}

impl DiagnosticCategory {
    /// Canonical string form used by every output surface (CLI, action, python).
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InitialDiff => "initial_diff",
            Self::SubmoduleDiff => "submodule_diff",
            Self::SkippedSameSha => "skipped_same_sha",
            Self::ShallowClone => "shallow_clone",
            Self::PatternLoad => "pattern_load",
            Self::SymlinkDetection => "symlink_detection",
            Self::WorkflowApi => "workflow_api",
            Self::AncestorRecovery => "ancestor_recovery",
            Self::VanishedDetection => "vanished_detection",
        }
    }
}

/// Result of YAML group pattern matching
#[derive(Debug, Clone)]
pub struct GroupResult {
    /// Group key (interned)
    pub key: InternedString,
    /// Indices into all_files that matched this group's patterns
    pub matched_indices: Vec<u32>,
    /// Indices into ProcessedResult::vanished_files matched by this group
    pub vanished_indices: Vec<u32>,
}

/// Deploy action for a YAML group
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum GroupDeployAction {
    /// Group should be deployed
    Deploy,
    /// Group should be skipped
    Skip,
    /// Group's stack should be destroyed (its defining files are gone)
    Destroy,
}

impl GroupDeployAction {
    /// Canonical string form used by every output surface (CLI, action, python).
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Deploy => "deploy",
            Self::Skip => "skip",
            Self::Destroy => "destroy",
        }
    }
}

/// Reason why a group needs deployment
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum GroupDeployReason {
    /// Group has new changes in current diff
    NewChange,
    /// Group has files from a previous workflow failure
    PreviousFailure,
    /// Group has both new changes and previous failures
    BothNewAndFailed,
    /// Group's files were added then removed within the PR history
    Vanished,
    /// Group's files were deleted at the endpoint diff
    EndpointDeleted,
}

impl GroupDeployReason {
    /// Canonical string form used by every output surface (CLI, action, python).
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::NewChange => "new_change",
            Self::PreviousFailure => "previous_failure",
            Self::BothNewAndFailed => "both_new_and_failed",
            Self::Vanished => "vanished",
            Self::EndpointDeleted => "deleted",
        }
    }
}

/// Key mode for `files_group_by` template discovery
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GroupByKey {
    /// Use the directory name as group key (e.g. "prod")
    #[default]
    Name,
    /// Use the relative path as group key (e.g. "stacks/prod")
    Path,
    /// Use a short hash of the directory name as group key (e.g. "a1b2c3d4")
    Hash,
}

impl GroupByKey {
    /// Parse from a string (case-insensitive)
    pub fn parse(s: &str) -> Self {
        match s.to_ascii_lowercase().as_str() {
            "path" => Self::Path,
            "hash" => Self::Hash,
            _ => Self::Name,
        }
    }
}

/// Deploy decision for a single YAML group
#[derive(Debug, Clone)]
pub struct GroupDeployDecision {
    /// Group key (interned)
    pub key: InternedString,
    /// Deploy or skip
    pub action: GroupDeployAction,
    /// Reason for deployment (None when action is Skip)
    pub reason: Option<GroupDeployReason>,
    /// Files in this group that need rebuilding
    pub files_to_rebuild: Vec<InternedString>,
    /// Files in this group that can be skipped
    pub files_to_skip: Vec<InternedString>,
    /// Total files matched by this group
    pub total_files: u32,
    /// Whether this group is blocked by a concurrent workflow
    pub concurrency_blocked: bool,
    /// Number of concurrent workflow runs blocking this group
    pub concurrency_blocked_by: u32,
    /// Vanished members of this group (empty unless detect_vanished)
    pub vanished_files: Vec<VanishedFile>,
    /// Commit to reconstruct file contents from (set when action == Destroy):
    /// newest vanished last_seen_sha, or base_sha for endpoint-deleted groups
    pub reconstruct_sha: Option<InternedString>,
}

/// Configuration input - parameters organized by category
#[derive(Clone)]
pub struct InputConfig<'a> {
    // Git references
    /// Base commit SHA for comparison
    pub base_sha: Option<Cow<'a, str>>,
    /// Current commit SHA
    pub sha: Option<Cow<'a, str>>,
    /// Include changes since this date
    pub since: Option<Cow<'a, str>>,
    /// Include changes until this date
    pub until: Option<Cow<'a, str>>,

    // Pattern filtering
    /// Glob patterns to include files
    pub files: Option<Vec<Cow<'a, str>>>,
    /// Separator for files output
    pub files_separator: Cow<'a, str>,
    /// Glob patterns to exclude files
    pub files_ignore: Option<Vec<Cow<'a, str>>>,
    /// Separator for ignored files output
    pub files_ignore_separator: Cow<'a, str>,

    // Feature 1: YAML patterns
    /// YAML content with pattern groups
    pub files_yaml: Option<Cow<'a, str>>,
    /// Path to YAML file with pattern groups
    pub files_yaml_from_source_file: Option<Cow<'a, str>>,
    // Feature 2: Pattern source files
    /// Path to file containing patterns (one per line)
    pub files_from_source_file: Option<Cow<'a, str>>,
    /// Separator for source file patterns
    pub files_from_source_file_separator: Cow<'a, str>,

    // Diff configuration
    /// Git diff filter (ACDMRTUX)
    pub diff_filter: Cow<'a, str>,
    /// Include both old and new paths for renamed files
    pub include_all_old_new_renamed_files: bool,
    /// Separator between old and new paths
    pub old_new_separator: Cow<'a, str>,
    /// Separator for old/new files list
    pub old_new_files_separator: Cow<'a, str>,

    // Path handling
    /// Output directory names instead of files
    pub dir_names: bool,
    /// Maximum depth for directory names
    pub dir_names_max_depth: Option<u32>,
    /// Enable git quotepath
    pub quotepath: bool,
    /// Path separator for output
    pub path_separator: Cow<'a, str>,

    // Feature 6: Directory extras
    /// Exclude current directory from dir_names output
    pub dir_names_exclude_current_dir: bool,
    /// Only include directories containing these files
    pub dir_names_include_files: Option<Vec<Cow<'a, str>>>,
    /// For deleted files, only include directories where all files are deleted
    pub dir_names_deleted_files_include_only_deleted_dirs: bool,

    // Submodules
    /// Include submodule changes
    pub include_submodules: bool,
    /// Filter for submodule paths
    pub submodule_filter: Option<Cow<'a, str>>,

    // Fetch configuration
    /// Git fetch depth
    pub fetch_depth: u32,
    /// Fetch additional submodule history
    pub fetch_additional_submodule_history: bool,

    // Output options
    /// Output as JSON
    pub json: bool,
    /// Escape JSON special characters
    pub escape_json: bool,
    /// Enable safe output mode
    pub safe_output: bool,
    /// Output directory for file dumps
    pub output_dir: Option<Cow<'a, str>>,

    // Vanished-file detection
    /// Walk base..head first-parent history for files added then removed
    pub detect_vanished: bool,
    /// Max commits to walk before truncating with a diagnostic (0 = unlimited)
    pub vanished_max_commits: u32,
    /// Map groups whose only membership is endpoint-Deleted files to Destroy
    /// (reconstruct_sha = base_sha)
    pub deleted_to_destroy: bool,

    // Performance tuning
    /// Skip initial fetch operation
    pub skip_initial_fetch: bool,
    /// Use GitHub REST API instead of git
    pub use_rest_api: bool,
    /// API URL override
    pub api_url: Option<Cow<'a, str>>,
    /// GitHub API token
    pub token: Option<Cow<'a, str>>,

    // Advanced options
    /// Write output to files
    pub write_output_files: bool,
    /// Process negation patterns first
    pub negation_patterns_first: bool,
    /// Match .gitignore files
    pub match_gitignore_files: bool,
    /// Recover deleted file contents
    pub recover_deleted_files: bool,
    /// Exclude symbolic links
    pub exclude_symlinks: bool,

    // Feature 9: Tag comparison
    /// Pattern to match tags for comparison
    pub tags_pattern: Option<Cow<'a, str>>,
    /// Pattern to ignore tags
    pub tags_ignore_pattern: Option<Cow<'a, str>>,

    // Feature 11: Soft-fail
    /// Fail on initial diff error (default: true)
    pub fail_on_initial_diff_error: bool,
    /// Fail on submodule diff error (default: false)
    pub fail_on_submodule_diff_error: bool,
    /// Skip if base and head SHA are the same (default: false)
    pub skip_same_sha: bool,

    // Feature 15: Rename splitting
    /// Output renamed files as separate deleted + added entries
    pub output_renamed_as_deleted_added: bool,

    // Feature 16: POSIX path separator
    /// Force POSIX (forward slash) path separators in output
    pub use_posix_path_separator: bool,

    // Workflow failure tracking
    /// Enable workflow failure tracking
    pub track_workflow_failures: bool,
    /// Number of commits to look back for failed workflows (default: 5)
    pub workflow_lookback_commits: u32,
    /// Check for active workflows on same files and wait (default: true)
    pub wait_for_active_workflows: bool,
    /// Maximum wait time for active workflows in seconds (default: 300 = 5 min)
    pub workflow_max_wait_seconds: u32,
    /// Include failed files in incremental CI output (default: true)
    pub include_failed_files: bool,

    // Workflow intelligence (enhanced)
    /// Failure tracking granularity: Run (default) or Job (per-job pattern matching)
    pub failure_tracking_level: FailureTrackingLevel,
    /// Number of commits to look back for successful workflows
    pub workflow_success_lookback: u32,
    /// Skip files from successful prior workflows (default: true when track_workflow_failures)
    pub skip_successful_files: bool,
    /// Glob pattern to match specific workflow names
    pub workflow_name_filter: Option<Cow<'a, str>>,

    // Group-by discovery
    /// Template pattern for auto-discovering groups (e.g. "stacks/{group}/**")
    pub files_group_by: Option<Cow<'a, str>>,
    /// Key mode for group-by discovery: "name" (default), "path", or "hash"
    pub files_group_by_key: Option<Cow<'a, str>>,

    // Ancestor directory file association
    /// Depth for ancestor directory file lookup (0=disabled, max=3)
    pub files_ancestor_lookup_depth: u32,

    // Deploy matrix enrichment
    /// Include action/reason fields in deploy matrix JSON
    pub deploy_matrix_include_reason: bool,
    /// Include concurrency_blocked fields in deploy matrix JSON
    pub deploy_matrix_include_concurrency: bool,
}

impl<'a> std::fmt::Debug for InputConfig<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InputConfig")
            .field("base_sha", &self.base_sha)
            .field("sha", &self.sha)
            .field("since", &self.since)
            .field("until", &self.until)
            .field("files", &self.files)
            .field("files_separator", &self.files_separator)
            .field("files_ignore", &self.files_ignore)
            .field("files_yaml", &self.files_yaml)
            .field("files_from_source_file", &self.files_from_source_file)
            .field("diff_filter", &self.diff_filter)
            .field("json", &self.json)
            .field("safe_output", &self.safe_output)
            .field("use_rest_api", &self.use_rest_api)
            .field("api_url", &self.api_url)
            .field("token", &self.token.as_ref().map(|_| "<redacted>"))
            .field("track_workflow_failures", &self.track_workflow_failures)
            .field("files_group_by", &self.files_group_by)
            .field("files_group_by_key", &self.files_group_by_key)
            .field(
                "files_ancestor_lookup_depth",
                &self.files_ancestor_lookup_depth,
            )
            .field(
                "deploy_matrix_include_reason",
                &self.deploy_matrix_include_reason,
            )
            .field(
                "deploy_matrix_include_concurrency",
                &self.deploy_matrix_include_concurrency,
            )
            .finish_non_exhaustive()
    }
}

impl<'a> Default for InputConfig<'a> {
    fn default() -> Self {
        Self {
            base_sha: None,
            sha: None,
            since: None,
            until: None,
            files: None,
            files_separator: Cow::Borrowed("\n"),
            files_ignore: None,
            files_ignore_separator: Cow::Borrowed("\n"),
            files_yaml: None,
            files_yaml_from_source_file: None,
            files_from_source_file: None,
            files_from_source_file_separator: Cow::Borrowed("\n"),
            diff_filter: Cow::Borrowed("ACDMRTUX"),
            include_all_old_new_renamed_files: false,
            old_new_separator: Cow::Borrowed(" "),
            old_new_files_separator: Cow::Borrowed("\n"),
            dir_names: false,
            dir_names_max_depth: None,
            quotepath: true,
            path_separator: if cfg!(windows) {
                Cow::Borrowed("\\")
            } else {
                Cow::Borrowed("/")
            },
            dir_names_exclude_current_dir: false,
            dir_names_include_files: None,
            dir_names_deleted_files_include_only_deleted_dirs: false,
            include_submodules: false,
            submodule_filter: None,
            fetch_depth: 0,
            fetch_additional_submodule_history: false,
            json: false,
            escape_json: true,
            safe_output: true,
            output_dir: None,
            detect_vanished: false,
            vanished_max_commits: 500,
            deleted_to_destroy: false,
            skip_initial_fetch: false,
            use_rest_api: false,
            api_url: None,
            token: None,
            write_output_files: false,
            negation_patterns_first: true,
            match_gitignore_files: false,
            recover_deleted_files: false,
            exclude_symlinks: false,
            tags_pattern: None,
            tags_ignore_pattern: None,
            fail_on_initial_diff_error: true,
            fail_on_submodule_diff_error: false,
            skip_same_sha: false,
            output_renamed_as_deleted_added: false,
            use_posix_path_separator: false,
            track_workflow_failures: false,
            workflow_lookback_commits: 5,
            wait_for_active_workflows: true,
            workflow_max_wait_seconds: 300,
            include_failed_files: true,
            failure_tracking_level: FailureTrackingLevel::Run,
            workflow_success_lookback: 5,
            skip_successful_files: true,
            workflow_name_filter: None,
            files_group_by: None,
            files_group_by_key: None,
            files_ancestor_lookup_depth: 0,
            deploy_matrix_include_reason: false,
            deploy_matrix_include_concurrency: false,
        }
    }
}

impl<'a> InputConfig<'a> {
    /// Baseline configuration for GitHub Actions consumers: safe multiline
    /// escaping, JSON outputs, POSIX path separators, and no implicit fetch.
    /// The CLI (and therefore the composite action) builds on this; the policy
    /// lives here so every consumer agrees on what "running under GHA" means.
    pub fn github_actions_defaults() -> Self {
        Self {
            safe_output: true,
            json: true,
            escape_json: true,
            use_posix_path_separator: true,
            skip_initial_fetch: true,
            ..Self::default()
        }
    }

    // ── zero-copy builder methods ───────────────────────────────────────
    // Each setter borrows (`Cow::Borrowed`) — no allocation. `Option`-taking
    // setters leave the field untouched on `None` so cleaned env inputs can
    // be threaded straight through.

    /// Override the base commit SHA (no-op on `None`).
    pub fn with_base_sha(mut self, v: Option<&'a str>) -> Self {
        if v.is_some() {
            self.base_sha = v.map(Cow::Borrowed);
        }
        self
    }

    /// Override the head commit SHA (no-op on `None`).
    pub fn with_sha(mut self, v: Option<&'a str>) -> Self {
        if v.is_some() {
            self.sha = v.map(Cow::Borrowed);
        }
        self
    }

    /// Set include glob patterns (no-op on `None`).
    pub fn with_files(mut self, v: Option<Vec<&'a str>>) -> Self {
        if let Some(files) = v {
            self.files = Some(files.into_iter().map(Cow::Borrowed).collect());
        }
        self
    }

    /// Set exclude glob patterns (no-op on `None`).
    pub fn with_files_ignore(mut self, v: Option<Vec<&'a str>>) -> Self {
        if let Some(files) = v {
            self.files_ignore = Some(files.into_iter().map(Cow::Borrowed).collect());
        }
        self
    }

    /// Set the group discovery template, e.g. `stacks/{group}/**` (no-op on `None`).
    pub fn with_files_group_by(mut self, v: Option<&'a str>) -> Self {
        if v.is_some() {
            self.files_group_by = v.map(Cow::Borrowed);
        }
        self
    }

    /// Set the group key mode (`name`, `path`, or `hash`).
    pub fn with_files_group_by_key(mut self, v: &'a str) -> Self {
        self.files_group_by_key = Some(Cow::Borrowed(v));
        self
    }

    /// Set ancestor directory lookup depth (clamped to 3 by the pipeline).
    pub fn with_files_ancestor_lookup_depth(mut self, v: u32) -> Self {
        self.files_ancestor_lookup_depth = v;
        self
    }

    /// Enable workflow failure tracking.
    pub fn with_track_workflow_failures(mut self, v: bool) -> Self {
        self.track_workflow_failures = v;
        self
    }

    /// Set failure tracking granularity from its canonical string form
    /// (`"job"`/`"Job"` -> Job, anything else -> Run).
    pub fn with_failure_tracking_level_str(mut self, v: &str) -> Self {
        self.failure_tracking_level = match v {
            "job" | "Job" => FailureTrackingLevel::Job,
            _ => FailureTrackingLevel::Run,
        };
        self
    }

    /// Wait for concurrent overlapping workflows before deciding.
    pub fn with_wait_for_active_workflows(mut self, v: bool) -> Self {
        self.wait_for_active_workflows = v;
        self
    }

    /// Cap the wait for active workflows, in seconds.
    pub fn with_workflow_max_wait_seconds(mut self, v: u32) -> Self {
        self.workflow_max_wait_seconds = v;
        self
    }

    /// Filter tracked workflows by name glob (no-op on `None`).
    pub fn with_workflow_name_filter(mut self, v: Option<&'a str>) -> Self {
        if v.is_some() {
            self.workflow_name_filter = v.map(Cow::Borrowed);
        }
        self
    }

    /// Include action/reason fields in the deploy matrix.
    pub fn with_deploy_matrix_include_reason(mut self, v: bool) -> Self {
        self.deploy_matrix_include_reason = v;
        self
    }

    /// Include concurrency fields in the deploy matrix.
    pub fn with_deploy_matrix_include_concurrency(mut self, v: bool) -> Self {
        self.deploy_matrix_include_concurrency = v;
        self
    }

    /// Set the GitHub token (no-op on `None`).
    pub fn with_token(mut self, v: Option<&'a str>) -> Self {
        if v.is_some() {
            self.token = v.map(Cow::Borrowed);
        }
        self
    }

    /// Enable vanished-file detection (base..head first-parent history walk).
    pub fn with_detect_vanished(mut self, v: bool) -> Self {
        self.detect_vanished = v;
        self
    }

    /// Cap the vanished-detection history walk (0 = unlimited).
    pub fn with_vanished_max_commits(mut self, v: u32) -> Self {
        self.vanished_max_commits = v;
        self
    }

    /// Map endpoint-deleted-only groups to Destroy deploy actions.
    pub fn with_deleted_to_destroy(mut self, v: bool) -> Self {
        self.deleted_to_destroy = v;
        self
    }
}

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

    #[test]
    fn test_builder_matches_struct_literal() {
        let built = InputConfig::github_actions_defaults()
            .with_base_sha(Some("abc"))
            .with_sha(Some("def"))
            .with_files(Some(vec!["stacks/**"]))
            .with_files_ignore(Some(vec!["docs/**"]))
            .with_files_group_by(Some("stacks/{group}/**"))
            .with_files_group_by_key("path")
            .with_files_ancestor_lookup_depth(2)
            .with_track_workflow_failures(true)
            .with_failure_tracking_level_str("job")
            .with_wait_for_active_workflows(true)
            .with_workflow_max_wait_seconds(60)
            .with_workflow_name_filter(Some("CI*"))
            .with_deploy_matrix_include_reason(true)
            .with_deploy_matrix_include_concurrency(true)
            .with_token(Some("t"));

        let literal = InputConfig {
            base_sha: Some(Cow::Borrowed("abc")),
            sha: Some(Cow::Borrowed("def")),
            files: Some(vec![Cow::Borrowed("stacks/**")]),
            files_ignore: Some(vec![Cow::Borrowed("docs/**")]),
            files_group_by: Some(Cow::Borrowed("stacks/{group}/**")),
            files_group_by_key: Some(Cow::Borrowed("path")),
            files_ancestor_lookup_depth: 2,
            track_workflow_failures: true,
            failure_tracking_level: FailureTrackingLevel::Job,
            wait_for_active_workflows: true,
            workflow_max_wait_seconds: 60,
            workflow_name_filter: Some(Cow::Borrowed("CI*")),
            deploy_matrix_include_reason: true,
            deploy_matrix_include_concurrency: true,
            token: Some(Cow::Borrowed("t")),
            safe_output: true,
            json: true,
            escape_json: true,
            use_posix_path_separator: true,
            skip_initial_fetch: true,
            ..Default::default()
        };

        assert_eq!(built.base_sha, literal.base_sha);
        assert_eq!(built.sha, literal.sha);
        assert_eq!(built.files, literal.files);
        assert_eq!(built.files_ignore, literal.files_ignore);
        assert_eq!(built.files_group_by, literal.files_group_by);
        assert_eq!(built.files_group_by_key, literal.files_group_by_key);
        assert_eq!(
            built.files_ancestor_lookup_depth,
            literal.files_ancestor_lookup_depth
        );
        assert_eq!(
            built.track_workflow_failures,
            literal.track_workflow_failures
        );
        assert_eq!(built.failure_tracking_level, literal.failure_tracking_level);
        assert_eq!(
            built.wait_for_active_workflows,
            literal.wait_for_active_workflows
        );
        assert_eq!(
            built.workflow_max_wait_seconds,
            literal.workflow_max_wait_seconds
        );
        assert_eq!(built.workflow_name_filter, literal.workflow_name_filter);
        assert_eq!(built.token, literal.token);
        assert!(built.safe_output && built.json && built.escape_json);
        assert!(built.use_posix_path_separator && built.skip_initial_fetch);
    }

    #[test]
    fn test_builder_none_leaves_defaults() {
        let built = InputConfig::github_actions_defaults()
            .with_base_sha(None)
            .with_files(None)
            .with_files_group_by(None)
            .with_workflow_name_filter(None)
            .with_token(None);
        assert!(built.base_sha.is_none());
        assert!(built.files.is_none());
        assert!(built.files_group_by.is_none());
        assert!(built.workflow_name_filter.is_none());
        assert!(built.token.is_none());
    }

    #[test]
    fn test_change_type_from_byte() {
        assert_eq!(ChangeType::from_byte(b'A'), Some(ChangeType::Added));
        assert_eq!(ChangeType::from_byte(b'M'), Some(ChangeType::Modified));
        assert_eq!(ChangeType::from_byte(b'D'), Some(ChangeType::Deleted));
        assert_eq!(ChangeType::from_byte(b'R'), Some(ChangeType::Renamed));
        assert_eq!(ChangeType::from_byte(b'Z'), None);
    }

    #[test]
    fn test_change_type_as_str() {
        assert_eq!(ChangeType::Added.as_str(), "added");
        assert_eq!(ChangeType::Modified.as_str(), "modified");
        assert_eq!(ChangeType::Deleted.as_str(), "deleted");
    }

    #[test]
    fn test_change_type_as_byte() {
        assert_eq!(ChangeType::Added.as_byte(), b'A');
        assert_eq!(ChangeType::Modified.as_byte(), b'M');
        assert_eq!(ChangeType::Deleted.as_byte(), b'D');
        assert_eq!(ChangeType::Renamed.as_byte(), b'R');
    }

    #[test]
    fn test_change_type_roundtrip() {
        let types = [
            ChangeType::Added,
            ChangeType::Copied,
            ChangeType::Deleted,
            ChangeType::Modified,
            ChangeType::Renamed,
            ChangeType::TypeChanged,
            ChangeType::Unmerged,
            ChangeType::Unknown,
        ];

        for change_type in &types {
            let byte = change_type.as_byte();
            let parsed = ChangeType::from_byte(byte);
            assert_eq!(parsed, Some(*change_type));
        }
    }

    #[test]
    fn test_input_config_default() {
        let config = InputConfig::default();
        assert_eq!(config.diff_filter, "ACDMRTUX");
        assert_eq!(config.files_separator, "\n");
        assert!(!config.json);
        assert!(config.quotepath);
    }

    #[test]
    fn test_file_origin_default() {
        let origin = FileOrigin::default();
        assert!(!origin.in_current_changes);
        assert!(!origin.in_previous_failure);
        assert!(!origin.in_previous_success);
    }

    #[test]
    fn test_processed_result_from_unfiltered() {
        let diff = DiffResult {
            files: vec![
                ChangedFile {
                    path: InternedString(0),
                    change_type: ChangeType::Added,
                    previous_path: None,
                    is_symlink: false,
                    submodule_depth: 0,
                    origin: FileOrigin::default(),
                },
                ChangedFile {
                    path: InternedString(1),
                    change_type: ChangeType::Modified,
                    previous_path: None,
                    is_symlink: false,
                    submodule_depth: 0,
                    origin: FileOrigin::default(),
                },
            ],
            additions: 10,
            deletions: 5,
        };

        let result = ProcessedResult::from_unfiltered(diff);
        assert_eq!(result.all_files.len(), 2);
        assert_eq!(result.filtered_indices, vec![0, 1]);
        assert!(result.unmatched_indices.is_empty());
        assert!(!result.pattern_applied);
        assert_eq!(result.additions, 10);
        assert_eq!(result.deletions, 5);
    }

    #[test]
    fn test_processed_result_accessors() {
        let result = ProcessedResult {
            all_files: vec![
                ChangedFile {
                    path: InternedString(0),
                    change_type: ChangeType::Added,
                    previous_path: None,
                    is_symlink: false,
                    submodule_depth: 0,
                    origin: FileOrigin::default(),
                },
                ChangedFile {
                    path: InternedString(1),
                    change_type: ChangeType::Modified,
                    previous_path: None,
                    is_symlink: false,
                    submodule_depth: 0,
                    origin: FileOrigin::default(),
                },
                ChangedFile {
                    path: InternedString(2),
                    change_type: ChangeType::Deleted,
                    previous_path: None,
                    is_symlink: false,
                    submodule_depth: 0,
                    origin: FileOrigin::default(),
                },
            ],
            filtered_indices: vec![0, 2],
            unmatched_indices: vec![1],
            pattern_applied: true,
            group_results: Vec::new(),
            additions: 0,
            deletions: 0,
            diagnostics: Vec::new(),
            workflow_result: None,
            ci_decision: None,
            vanished_files: Vec::new(),
            base_sha: None,
            head_sha: None,
        };

        assert_eq!(result.matched_files().len(), 2);
        assert_eq!(result.other_files().len(), 1);
        assert_eq!(result.matched_files()[0].change_type, ChangeType::Added);
        assert_eq!(result.matched_files()[1].change_type, ChangeType::Deleted);
        assert_eq!(result.other_files()[0].change_type, ChangeType::Modified);
    }

    #[test]
    fn test_ci_decision_default() {
        let decision = CiDecision::default();
        assert!(decision.files_to_rebuild.is_empty());
        assert!(decision.files_to_skip.is_empty());
        assert!(decision.failed_jobs.is_empty());
        assert!(decision.successful_jobs.is_empty());
        assert!(decision.rebuild_reasons.is_empty());
    }

    #[test]
    fn test_failure_tracking_level_default() {
        let level = FailureTrackingLevel::default();
        assert_eq!(level, FailureTrackingLevel::Run);
    }

    #[test]
    fn test_failure_tracking_level_equality() {
        assert_eq!(FailureTrackingLevel::Run, FailureTrackingLevel::Run);
        assert_eq!(FailureTrackingLevel::Job, FailureTrackingLevel::Job);
        assert_ne!(FailureTrackingLevel::Run, FailureTrackingLevel::Job);
    }

    #[test]
    fn test_failure_tracking_level_copy() {
        let level = FailureTrackingLevel::Job;
        let copy = level; // Copy trait
        assert_eq!(level, copy);
    }

    #[test]
    fn test_input_config_failure_tracking_level() {
        let config = InputConfig::default();
        assert_eq!(config.failure_tracking_level, FailureTrackingLevel::Run);

        let config_job = InputConfig {
            failure_tracking_level: FailureTrackingLevel::Job,
            ..Default::default()
        };
        assert_eq!(config_job.failure_tracking_level, FailureTrackingLevel::Job);
    }

    #[test]
    fn test_workflow_failure_with_jobs() {
        let failure = WorkflowFailure {
            run: WorkflowRun {
                id: 1,
                name: InternedString(0),
                status: WorkflowStatus::Completed,
                conclusion: Some(WorkflowConclusion::Failure),
                branch: InternedString(1),
                head_sha: InternedString(2),
                created_at: 1000,
            },
            files: vec![InternedString(3)],
            failed_jobs: vec![WorkflowJob {
                id: 10,
                name: InternedString(4),
                status: WorkflowStatus::Completed,
                conclusion: Some(WorkflowConclusion::Failure),
                run_id: 1,
                started_at: 100,
                completed_at: 200,
            }],
        };

        assert_eq!(failure.run.id, 1);
        assert_eq!(failure.files.len(), 1);
        assert_eq!(failure.failed_jobs.len(), 1);
        assert_eq!(failure.failed_jobs[0].id, 10);
    }

    #[test]
    fn test_workflow_success_with_jobs() {
        let success = WorkflowSuccess {
            run: WorkflowRun {
                id: 2,
                name: InternedString(0),
                status: WorkflowStatus::Completed,
                conclusion: Some(WorkflowConclusion::Success),
                branch: InternedString(1),
                head_sha: InternedString(2),
                created_at: 2000,
            },
            jobs: vec![WorkflowJob {
                id: 20,
                name: InternedString(5),
                status: WorkflowStatus::Completed,
                conclusion: Some(WorkflowConclusion::Success),
                run_id: 2,
                started_at: 300,
                completed_at: 400,
            }],
            files: vec![InternedString(3), InternedString(4)],
        };

        assert_eq!(success.run.id, 2);
        assert_eq!(success.files.len(), 2);
        assert_eq!(success.jobs.len(), 1);
        assert_eq!(success.jobs[0].id, 20);
    }

    #[test]
    fn test_workflow_status_variants() {
        assert_eq!(WorkflowStatus::Queued, WorkflowStatus::Queued);
        assert_eq!(WorkflowStatus::InProgress, WorkflowStatus::InProgress);
        assert_eq!(WorkflowStatus::Completed, WorkflowStatus::Completed);
        assert_ne!(WorkflowStatus::Queued, WorkflowStatus::Completed);
    }

    #[test]
    fn test_workflow_conclusion_variants() {
        assert_eq!(WorkflowConclusion::Success, WorkflowConclusion::Success);
        assert_eq!(WorkflowConclusion::Failure, WorkflowConclusion::Failure);
        assert_eq!(WorkflowConclusion::Cancelled, WorkflowConclusion::Cancelled);
        assert_eq!(WorkflowConclusion::Skipped, WorkflowConclusion::Skipped);
        assert_eq!(WorkflowConclusion::TimedOut, WorkflowConclusion::TimedOut);
        assert_eq!(WorkflowConclusion::Neutral, WorkflowConclusion::Neutral);
        assert_ne!(WorkflowConclusion::Success, WorkflowConclusion::Failure);
    }

    #[test]
    fn test_group_deploy_action_equality() {
        assert_eq!(GroupDeployAction::Deploy, GroupDeployAction::Deploy);
        assert_eq!(GroupDeployAction::Skip, GroupDeployAction::Skip);
        assert_ne!(GroupDeployAction::Deploy, GroupDeployAction::Skip);
    }

    #[test]
    fn test_group_deploy_reason_equality() {
        assert_eq!(GroupDeployReason::NewChange, GroupDeployReason::NewChange);
        assert_eq!(
            GroupDeployReason::PreviousFailure,
            GroupDeployReason::PreviousFailure
        );
        assert_eq!(
            GroupDeployReason::BothNewAndFailed,
            GroupDeployReason::BothNewAndFailed
        );
        assert_ne!(
            GroupDeployReason::NewChange,
            GroupDeployReason::PreviousFailure
        );
    }

    #[test]
    fn test_group_deploy_decision_deploy() {
        use crate::interner::StringInterner;
        let interner = StringInterner::new();
        let prod_key = interner.intern("prod");

        let decision = GroupDeployDecision {
            key: prod_key,
            action: GroupDeployAction::Deploy,
            reason: Some(GroupDeployReason::NewChange),
            files_to_rebuild: vec![InternedString(0), InternedString(1)],
            files_to_skip: vec![],
            total_files: 2,
            concurrency_blocked: false,
            concurrency_blocked_by: 0,
            vanished_files: Vec::new(),
            reconstruct_sha: None,
        };
        assert_eq!(decision.action, GroupDeployAction::Deploy);
        assert_eq!(decision.reason, Some(GroupDeployReason::NewChange));
        assert_eq!(decision.files_to_rebuild.len(), 2);
        assert_eq!(decision.total_files, 2);
        assert!(!decision.concurrency_blocked);
        assert_eq!(decision.concurrency_blocked_by, 0);
    }

    #[test]
    fn test_group_deploy_decision_skip() {
        use crate::interner::StringInterner;
        let interner = StringInterner::new();
        let staging_key = interner.intern("staging");

        let decision = GroupDeployDecision {
            key: staging_key,
            action: GroupDeployAction::Skip,
            reason: None,
            files_to_rebuild: vec![],
            files_to_skip: vec![InternedString(0)],
            total_files: 1,
            concurrency_blocked: false,
            concurrency_blocked_by: 0,
            vanished_files: Vec::new(),
            reconstruct_sha: None,
        };
        assert_eq!(decision.action, GroupDeployAction::Skip);
        assert!(decision.reason.is_none());
        assert!(decision.files_to_rebuild.is_empty());
        assert_eq!(decision.files_to_skip.len(), 1);
    }

    #[test]
    fn test_workflow_run_is_copy() {
        let r = WorkflowRun {
            id: 1,
            name: InternedString(0),
            status: WorkflowStatus::Completed,
            conclusion: Some(WorkflowConclusion::Success),
            branch: InternedString(1),
            head_sha: InternedString(2),
            created_at: 1000,
        };
        let r2 = r; // Copy
        let _ = r; // still usable after "move" — Copy
        assert_eq!(r2.id, 1);
    }

    #[test]
    fn test_workflow_job_is_copy() {
        let j = WorkflowJob {
            id: 10,
            name: InternedString(0),
            status: WorkflowStatus::Completed,
            conclusion: Some(WorkflowConclusion::Failure),
            run_id: 1,
            started_at: 100,
            completed_at: 200,
        };
        let j2 = j; // Copy
        let _ = j; // still usable
        assert_eq!(j2.id, 10);
    }

    #[test]
    fn test_group_by_key_parse() {
        assert_eq!(GroupByKey::parse("name"), GroupByKey::Name);
        assert_eq!(GroupByKey::parse("path"), GroupByKey::Path);
        assert_eq!(GroupByKey::parse("hash"), GroupByKey::Hash);
        assert_eq!(GroupByKey::parse("PATH"), GroupByKey::Path);
        assert_eq!(GroupByKey::parse("HASH"), GroupByKey::Hash);
        assert_eq!(GroupByKey::parse("unknown"), GroupByKey::Name); // default
    }

    #[test]
    fn test_group_by_key_default() {
        assert_eq!(GroupByKey::default(), GroupByKey::Name);
    }

    #[test]
    fn test_input_config_debug_redacts_token() {
        let config = InputConfig {
            token: Some(std::borrow::Cow::Borrowed("ghp_SuperSecretToken12345")),
            ..Default::default()
        };
        let debug_output = format!("{:?}", config);
        assert!(
            !debug_output.contains("ghp_SuperSecretToken12345"),
            "Debug output must not contain the actual token value"
        );
        assert!(
            debug_output.contains("<redacted>"),
            "Debug output should show <redacted> for the token field"
        );
    }

    #[test]
    fn test_input_config_debug_no_token_shows_none() {
        let config = InputConfig::default();
        let debug_output = format!("{:?}", config);
        assert!(
            debug_output.contains("token: None"),
            "Debug output should show None when no token is set"
        );
        assert!(
            !debug_output.contains("<redacted>"),
            "Debug output should not show <redacted> when no token is set"
        );
    }
}