cflx 0.6.130

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
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
//! Apply and archive attempt history tracking module.
//!
//! This module provides in-memory tracking of apply and archive attempts per change,
//! allowing context injection for subsequent retry attempts.

use std::collections::HashMap;
use std::time::Duration;

/// Default number of tail lines to capture from stdout/stderr
const DEFAULT_TAIL_LINES: usize = 50;

/// Collects stdout/stderr output and captures the last N lines as a summary.
#[derive(Debug, Clone)]
pub struct OutputCollector {
    stdout_lines: Vec<String>,
    stderr_lines: Vec<String>,
    max_lines: usize,
}

impl OutputCollector {
    /// Create a new OutputCollector with default tail line count.
    pub fn new() -> Self {
        Self::with_max_lines(DEFAULT_TAIL_LINES)
    }

    /// Create a new OutputCollector with a specified maximum tail line count.
    pub fn with_max_lines(max_lines: usize) -> Self {
        Self {
            stdout_lines: Vec::new(),
            stderr_lines: Vec::new(),
            max_lines,
        }
    }

    /// Add a stdout line to the collector.
    pub fn add_stdout(&mut self, line: &str) {
        self.stdout_lines.push(line.to_string());
        // Keep only the last N lines to avoid unbounded memory growth
        if self.stdout_lines.len() > self.max_lines {
            self.stdout_lines.remove(0);
        }
    }

    /// Add a stderr line to the collector.
    pub fn add_stderr(&mut self, line: &str) {
        self.stderr_lines.push(line.to_string());
        // Keep only the last N lines to avoid unbounded memory growth
        if self.stderr_lines.len() > self.max_lines {
            self.stderr_lines.remove(0);
        }
    }

    /// Get the stdout tail summary as a single string.
    /// Returns None if no stdout was captured.
    pub fn stdout_tail(&self) -> Option<String> {
        if self.stdout_lines.is_empty() {
            None
        } else {
            Some(self.stdout_lines.join("\n"))
        }
    }

    /// Get the stderr tail summary as a single string.
    /// Returns None if no stderr was captured.
    pub fn stderr_tail(&self) -> Option<String> {
        if self.stderr_lines.is_empty() {
            None
        } else {
            Some(self.stderr_lines.join("\n"))
        }
    }
}

impl Default for OutputCollector {
    fn default() -> Self {
        Self::new()
    }
}

/// Summary of a single apply attempt
#[derive(Debug, Clone)]
pub struct ApplyAttempt {
    /// Attempt number (1-based)
    pub attempt: u32,
    /// Whether the attempt succeeded
    pub success: bool,
    /// Duration of the attempt
    pub duration: Duration,
    /// Error message if failed (None if success)
    pub error: Option<String>,
    /// Exit code if available
    pub exit_code: Option<i32>,
    /// Last N lines of stdout (tail summary)
    pub stdout_tail: Option<String>,
    /// Last N lines of stderr (tail summary)
    pub stderr_tail: Option<String>,
}

/// Tracks apply attempts per change
pub struct ApplyHistory {
    /// Map of change_id to list of attempts
    attempts: HashMap<String, Vec<ApplyAttempt>>,
}

impl ApplyHistory {
    /// Create a new empty ApplyHistory
    pub fn new() -> Self {
        Self {
            attempts: HashMap::new(),
        }
    }

    /// Record a new attempt for a change
    pub fn record(&mut self, change_id: &str, attempt: ApplyAttempt) {
        self.attempts
            .entry(change_id.to_string())
            .or_default()
            .push(attempt);
    }

    /// Get all attempts for a change
    #[allow(dead_code)]
    pub fn get(&self, change_id: &str) -> Option<&[ApplyAttempt]> {
        self.attempts.get(change_id).map(|v| v.as_slice())
    }

    /// Get the last attempt for a change
    #[allow(dead_code)]
    pub fn last(&self, change_id: &str) -> Option<&ApplyAttempt> {
        self.attempts.get(change_id).and_then(|v| v.last())
    }

    /// Get attempt count for a change
    pub fn count(&self, change_id: &str) -> u32 {
        self.attempts
            .get(change_id)
            .map(|v| v.len() as u32)
            .unwrap_or(0)
    }

    /// Clear history for a change (call on successful archive)
    #[allow(dead_code)]
    pub fn clear(&mut self, change_id: &str) {
        self.attempts.remove(change_id);
    }

    /// Format history as context string for prompt injection.
    /// Returns an empty string if there are no previous attempts.
    pub fn format_context(&self, change_id: &str) -> String {
        let Some(attempts) = self.attempts.get(change_id) else {
            return String::new();
        };

        if attempts.is_empty() {
            return String::new();
        }

        attempts
            .iter()
            .map(|a| {
                let status = if a.success { "success" } else { "failed" };
                let duration_secs = a.duration.as_secs();
                let error_line = match &a.error {
                    Some(e) => format!("\nerror: {}", e),
                    None => String::new(),
                };
                let exit_code_line = match a.exit_code {
                    Some(code) => format!("\nexit_code: {}", code),
                    None => String::new(),
                };
                let stdout_line = match &a.stdout_tail {
                    Some(s) if !s.is_empty() => format!("\nstdout_tail:\n{}", s),
                    _ => String::new(),
                };
                let stderr_line = match &a.stderr_tail {
                    Some(s) if !s.is_empty() => format!("\nstderr_tail:\n{}", s),
                    _ => String::new(),
                };

                format!(
                    "<last_apply attempt=\"{}\">\nstatus: {}\nduration: {}s{}{}{}{}\n</last_apply>",
                    a.attempt,
                    status,
                    duration_secs,
                    error_line,
                    exit_code_line,
                    stdout_line,
                    stderr_line
                )
            })
            .collect::<Vec<_>>()
            .join("\n\n")
    }
}

impl Default for ApplyHistory {
    fn default() -> Self {
        Self::new()
    }
}

/// Primary reason taxonomy for archive retry/resume contexts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArchivePrimaryReason {
    CommandFailed,
    PrerequisiteBlocker,
    VerificationFailed,
    PostArchiveCompletionFailed,
    Stalled,
    ResumedContextOnly,
}

impl ArchivePrimaryReason {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::CommandFailed => "command_failed",
            Self::PrerequisiteBlocker => "prerequisite_blocker",
            Self::VerificationFailed => "verification_failed",
            Self::PostArchiveCompletionFailed => "post_archive_completion_failed",
            Self::Stalled => "stalled",
            Self::ResumedContextOnly => "resumed_context_only",
        }
    }
}

/// Summary of a single archive attempt
#[derive(Debug, Clone)]
pub struct ArchiveAttempt {
    /// Attempt number (1-based)
    pub attempt: u32,
    /// Whether the attempt succeeded
    pub success: bool,
    /// Duration of the attempt
    pub duration: Duration,
    /// Error message if failed (None if success)
    pub error: Option<String>,
    /// Primary failure reason if available
    pub primary_reason: Option<ArchivePrimaryReason>,
    /// Verification result (e.g., reason why NotArchived)
    pub verification_result: Option<String>,
    /// Exit code if available
    pub exit_code: Option<i32>,
    /// Last N lines of stdout (tail summary)
    pub stdout_tail: Option<String>,
    /// Last N lines of stderr (tail summary)
    pub stderr_tail: Option<String>,
}

/// Tracks archive attempts per change
pub struct ArchiveHistory {
    /// Map of change_id to list of attempts
    attempts: HashMap<String, Vec<ArchiveAttempt>>,
}

impl ArchiveHistory {
    /// Create a new empty ArchiveHistory
    pub fn new() -> Self {
        Self {
            attempts: HashMap::new(),
        }
    }

    /// Record a new attempt for a change
    pub fn record(&mut self, change_id: &str, attempt: ArchiveAttempt) {
        self.attempts
            .entry(change_id.to_string())
            .or_default()
            .push(attempt);
    }

    /// Get all attempts for a change
    #[allow(dead_code)]
    pub fn get(&self, change_id: &str) -> Option<&[ArchiveAttempt]> {
        self.attempts.get(change_id).map(|v| v.as_slice())
    }

    /// Get attempt count for a change
    pub fn count(&self, change_id: &str) -> u32 {
        self.attempts
            .get(change_id)
            .map(|v| v.len() as u32)
            .unwrap_or(0)
    }

    /// Clear history for a change (call on successful archive)
    pub fn clear(&mut self, change_id: &str) {
        self.attempts.remove(change_id);
    }

    /// Format history as context string for prompt injection.
    /// Returns an empty string if there are no previous attempts.
    pub fn format_context(&self, change_id: &str) -> String {
        let Some(attempts) = self.attempts.get(change_id) else {
            return String::new();
        };

        if attempts.is_empty() {
            return String::new();
        }

        attempts
            .iter()
            .map(|a| {
                let status = if a.success { "success" } else { "failed" };
                let duration_secs = a.duration.as_secs();
                let error_line = match &a.error {
                    Some(e) => format!("\nerror: {}", e),
                    None => String::new(),
                };
                let reason_line = match a.primary_reason {
                    Some(reason) => format!("\nprimary_reason: {}", reason.as_str()),
                    None => String::new(),
                };
                let verification_line = match &a.verification_result {
                    Some(v) => format!("\nverification_result: {}", v),
                    None => String::new(),
                };
                let exit_code_line = match a.exit_code {
                    Some(code) => format!("\nexit_code: {}", code),
                    None => String::new(),
                };
                let stdout_line = match &a.stdout_tail {
                    Some(s) if !s.is_empty() => format!("\nstdout_tail:\n{}", s),
                    _ => String::new(),
                };
                let stderr_line = match &a.stderr_tail {
                    Some(s) if !s.is_empty() => format!("\nstderr_tail:\n{}", s),
                    _ => String::new(),
                };

                format!(
                    "<last_archive attempt=\"{}\">\nstatus: {}\nduration: {}s{}{}{}{}{}{}\n</last_archive>",
                    a.attempt,
                    status,
                    duration_secs,
                    error_line,
                    reason_line,
                    verification_line,
                    exit_code_line,
                    stdout_line,
                    stderr_line
                )
            })
            .collect::<Vec<_>>()
            .join("\n\n")
    }
}

impl Default for ArchiveHistory {
    fn default() -> Self {
        Self::new()
    }
}

/// Summary of a single acceptance attempt
#[derive(Debug, Clone)]
pub struct AcceptanceAttempt {
    /// Attempt number (1-based)
    pub attempt: u32,
    /// Whether the acceptance passed
    pub passed: bool,
    /// Duration of the attempt
    pub duration: Duration,
    /// Findings if failed (None if passed)
    pub findings: Option<Vec<String>>,
    /// Exit code if available
    pub exit_code: Option<i32>,
    /// Last N lines of stdout (tail summary)
    pub stdout_tail: Option<String>,
    /// Last N lines of stderr (tail summary)
    pub stderr_tail: Option<String>,
    /// Commit hash at the time of this acceptance check (for diff calculation)
    pub commit_hash: Option<String>,
}

/// Tracks acceptance attempts per change
pub struct AcceptanceHistory {
    /// Map of change_id to list of attempts
    attempts: HashMap<String, Vec<AcceptanceAttempt>>,
}

impl AcceptanceHistory {
    /// Create a new empty AcceptanceHistory
    pub fn new() -> Self {
        Self {
            attempts: HashMap::new(),
        }
    }

    /// Record a new attempt for a change
    pub fn record(&mut self, change_id: &str, attempt: AcceptanceAttempt) {
        self.attempts
            .entry(change_id.to_string())
            .or_default()
            .push(attempt);
    }

    /// Get all attempts for a change
    #[allow(dead_code)]
    pub fn get(&self, change_id: &str) -> Option<&[AcceptanceAttempt]> {
        self.attempts.get(change_id).map(|v| v.as_slice())
    }

    /// Get attempt count for a change
    pub fn count(&self, change_id: &str) -> u32 {
        self.attempts
            .get(change_id)
            .map(|v| v.len() as u32)
            .unwrap_or(0)
    }

    /// Clear history for a change (call on successful archive)
    pub fn clear(&mut self, change_id: &str) {
        self.attempts.remove(change_id);
    }

    /// Count consecutive CONTINUE attempts from the end of the history.
    /// A CONTINUE attempt is detected by checking if findings contain "Investigation incomplete - continue later".
    pub fn count_consecutive_continues(&self, change_id: &str) -> u32 {
        let Some(attempts) = self.attempts.get(change_id) else {
            return 0;
        };

        attempts
            .iter()
            .rev()
            .take_while(|a| {
                a.findings
                    .as_ref()
                    .and_then(|f| f.first())
                    .map(|s| s.contains("Investigation incomplete - continue later"))
                    .unwrap_or(false)
            })
            .count() as u32
    }

    /// Get the last commit hash from the most recent acceptance attempt.
    /// Returns None if there are no previous attempts or the last attempt has no commit hash.
    pub fn last_commit_hash(&self, change_id: &str) -> Option<String> {
        self.attempts
            .get(change_id)
            .and_then(|v| v.last())
            .and_then(|a| a.commit_hash.clone())
    }

    /// Get the last findings from the most recent acceptance attempt.
    /// Returns None if there are no previous attempts or the last attempt has no findings.
    pub fn last_findings(&self, change_id: &str) -> Option<Vec<String>> {
        self.attempts
            .get(change_id)
            .and_then(|v| v.last())
            .and_then(|a| a.findings.clone())
    }

    /// Get the last acceptance attempt for a change.
    /// Returns None if there are no previous attempts.
    #[allow(dead_code)] // Reserved for future direct use
    pub fn get_last_attempt(&self, change_id: &str) -> Option<&AcceptanceAttempt> {
        self.attempts.get(change_id).and_then(|v| v.last())
    }

    /// Get the last stdout tail from the most recent acceptance attempt.
    /// Returns None if there are no previous attempts or the last attempt has no stdout tail.
    pub fn last_stdout_tail(&self, change_id: &str) -> Option<String> {
        self.attempts
            .get(change_id)
            .and_then(|v| v.last())
            .and_then(|a| a.stdout_tail.clone())
    }

    /// Get the last stderr tail from the most recent acceptance attempt.
    /// Returns None if there are no previous attempts or the last attempt has no stderr tail.
    pub fn last_stderr_tail(&self, change_id: &str) -> Option<String> {
        self.attempts
            .get(change_id)
            .and_then(|v| v.last())
            .and_then(|a| a.stderr_tail.clone())
    }

    /// Format history as context string for prompt injection.
    /// Returns an empty string if there are no previous attempts.
    pub fn format_context(&self, change_id: &str) -> String {
        let Some(attempts) = self.attempts.get(change_id) else {
            return String::new();
        };

        if attempts.is_empty() {
            return String::new();
        }

        attempts
            .iter()
            .map(|a| {
                let status = if a.passed { "passed" } else { "failed" };
                let duration_secs = a.duration.as_secs();
                let findings_line = match &a.findings {
                    Some(f) if !f.is_empty() => {
                        let findings_text = f
                            .iter()
                            .map(|finding| format!("  - {}", finding))
                            .collect::<Vec<_>>()
                            .join("\n");
                        format!("\nfindings:\n{}", findings_text)
                    }
                    _ => String::new(),
                };
                let exit_code_line = match a.exit_code {
                    Some(code) => format!("\nexit_code: {}", code),
                    None => String::new(),
                };
                let stdout_line = match &a.stdout_tail {
                    Some(s) if !s.is_empty() => format!("\nstdout_tail:\n{}", s),
                    _ => String::new(),
                };
                let stderr_line = match &a.stderr_tail {
                    Some(s) if !s.is_empty() => format!("\nstderr_tail:\n{}", s),
                    _ => String::new(),
                };

                format!(
                    "<last_acceptance attempt=\"{}\">\nstatus: {}\nduration: {}s{}{}{}{}\n</last_acceptance>",
                    a.attempt, status, duration_secs, findings_line, exit_code_line, stdout_line, stderr_line
                )
            })
            .collect::<Vec<_>>()
            .join("\n\n")
    }
}

impl Default for AcceptanceHistory {
    fn default() -> Self {
        Self::new()
    }
}

/// Summary of a single resolve attempt
#[derive(Debug, Clone)]
pub struct ResolveAttempt {
    /// Attempt number (1-based)
    pub attempt: u32,
    /// Whether the command exited successfully
    pub command_success: bool,
    /// Whether verification passed
    pub verification_success: bool,
    /// Duration of the attempt
    pub duration: Duration,
    /// Reason why the resolve needs to continue (verification failure reason)
    pub continuation_reason: Option<String>,
    /// Exit code if available
    pub exit_code: Option<i32>,
    /// Last N lines of stdout (tail summary)
    pub stdout_tail: Option<String>,
    /// Last N lines of stderr (tail summary)
    pub stderr_tail: Option<String>,
}

/// Tracks resolve attempts within a single retry session
pub struct ResolveContext {
    /// Attempts in the current session
    attempts: Vec<ResolveAttempt>,
    /// Maximum number of retries
    max_retries: u32,
}

impl ResolveContext {
    /// Create a new resolve context for a retry session
    pub fn new(max_retries: u32) -> Self {
        Self {
            attempts: Vec::new(),
            max_retries,
        }
    }

    /// Record a new attempt
    pub fn record(&mut self, attempt: ResolveAttempt) {
        self.attempts.push(attempt);
    }

    /// Get the current attempt number (1-based)
    pub fn current_attempt(&self) -> u32 {
        (self.attempts.len() as u32) + 1
    }

    /// Format continuation context for prompt injection.
    /// Returns an empty string if there are no previous attempts.
    pub fn format_continuation_context(&self) -> String {
        if self.attempts.is_empty() {
            return String::new();
        }

        let mut lines = vec![
            format!(
                "This is attempt {} of {} for conflict resolution.",
                self.current_attempt(),
                self.max_retries
            ),
            String::new(),
        ];

        for attempt in &self.attempts {
            let command_exit = if attempt.command_success {
                format!("success (code: {})", attempt.exit_code.unwrap_or(0))
            } else {
                format!("failed (code: {})", attempt.exit_code.unwrap_or(-1))
            };
            let verification = if attempt.verification_success {
                "passed"
            } else {
                "failed"
            };
            let duration_secs = attempt.duration.as_secs();

            lines.push(format!("Previous attempt ({}):", attempt.attempt));
            lines.push(format!("- Command exit: {}", command_exit));
            lines.push(format!("- Verification: {}", verification));
            if let Some(reason) = &attempt.continuation_reason {
                lines.push(format!("- Reason: {}", reason));
            }
            lines.push(format!("- Duration: {}s", duration_secs));
            if let Some(stdout) = &attempt.stdout_tail {
                if !stdout.is_empty() {
                    lines.push("- Stdout tail:".to_string());
                    lines.push(format!("  {}", stdout.replace('\n', "\n  ")));
                }
            }
            if let Some(stderr) = &attempt.stderr_tail {
                if !stderr.is_empty() {
                    lines.push("- Stderr tail:".to_string());
                    lines.push(format!("  {}", stderr.replace('\n', "\n  ")));
                }
            }
            lines.push(String::new());
        }

        if let Some(last) = self.attempts.last() {
            if let Some(reason) = &last.continuation_reason {
                lines.push(format!("Continue resolving the conflicts. {}", reason));
            } else {
                lines.push("Continue resolving the conflicts.".to_string());
            }
        }

        format!(
            "<resolve_context>\n{}\n</resolve_context>",
            lines.join("\n")
        )
    }
}

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

    fn create_test_attempt(attempt: u32, success: bool, duration_secs: u64) -> ApplyAttempt {
        ApplyAttempt {
            attempt,
            success,
            duration: Duration::from_secs(duration_secs),
            error: if success {
                None
            } else {
                Some("Test error".to_string())
            },
            exit_code: if success { Some(0) } else { Some(1) },
            stdout_tail: None,
            stderr_tail: None,
        }
    }

    #[test]
    fn test_new_history_is_empty() {
        let history = ApplyHistory::new();
        assert!(history.get("any-change").is_none());
        assert_eq!(history.count("any-change"), 0);
    }

    #[test]
    fn test_record_and_retrieve() {
        let mut history = ApplyHistory::new();
        let attempt = create_test_attempt(1, false, 30);

        history.record("change-a", attempt);

        assert_eq!(history.count("change-a"), 1);
        let attempts = history.get("change-a").unwrap();
        assert_eq!(attempts.len(), 1);
        assert_eq!(attempts[0].attempt, 1);
        assert!(!attempts[0].success);
    }

    #[test]
    fn test_multiple_attempts_accumulation() {
        let mut history = ApplyHistory::new();

        history.record("change-a", create_test_attempt(1, false, 30));
        history.record("change-a", create_test_attempt(2, false, 45));
        history.record("change-a", create_test_attempt(3, true, 60));

        assert_eq!(history.count("change-a"), 3);

        let attempts = history.get("change-a").unwrap();
        assert_eq!(attempts[0].attempt, 1);
        assert_eq!(attempts[1].attempt, 2);
        assert_eq!(attempts[2].attempt, 3);

        let last = history.last("change-a").unwrap();
        assert_eq!(last.attempt, 3);
        assert!(last.success);
    }

    #[test]
    fn test_separate_changes_tracked_independently() {
        let mut history = ApplyHistory::new();

        history.record("change-a", create_test_attempt(1, false, 30));
        history.record("change-b", create_test_attempt(1, true, 20));
        history.record("change-a", create_test_attempt(2, true, 40));

        assert_eq!(history.count("change-a"), 2);
        assert_eq!(history.count("change-b"), 1);
    }

    #[test]
    fn test_clear_functionality() {
        let mut history = ApplyHistory::new();

        history.record("change-a", create_test_attempt(1, false, 30));
        history.record("change-a", create_test_attempt(2, true, 45));
        history.record("change-b", create_test_attempt(1, true, 20));

        assert_eq!(history.count("change-a"), 2);

        history.clear("change-a");

        assert_eq!(history.count("change-a"), 0);
        assert!(history.get("change-a").is_none());
        // change-b should be unaffected
        assert_eq!(history.count("change-b"), 1);
    }

    #[test]
    fn test_format_context_empty_history() {
        let history = ApplyHistory::new();
        let context = history.format_context("change-a");
        assert!(context.is_empty());
    }

    #[test]
    fn test_format_context_single_failed_attempt() {
        let mut history = ApplyHistory::new();
        history.record(
            "change-a",
            ApplyAttempt {
                attempt: 1,
                success: false,
                duration: Duration::from_secs(45),
                error: Some("Type error in auth.rs:42".to_string()),
                exit_code: Some(1),
                stdout_tail: None,
                stderr_tail: None,
            },
        );

        let context = history.format_context("change-a");

        assert!(context.contains("<last_apply attempt=\"1\">"));
        assert!(context.contains("status: failed"));
        assert!(context.contains("duration: 45s"));
        assert!(context.contains("error: Type error in auth.rs:42"));
        assert!(context.contains("exit_code: 1"));
        assert!(context.contains("</last_apply>"));
    }

    #[test]
    fn test_format_context_successful_attempt() {
        let mut history = ApplyHistory::new();
        history.record(
            "change-a",
            ApplyAttempt {
                attempt: 1,
                success: true,
                duration: Duration::from_secs(30),
                error: None,
                exit_code: Some(0),
                stdout_tail: None,
                stderr_tail: None,
            },
        );

        let context = history.format_context("change-a");

        assert!(context.contains("status: success"));
        assert!(!context.contains("error:"));
        assert!(context.contains("exit_code: 0"));
    }

    #[test]
    fn test_format_context_multiple_attempts() {
        let mut history = ApplyHistory::new();
        history.record(
            "change-a",
            ApplyAttempt {
                attempt: 1,
                success: false,
                duration: Duration::from_secs(30),
                error: Some("Missing dependency".to_string()),
                exit_code: Some(1),
                stdout_tail: None,
                stderr_tail: None,
            },
        );
        history.record(
            "change-a",
            ApplyAttempt {
                attempt: 2,
                success: false,
                duration: Duration::from_secs(45),
                error: Some("Type error".to_string()),
                exit_code: Some(1),
                stdout_tail: None,
                stderr_tail: None,
            },
        );

        let context = history.format_context("change-a");

        // Should contain both attempts
        assert!(context.contains("<last_apply attempt=\"1\">"));
        assert!(context.contains("<last_apply attempt=\"2\">"));
        assert!(context.contains("Missing dependency"));
        assert!(context.contains("Type error"));
    }

    #[test]
    fn test_last_returns_none_for_unknown_change() {
        let history = ApplyHistory::new();
        assert!(history.last("unknown").is_none());
    }

    #[test]
    fn test_default_impl() {
        let history = ApplyHistory::default();
        assert_eq!(history.count("any"), 0);
    }

    // ArchiveHistory tests
    fn create_test_archive_attempt(
        attempt: u32,
        success: bool,
        duration_secs: u64,
        verification_result: Option<String>,
    ) -> ArchiveAttempt {
        ArchiveAttempt {
            attempt,
            success,
            duration: Duration::from_secs(duration_secs),
            error: if success {
                None
            } else {
                Some("Archive verification failed".to_string())
            },
            primary_reason: if success {
                None
            } else {
                Some(ArchivePrimaryReason::VerificationFailed)
            },
            verification_result,
            exit_code: if success { Some(0) } else { Some(1) },
            stdout_tail: None,
            stderr_tail: None,
        }
    }

    #[test]
    fn test_archive_history_new() {
        let history = ArchiveHistory::new();
        assert!(history.get("any-change").is_none());
        assert_eq!(history.count("any-change"), 0);
    }

    #[test]
    fn test_archive_history_record_and_retrieve() {
        let mut history = ArchiveHistory::new();
        let attempt = create_test_archive_attempt(
            1,
            false,
            5,
            Some("Change still exists at openspec/changes/my-change".to_string()),
        );

        history.record("change-a", attempt);

        assert_eq!(history.count("change-a"), 1);
        let attempts = history.get("change-a").unwrap();
        assert_eq!(attempts.len(), 1);
        assert_eq!(attempts[0].attempt, 1);
        assert!(!attempts[0].success);
    }

    #[test]
    fn test_archive_history_multiple_attempts() {
        let mut history = ArchiveHistory::new();

        history.record(
            "change-a",
            create_test_archive_attempt(1, false, 5, Some("Change not archived".to_string())),
        );
        history.record(
            "change-a",
            create_test_archive_attempt(2, false, 6, Some("Change not archived".to_string())),
        );
        history.record("change-a", create_test_archive_attempt(3, true, 7, None));

        assert_eq!(history.count("change-a"), 3);
    }

    #[test]
    fn test_archive_history_clear() {
        let mut history = ArchiveHistory::new();

        history.record(
            "change-a",
            create_test_archive_attempt(1, false, 5, Some("Not archived".to_string())),
        );
        history.record("change-b", create_test_archive_attempt(1, true, 5, None));

        assert_eq!(history.count("change-a"), 1);

        history.clear("change-a");

        assert_eq!(history.count("change-a"), 0);
        assert!(history.get("change-a").is_none());
        // change-b should be unaffected
        assert_eq!(history.count("change-b"), 1);
    }

    #[test]
    fn test_archive_history_format_context_empty() {
        let history = ArchiveHistory::new();
        let context = history.format_context("change-a");
        assert!(context.is_empty());
    }

    #[test]
    fn test_archive_history_format_context_single_attempt() {
        let mut history = ArchiveHistory::new();
        history.record(
            "change-a",
            ArchiveAttempt {
                attempt: 1,
                success: false,
                duration: Duration::from_secs(5),
                error: Some("Archive command succeeded but verification failed".to_string()),
                primary_reason: Some(ArchivePrimaryReason::VerificationFailed),
                verification_result: Some(
                    "Change still exists at openspec/changes/my-change".to_string(),
                ),
                exit_code: Some(0),
                stdout_tail: None,
                stderr_tail: None,
            },
        );

        let context = history.format_context("change-a");

        assert!(context.contains("<last_archive attempt=\"1\">"));
        assert!(context.contains("status: failed"));
        assert!(context.contains("duration: 5s"));
        assert!(context.contains("error: Archive command succeeded but verification failed"));
        assert!(context.contains("verification_result: Change still exists"));
        assert!(context.contains("exit_code: 0"));
        assert!(context.contains("</last_archive>"));
    }

    #[test]
    fn test_archive_history_format_context_multiple_attempts() {
        let mut history = ArchiveHistory::new();
        history.record(
            "change-a",
            ArchiveAttempt {
                attempt: 1,
                success: false,
                duration: Duration::from_secs(5),
                error: Some("Verification failed".to_string()),
                primary_reason: Some(ArchivePrimaryReason::VerificationFailed),
                verification_result: Some("Change not moved".to_string()),
                exit_code: Some(0),
                stdout_tail: None,
                stderr_tail: None,
            },
        );
        history.record(
            "change-a",
            ArchiveAttempt {
                attempt: 2,
                success: false,
                duration: Duration::from_secs(6),
                error: Some("Still not archived".to_string()),
                primary_reason: Some(ArchivePrimaryReason::VerificationFailed),
                verification_result: Some("Change still exists".to_string()),
                exit_code: Some(0),
                stdout_tail: None,
                stderr_tail: None,
            },
        );

        let context = history.format_context("change-a");

        // Should contain both attempts
        assert!(context.contains("<last_archive attempt=\"1\">"));
        assert!(context.contains("<last_archive attempt=\"2\">"));
        assert!(context.contains("Change not moved"));
        assert!(context.contains("Change still exists"));
    }

    #[test]
    fn test_archive_history_default() {
        let history = ArchiveHistory::default();
        assert_eq!(history.count("any"), 0);
    }

    // ResolveContext tests
    #[test]
    fn test_resolve_context_new() {
        let context = ResolveContext::new(3);
        assert_eq!(context.current_attempt(), 1);
        assert!(context.format_continuation_context().is_empty());
    }

    #[test]
    fn test_resolve_context_record() {
        let mut context = ResolveContext::new(3);

        context.record(ResolveAttempt {
            attempt: 1,
            command_success: true,
            verification_success: false,
            duration: Duration::from_secs(45),
            continuation_reason: Some(
                "Conflicts still present after resolution attempt: src/main.rs".to_string(),
            ),
            exit_code: Some(0),
            stdout_tail: None,
            stderr_tail: None,
        });

        assert_eq!(context.current_attempt(), 2);
    }

    #[test]
    fn test_resolve_context_format_continuation() {
        let mut context = ResolveContext::new(3);

        context.record(ResolveAttempt {
            attempt: 1,
            command_success: true,
            verification_success: false,
            duration: Duration::from_secs(45),
            continuation_reason: Some(
                "Conflicts still present after resolution attempt: src/main.rs, src/lib.rs"
                    .to_string(),
            ),
            exit_code: Some(0),
            stdout_tail: None,
            stderr_tail: None,
        });

        let formatted = context.format_continuation_context();

        assert!(formatted.contains("<resolve_context>"));
        assert!(formatted.contains("This is attempt 2 of 3 for conflict resolution"));
        assert!(formatted.contains("Previous attempt (1):"));
        assert!(formatted.contains("Command exit: success (code: 0)"));
        assert!(formatted.contains("Verification: failed"));
        assert!(formatted.contains("Reason: Conflicts still present"));
        assert!(formatted.contains("Duration: 45s"));
        assert!(formatted.contains("Continue resolving the conflicts"));
        assert!(formatted.contains("</resolve_context>"));
    }

    #[test]
    fn test_resolve_context_multiple_attempts() {
        let mut context = ResolveContext::new(5);

        context.record(ResolveAttempt {
            attempt: 1,
            command_success: true,
            verification_success: false,
            duration: Duration::from_secs(30),
            continuation_reason: Some("Conflict markers remain".to_string()),
            exit_code: Some(0),
            stdout_tail: None,
            stderr_tail: None,
        });

        context.record(ResolveAttempt {
            attempt: 2,
            command_success: true,
            verification_success: false,
            duration: Duration::from_secs(40),
            continuation_reason: Some("MERGE_HEAD still exists".to_string()),
            exit_code: Some(0),
            stdout_tail: None,
            stderr_tail: None,
        });

        let formatted = context.format_continuation_context();

        assert!(formatted.contains("This is attempt 3 of 5"));
        assert!(formatted.contains("Previous attempt (1):"));
        assert!(formatted.contains("Previous attempt (2):"));
        assert!(formatted.contains("Conflict markers remain"));
        assert!(formatted.contains("MERGE_HEAD still exists"));
    }

    // OutputCollector tests
    #[test]
    fn test_output_collector_new() {
        let collector = OutputCollector::new();
        assert!(collector.stdout_tail().is_none());
        assert!(collector.stderr_tail().is_none());
    }

    #[test]
    fn test_output_collector_add_stdout() {
        let mut collector = OutputCollector::new();
        collector.add_stdout("line 1");
        collector.add_stdout("line 2");

        let stdout = collector.stdout_tail().unwrap();
        assert_eq!(stdout, "line 1\nline 2");
    }

    #[test]
    fn test_output_collector_add_stderr() {
        let mut collector = OutputCollector::new();
        collector.add_stderr("error 1");
        collector.add_stderr("error 2");

        let stderr = collector.stderr_tail().unwrap();
        assert_eq!(stderr, "error 1\nerror 2");
    }

    #[test]
    fn test_output_collector_max_lines() {
        let mut collector = OutputCollector::with_max_lines(3);
        collector.add_stdout("line 1");
        collector.add_stdout("line 2");
        collector.add_stdout("line 3");
        collector.add_stdout("line 4");
        collector.add_stdout("line 5");

        let stdout = collector.stdout_tail().unwrap();
        assert_eq!(stdout, "line 3\nline 4\nline 5");
        assert!(!stdout.contains("line 1"));
        assert!(!stdout.contains("line 2"));
    }

    #[test]
    fn test_output_collector_default() {
        let collector = OutputCollector::default();
        assert!(collector.stdout_tail().is_none());
        assert!(collector.stderr_tail().is_none());
    }

    // AcceptanceHistory tests
    #[test]
    fn test_acceptance_history_last_commit_hash() {
        let mut history = AcceptanceHistory::new();

        // No history - should return None
        assert!(history.last_commit_hash("change-a").is_none());

        // Add attempt with commit hash
        history.record(
            "change-a",
            AcceptanceAttempt {
                attempt: 1,
                passed: false,
                duration: Duration::from_secs(30),
                findings: Some(vec!["Issue 1".to_string()]),
                exit_code: Some(1),
                stdout_tail: None,
                stderr_tail: None,
                commit_hash: Some("abc123".to_string()),
            },
        );

        // Should return the commit hash
        assert_eq!(
            history.last_commit_hash("change-a"),
            Some("abc123".to_string())
        );

        // Add another attempt with different commit hash
        history.record(
            "change-a",
            AcceptanceAttempt {
                attempt: 2,
                passed: true,
                duration: Duration::from_secs(45),
                findings: None,
                exit_code: Some(0),
                stdout_tail: None,
                stderr_tail: None,
                commit_hash: Some("def456".to_string()),
            },
        );

        // Should return the last commit hash
        assert_eq!(
            history.last_commit_hash("change-a"),
            Some("def456".to_string())
        );
    }

    #[test]
    fn test_acceptance_history_last_commit_hash_none() {
        let mut history = AcceptanceHistory::new();

        // Add attempt without commit hash
        history.record(
            "change-a",
            AcceptanceAttempt {
                attempt: 1,
                passed: false,
                duration: Duration::from_secs(30),
                findings: Some(vec!["Issue 1".to_string()]),
                exit_code: Some(1),
                stdout_tail: None,
                stderr_tail: None,
                commit_hash: None,
            },
        );

        // Should return None
        assert!(history.last_commit_hash("change-a").is_none());
    }

    #[test]
    fn test_acceptance_history_last_findings() {
        let mut history = AcceptanceHistory::new();

        // No history - should return None
        assert!(history.last_findings("change-a").is_none());

        // Add attempt with findings
        let findings1 = vec!["Issue 1".to_string(), "Issue 2".to_string()];
        history.record(
            "change-a",
            AcceptanceAttempt {
                attempt: 1,
                passed: false,
                duration: Duration::from_secs(30),
                findings: Some(findings1.clone()),
                exit_code: Some(1),
                stdout_tail: None,
                stderr_tail: None,
                commit_hash: Some("abc123".to_string()),
            },
        );

        // Should return the findings
        assert_eq!(history.last_findings("change-a"), Some(findings1));

        // Add another attempt with different findings
        let findings2 = vec!["Fixed issue 1".to_string()];
        history.record(
            "change-a",
            AcceptanceAttempt {
                attempt: 2,
                passed: false,
                duration: Duration::from_secs(45),
                findings: Some(findings2.clone()),
                exit_code: Some(1),
                stdout_tail: None,
                stderr_tail: None,
                commit_hash: Some("def456".to_string()),
            },
        );

        // Should return the last findings
        assert_eq!(history.last_findings("change-a"), Some(findings2));

        // Add passed attempt with no findings
        history.record(
            "change-a",
            AcceptanceAttempt {
                attempt: 3,
                passed: true,
                duration: Duration::from_secs(50),
                findings: None,
                exit_code: Some(0),
                stdout_tail: None,
                stderr_tail: None,
                commit_hash: Some("ghi789".to_string()),
            },
        );

        // Should return None (last attempt has no findings)
        assert!(history.last_findings("change-a").is_none());
    }
}