cflx 0.6.189

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
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
1501
//! Shared acceptance operations for CLI and TUI modes.
//!
//! Provides acceptance test execution after apply and before archive.

#![allow(dead_code)]

use crate::agent::AgentRunner;
use crate::error::{OrchestratorError, Result};
use crate::history::{AcceptanceAttempt, OutputCollector};
use crate::openspec::Change;
use tracing::{info, warn};

use super::output::OutputHandler;

const ACCEPTANCE_OUTPUT_FALLBACK: &str = "No acceptance output captured";
pub const MAX_ACCEPTANCE_RETRY_CYCLES: u32 = 10;

/// First history/finding line recorded when an acceptance command completes
/// without emitting any canonical verdict. Deliberately distinct from the
/// explicit-CONTINUE marker ("Investigation incomplete - continue later") so
/// missing-verdict attempts never count toward the consecutive-CONTINUE retry
/// budget.
pub const MISSING_VERDICT_DIAGNOSTIC: &str = "Missing acceptance verdict: acceptance command \
     exited without emitting a canonical verdict (protocol failure; status-only or waiting \
     output is not a verdict)";

/// Maximum number of acceptance protocol retries permitted after the initial
/// missing-verdict attempt. The initial invocation plus these retries gives
/// three opportunities to satisfy the verdict protocol.
///
/// This budget is deliberately separate from the configured explicit-`CONTINUE`
/// budget (`acceptance_max_continues`): a completed-but-verdictless command is a
/// protocol failure, not an intentional continuation request.
pub const MAX_MISSING_VERDICT_RETRIES: u32 = 2;

/// Marks an acceptance invocation as a missing-verdict protocol retry so the
/// prompt builder can inject the corrective continuation context.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MissingVerdictRetry {
    /// 1-based retry index (the first retry after the initial attempt is 1).
    pub attempt: u32,
    /// Maximum number of retries permitted after the initial attempt.
    pub max: u32,
}

/// Routing decision for a completed acceptance command that emitted no
/// canonical verdict.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingVerdictRetryDecision {
    /// Budget remains: re-invoke the normal configured acceptance command with
    /// the continuation context described by [`MissingVerdictRetry`].
    Retry(MissingVerdictRetry),
    /// Budget exhausted: route to the terminal missing-verdict protocol failure.
    Exhausted { attempts: u32, max: u32 },
}

/// Consecutive missing-verdict accounting for a single active orchestration run.
///
/// Per `openspec/CONSTITUTION.md` this is active-run memory only. It is never
/// persisted outside the worktree, so a process restart simply re-runs
/// acceptance for an applied-but-unarchived workspace instead of inferring a
/// verdict from prior narrative output.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MissingVerdictRetryState {
    consecutive: u32,
}

impl MissingVerdictRetryState {
    /// Number of consecutive missing verdicts observed so far.
    pub fn consecutive(&self) -> u32 {
        self.consecutive
    }

    /// Record any canonical verdict (PASS/FAIL/CONTINUE/GATED/stalled-hold).
    ///
    /// Canonical routing is unchanged; only the protocol counter resets.
    pub fn record_canonical_verdict(&mut self) {
        self.consecutive = 0;
    }

    /// Record one completed acceptance command that emitted no canonical
    /// verdict and return the resulting routing decision.
    pub fn record_missing_verdict(&mut self) -> MissingVerdictRetryDecision {
        self.consecutive = self.consecutive.saturating_add(1);
        if self.consecutive <= MAX_MISSING_VERDICT_RETRIES {
            MissingVerdictRetryDecision::Retry(MissingVerdictRetry {
                attempt: self.consecutive,
                max: MAX_MISSING_VERDICT_RETRIES,
            })
        } else {
            MissingVerdictRetryDecision::Exhausted {
                attempts: self.consecutive,
                max: MAX_MISSING_VERDICT_RETRIES,
            }
        }
    }
}

fn bounded_missing_verdict_evidence(findings: &[String]) -> String {
    let evidence = findings
        .iter()
        .take(5)
        .cloned()
        .collect::<Vec<_>>()
        .join(" | ");
    if evidence.is_empty() {
        "no acceptance output captured".to_string()
    } else {
        evidence
    }
}

/// Non-terminal progress message for a missing-verdict protocol retry.
///
/// Deliberately worded as progress, not error: the change is still acceptance
/// work in progress while retry budget remains.
pub fn missing_verdict_retry_progress(retry: MissingVerdictRetry, findings: &[String]) -> String {
    format!(
        "Acceptance completed without a canonical verdict; retrying acceptance \
         (protocol retry {}/{}). Evidence: {}",
        retry.attempt,
        retry.max,
        bounded_missing_verdict_evidence(findings)
    )
}

/// Terminal diagnostic emitted once the missing-verdict retry budget is spent.
pub fn missing_verdict_exhausted_error(attempts: u32, max: u32, findings: &[String]) -> String {
    format!(
        "Acceptance completed without a canonical verdict (missing-verdict protocol failure); \
         status-only or waiting output is not a verdict. Exhausted {attempts} consecutive \
         attempts after {max} protocol retries. Evidence: {}",
        bounded_missing_verdict_evidence(findings)
    )
}

/// Next step after an acceptance command completed without a canonical verdict.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MissingVerdictRetryStep {
    /// Budget remains: re-invoke the normal configured acceptance command with
    /// `retry` as the continuation marker. `progress` is the non-terminal
    /// operator-visible message.
    Retry {
        retry: MissingVerdictRetry,
        progress: String,
    },
    /// Budget exhausted: route to the terminal missing-verdict protocol failure.
    Exhausted { error: String },
}

/// Mode-independent driver for the missing-verdict protocol-retry sequence.
///
/// Serial and parallel orchestration share this driver so equivalent
/// observations produce equivalent routing. Each acceptance invocation reads its
/// continuation marker from [`Self::take_protocol_retry`] and reports the result
/// back through [`Self::observe_missing_verdict`] or
/// [`Self::observe_canonical_verdict`].
///
/// All state is active-run memory. Nothing is written outside the worktree, so a
/// restarted process re-runs acceptance from workspace file/git state rather
/// than resuming a protocol-retry sequence.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MissingVerdictRetryDriver {
    state: MissingVerdictRetryState,
    pending: Option<MissingVerdictRetry>,
}

impl MissingVerdictRetryDriver {
    /// Consume the continuation marker for the acceptance invocation that is
    /// about to start. `None` for an ordinary (non-retry) invocation.
    pub fn take_protocol_retry(&mut self) -> Option<MissingVerdictRetry> {
        self.pending.take()
    }

    /// Consecutive missing verdicts observed so far.
    pub fn consecutive_missing_verdicts(&self) -> u32 {
        self.state.consecutive()
    }

    /// Record any canonical verdict (PASS/FAIL/CONTINUE/GATED/stalled-hold).
    /// Canonical routing is unchanged; only the protocol sequence resets.
    pub fn observe_canonical_verdict(&mut self) {
        self.state.record_canonical_verdict();
        self.pending = None;
    }

    /// Record a completed acceptance command that emitted no canonical verdict
    /// and return the resulting non-terminal or terminal step.
    pub fn observe_missing_verdict(&mut self, findings: &[String]) -> MissingVerdictRetryStep {
        match self.state.record_missing_verdict() {
            MissingVerdictRetryDecision::Retry(retry) => {
                self.pending = Some(retry);
                MissingVerdictRetryStep::Retry {
                    retry,
                    progress: missing_verdict_retry_progress(retry, findings),
                }
            }
            MissingVerdictRetryDecision::Exhausted { attempts, max } => {
                self.pending = None;
                MissingVerdictRetryStep::Exhausted {
                    error: missing_verdict_exhausted_error(attempts, max, findings),
                }
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NormalizedFinding {
    pub identity: String,
    pub text: String,
    pub external: bool,
}

pub fn normalize_findings(findings: &[String]) -> Vec<NormalizedFinding> {
    fn rule_kind(text: &str) -> &'static str {
        if ["test", "coverage", "verification", "evidence"]
            .iter()
            .any(|word| text.contains(word))
        {
            "verification"
        } else if ["spec", "proposal", "requirement"]
            .iter()
            .any(|word| text.contains(word))
        {
            "specification"
        } else if ["task", "checklist", "truthful"]
            .iter()
            .any(|word| text.contains(word))
        {
            "task-truthfulness"
        } else if text.contains("dirty working tree") {
            "workspace-cleanliness"
        } else {
            "implementation"
        }
    }

    let mut normalized = findings
        .iter()
        .filter_map(|finding| {
            let normalized = finding.split_whitespace().collect::<Vec<_>>().join(" ");
            (!normalized.is_empty()).then(|| {
                let lower = normalized.to_ascii_lowercase();
                let finding_code = lower
                    .split_whitespace()
                    .next()
                    .filter(|word| word.starts_with('[') && word.ends_with(']'));
                let path_token = lower
                    .split_whitespace()
                    .find(|word| {
                        word.contains('/') || word.ends_with(".rs") || word.ends_with(".md")
                    })
                    .unwrap_or("");
                let path = path_token
                    .trim_matches(|character: char| {
                        matches!(character, '`' | '(' | ')' | '[' | ']' | ',' | '.' | ';')
                    })
                    .split(':')
                    .next()
                    .unwrap_or("");
                // An explicit non-mockable prerequisite is external only when the
                // finding has no repository target or requested repository repair.
                let external = path.is_empty()
                    && !lower.contains("fix ")
                    && !lower.contains("repair ")
                    && [
                        "external non-mockable",
                        "non-mockable external",
                        "external prerequisite",
                        "external service outage",
                        "missing non-mockable external credential",
                    ]
                    .iter()
                    .any(|needle| lower.contains(needle));
                let scope = if external { "external" } else { "repository" };
                NormalizedFinding {
                    identity: finding_code.map_or_else(
                        || {
                            let location = if path.is_empty() {
                                lower.as_str()
                            } else {
                                path
                            };
                            format!("{scope}|{location}|{}", rule_kind(&lower))
                        },
                        |code| format!("{scope}|code|{code}"),
                    ),
                    text: normalized,
                    external,
                }
            })
        })
        .collect::<Vec<_>>();
    normalized.sort_by(|left, right| left.identity.cmp(&right.identity));
    normalized.dedup_by(|left, right| left.identity == right.identity);
    normalized
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AcceptanceRetryDecision {
    Retry {
        reason: &'static str,
    },
    Stall {
        reason: &'static str,
        external_blockers: Vec<String>,
    },
}

pub fn repository_findings(findings: &[String]) -> Vec<String> {
    findings
        .iter()
        .filter(|finding| {
            normalize_findings(std::slice::from_ref(*finding))
                .first()
                .is_some_and(|normalized| !normalized.external)
        })
        .cloned()
        .collect()
}

pub fn semantic_progress_fingerprint(workspace: &std::path::Path) -> std::io::Result<String> {
    fn include(path: &str) -> bool {
        !path.starts_with(".git/")
            && !path.starts_with(".cflx/")
            && !path.contains("/APPLY_BLOCKED/")
            && !path.starts_with("logs/")
            && !path.starts_with("history/")
            && (path.starts_with("src/")
                || path.starts_with("tests/")
                || path.starts_with("config/")
                || path.starts_with("openspec/specs/")
                || path.contains("/specs/")
                || path == ".cflx.jsonc"
                || path.ends_with("/.cflx.jsonc")
                || path.ends_with("Cargo.toml")
                || path.ends_with("tasks.md"))
    }
    fn visit(
        root: &std::path::Path,
        directory: &std::path::Path,
        output: &mut Vec<(String, Vec<u8>)>,
    ) -> std::io::Result<()> {
        for entry in std::fs::read_dir(directory)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                visit(root, &path, output)?;
                continue;
            }
            let relative = path
                .strip_prefix(root)
                .unwrap()
                .to_string_lossy()
                .replace('\\', "/");
            if include(&relative) {
                let mut contents = std::fs::read(path)?;
                if relative.ends_with("tasks.md") {
                    let text = String::from_utf8_lossy(&contents);
                    contents = text
                        .split("\n## Current Acceptance Follow-up")
                        .next()
                        .unwrap_or(&text)
                        .split("\n## Acceptance #")
                        .next()
                        .unwrap_or(&text)
                        .as_bytes()
                        .to_vec();
                }
                output.push((relative, contents));
            }
        }
        Ok(())
    }
    let mut files = Vec::new();
    visit(workspace, workspace, &mut files)?;
    files.sort_by(|left, right| left.0.cmp(&right.0));
    let hash = files
        .into_iter()
        .flat_map(|(path, bytes)| path.into_bytes().into_iter().chain(bytes))
        .fold(0xcbf29ce484222325u64, |hash, byte| {
            (hash ^ byte as u64).wrapping_mul(0x100000001b3)
        });
    Ok(format!("{hash:016x}"))
}

pub fn decide_acceptance_retry(
    previous_identities: &[String],
    previous_fingerprint: Option<&str>,
    findings: &[NormalizedFinding],
    semantic_fingerprint: &str,
    cycle_count: u32,
) -> AcceptanceRetryDecision {
    let identities = findings
        .iter()
        .map(|finding| finding.identity.clone())
        .collect::<Vec<_>>();
    let external_blockers = findings
        .iter()
        .filter(|finding| finding.external)
        .map(|finding| finding.identity.clone())
        .collect();
    if cycle_count >= MAX_ACCEPTANCE_RETRY_CYCLES {
        return AcceptanceRetryDecision::Stall {
            reason: "acceptance_cycle_limit_exhausted",
            external_blockers,
        };
    }
    if !findings.is_empty() && findings.iter().all(|finding| finding.external) {
        return AcceptanceRetryDecision::Stall {
            reason: "external_acceptance_blocker",
            external_blockers,
        };
    }
    if previous_identities.is_empty() {
        return AcceptanceRetryDecision::Retry {
            reason: "first_acceptance_failure",
        };
    }
    if previous_identities != identities || previous_fingerprint != Some(semantic_fingerprint) {
        return AcceptanceRetryDecision::Retry {
            reason: "finding_or_semantic_progress_changed",
        };
    }
    AcceptanceRetryDecision::Stall {
        reason: "repeated_acceptance_findings",
        external_blockers,
    }
}

pub fn build_acceptance_tail_findings(
    stdout_tail: Option<String>,
    stderr_tail: Option<String>,
) -> Vec<String> {
    let stdout = stdout_tail.filter(|text| !text.trim().is_empty());
    let stderr = stderr_tail.filter(|text| !text.trim().is_empty());
    let selected = stdout
        .or(stderr)
        .unwrap_or_else(|| ACCEPTANCE_OUTPUT_FALLBACK.to_string());
    let lines = selected
        .lines()
        .filter(|line| {
            let trimmed = line.trim();
            // Filter out empty lines, ACCEPTANCE: markers, and FINDINGS: lines
            !trimmed.is_empty()
                && !trimmed.starts_with("ACCEPTANCE:")
                && !trimmed.starts_with("FINDINGS:")
        })
        .map(|line| line.to_string())
        .collect::<Vec<_>>();
    if lines.is_empty() {
        vec![ACCEPTANCE_OUTPUT_FALLBACK.to_string()]
    } else {
        lines
    }
}

/// Result of an acceptance operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AcceptanceResult {
    /// Acceptance passed - can proceed to archive.
    Pass,
    /// Acceptance failed - must return to apply loop.
    Fail { findings: Vec<String> },
    /// Acceptance requires more investigation - retry acceptance.
    Continue,
    /// Acceptance gated due to implementation blocker - stop apply loop.
    Gated,
    /// Acceptance command execution failed (non-zero exit).
    CommandFailed {
        error: String,
        findings: Vec<String>,
    },
    /// Acceptance detected a repeated unresolved permission/policy blocker.
    PermissionStalled {
        blocker: crate::events::StalledBlocker,
    },
    /// Acceptance command completed without emitting any canonical verdict.
    /// This is a protocol failure (for example a status-only "waiting for
    /// verification" exit) and is intentionally distinct from an explicit
    /// canonical `Continue`; it must never consume the explicit-CONTINUE
    /// retry path.
    MissingVerdict { findings: Vec<String> },
    /// Acceptance was cancelled (e.g., by user or timeout).
    Cancelled,
}

impl AcceptanceResult {
    /// Returns true if acceptance passed.
    pub fn is_pass(&self) -> bool {
        matches!(self, AcceptanceResult::Pass)
    }

    /// Returns true when the acceptance command emitted a canonical verdict
    /// (PASS/FAIL/CONTINUE/GATED/stalled-hold).
    ///
    /// A missing verdict is a protocol failure, and command failure and
    /// cancellation are not verdicts at all: none of them are canonical, so
    /// none of them reset or consume the missing-verdict protocol budget.
    pub fn is_canonical_verdict(&self) -> bool {
        matches!(
            self,
            AcceptanceResult::Pass
                | AcceptanceResult::Fail { .. }
                | AcceptanceResult::Continue
                | AcceptanceResult::Gated
                | AcceptanceResult::PermissionStalled { .. }
        )
    }
}

/// Run acceptance test for a change with streaming output.
///
/// # Arguments
/// * `change` - The change to test
/// * `agent` - The agent runner for history tracking
/// * `ai_runner` - The AI command runner for command execution
/// * `config` - Orchestrator configuration
/// * `output` - Output handler for streaming command output
/// * `cancel_check` - Function to check if operation should be cancelled
///
/// # Returns
/// * `Ok((AcceptanceResult::Pass, attempt_number))` - Acceptance passed
/// * `Ok((AcceptanceResult::Fail { findings }, attempt_number))` - Acceptance failed with findings
/// * `Ok((AcceptanceResult::CommandFailed { error, findings }, attempt_number))` - Command execution failed
/// * `Ok((AcceptanceResult::Cancelled, attempt_number))` - Operation was cancelled
/// * `Err(e)` - An error occurred
///
/// The attempt_number is the number of the acceptance attempt that was just recorded.
///
/// `protocol_retry` is `Some` only when this invocation continues a previous
/// attempt that exited without a canonical verdict.
#[allow(clippy::too_many_arguments)]
pub async fn acceptance_test_streaming<O, F>(
    change: &Change,
    agent: &mut AgentRunner,
    ai_runner: &crate::ai_command_runner::AiCommandRunner,
    _config: &crate::config::OrchestratorConfig,
    output: &O,
    cancel_check: F,
    protocol_retry: Option<MissingVerdictRetry>,
) -> Result<(AcceptanceResult, u32, String)>
where
    O: OutputHandler,
    F: Fn() -> bool,
{
    use crate::agent::OutputLine;

    info!("Running acceptance test for: {}", change.id);
    output.on_info(&format!("Acceptance test: {}", change.id));

    // Capture current commit hash for diff tracking
    let commit_hash = crate::vcs::git::commands::get_current_commit(".")
        .await
        .ok(); // Allow to fail silently (non-git repos)

    // Get current branch for diff context (first acceptance needs base branch)
    let base_branch = crate::vcs::git::commands::get_current_branch(".")
        .await
        .ok()
        .flatten(); // None if in detached HEAD or non-git repo

    // Execute acceptance command with streaming via AiCommandRunner (real process handle)
    let (mut child, mut output_rx, start_time, command) = agent
        .run_acceptance_streaming_with_runner(
            &change.id,
            ai_runner,
            None,
            base_branch.as_deref(),
            protocol_retry,
        )
        .await?;

    // Log acceptance started with command
    output.on_info(&format!("Acceptance started: {}", change.id));
    output.on_info(&format!(
        "  {}",
        crate::events::command_log_summary(&command)
    ));

    // Create output collector for history and parsing
    let mut output_collector = OutputCollector::new();
    let mut full_stdout = String::new();

    // Grace period after detecting an acceptance marker before terminating the process.
    // This handles the case where the agent process (or its child processes) does not exit
    // promptly after emitting ACCEPTANCE: PASS/FAIL/etc., for example because
    // child processes (MCP servers) keep stdout/stderr pipes open.
    const MARKER_GRACE_PERIOD: std::time::Duration = std::time::Duration::from_secs(30);

    // Stream output until channel closes or acceptance marker detected + grace period
    let mut marker_detected = false;
    let mut verdict_stream_detector = crate::acceptance::VerdictStreamDetector::default();
    let mut marker_deadline: Option<tokio::time::Instant> = None;
    let mut early_terminated = false;

    loop {
        let recv_future = output_rx.recv();

        let line = if let Some(deadline) = marker_deadline {
            // After marker detection, apply a timeout for remaining output
            match tokio::time::timeout_at(deadline, recv_future).await {
                Ok(Some(line)) => line,
                Ok(None) => break, // Channel closed normally
                Err(_) => {
                    // Grace period expired — terminate the process
                    warn!(
                        "Acceptance marker grace period expired for {}, terminating process",
                        change.id
                    );
                    let _ = child.terminate();
                    early_terminated = true;
                    break;
                }
            }
        } else {
            match tokio::time::timeout(std::time::Duration::from_millis(50), recv_future).await {
                Ok(Some(line)) => line,
                Ok(None) => break, // Channel closed normally
                Err(_) => {
                    if cancel_check() {
                        warn!("Acceptance test cancelled while waiting for output");
                        output.on_warn("Acceptance test cancelled");
                        let _ = child.terminate();
                        return Ok((AcceptanceResult::Cancelled, 0, command));
                    }
                    continue;
                }
            }
        };

        // Check for cancellation
        if cancel_check() {
            warn!("Acceptance test cancelled for: {}", change.id);
            output.on_warn("Acceptance test cancelled");
            let _ = child.terminate();
            // Note: For cancellation, we don't record an attempt, so return 0
            return Ok((AcceptanceResult::Cancelled, 0, command));
        }

        match line {
            OutputLine::Stdout(s) => {
                output_collector.add_stdout(&s);
                full_stdout.push_str(&s);
                full_stdout.push('\n');
                output.on_stdout(&s);

                // Detect a canonical verdict in stdout to start the grace
                // period. This prevents indefinite blocking when the agent
                // process does not exit after emitting the verdict. The
                // detector recognises the primary strict JSON verdict (as a
                // standalone line or wrapped in a supported agent JSONL event)
                // and, as fallback, the legacy standalone plain-text
                // marker. Malformed markers with trailing text (for example
                // "ACCEPTANCE: PASSAll ...") do NOT trigger early completion.
                if !marker_detected && verdict_stream_detector.detect(&s).is_some() {
                    marker_detected = true;
                    marker_deadline = Some(tokio::time::Instant::now() + MARKER_GRACE_PERIOD);
                    info!(
                        "Acceptance canonical verdict detected for {}, starting {}s grace period",
                        change.id,
                        MARKER_GRACE_PERIOD.as_secs()
                    );
                }
            }
            OutputLine::Stderr(s) => {
                output_collector.add_stderr(&s);
                output.on_agent_stderr(&s);
            }
        }
    }

    // Child has exited, wait for status. Keep this cancellation-aware because
    // the output channel may close before the process status is reaped.
    let status = loop {
        if cancel_check() {
            warn!(
                "Acceptance test cancelled while waiting for child status for: {}",
                change.id
            );
            output.on_warn("Acceptance test cancelled");
            let _ = child.terminate();
            return Ok((AcceptanceResult::Cancelled, 0, command));
        }

        match tokio::time::timeout(std::time::Duration::from_millis(50), child.wait()).await {
            Ok(status) => {
                break status.map_err(|e| {
                    OrchestratorError::AgentCommand(format!(
                        "Failed to wait for acceptance command for change '{}': {}",
                        change.id, e
                    ))
                })?;
            }
            Err(_) => continue,
        }
    };

    // Record attempt
    let stdout_tail = output_collector.stdout_tail();
    let stderr_tail = output_collector.stderr_tail();

    // Build tail findings for history recording (last N lines, used in AcceptanceAttempt).
    let tail_findings = build_acceptance_tail_findings(stdout_tail.clone(), stderr_tail.clone());

    // A verdict-finalized run is one we terminated after observing the
    // canonical standalone verdict. The non-zero exit from termination is
    // expected — the verdict drives the final result.
    let verdict_finalized_run = early_terminated && marker_detected;

    // Check if command failed (skip when verdict already finalized).
    if !status.success() && !verdict_finalized_run {
        let error_msg = format!(
            "Acceptance command failed with exit code: {:?}",
            status.code()
        );
        let attempt_number = agent.next_acceptance_attempt_number(&change.id);
        let attempt = AcceptanceAttempt {
            attempt: attempt_number,
            passed: false,
            duration: start_time.elapsed(),
            findings: Some(tail_findings.clone()),
            exit_code: status.code(),
            stdout_tail,
            stderr_tail,
            commit_hash: commit_hash.clone(),
        };
        agent.record_acceptance_attempt(&change.id, attempt);
        output.on_error(&error_msg);
        return Ok((
            AcceptanceResult::CommandFailed {
                error: error_msg,
                findings: tail_findings,
            },
            attempt_number,
            command,
        ));
    }

    // Parse acceptance output to determine result
    let parsed_result = crate::acceptance::parse_acceptance_output(&full_stdout);

    let (result, passed) = match parsed_result {
        crate::acceptance::AcceptanceResult::Pass => {
            info!("Acceptance test passed for: {}", change.id);
            output.on_info("Acceptance test: PASS");
            (AcceptanceResult::Pass, true)
        }
        crate::acceptance::AcceptanceResult::Fail {
            findings: parsed_findings,
        } => {
            info!("Acceptance test failed for: {}", change.id);
            output.on_warn("Acceptance test: FAIL");
            let findings = if parsed_findings.is_empty() {
                vec!["Investigate acceptance failure and apply the required fix".to_string()]
            } else {
                parsed_findings
            };
            (AcceptanceResult::Fail { findings }, false)
        }
        crate::acceptance::AcceptanceResult::Continue => {
            info!("Acceptance requires continuation for: {}", change.id);
            output.on_info("Acceptance test: CONTINUE");
            (AcceptanceResult::Continue, false)
        }
        crate::acceptance::AcceptanceResult::Gated => {
            info!("Acceptance gated for: {}", change.id);
            output.on_warn("Acceptance test: GATED");
            (AcceptanceResult::Gated, false)
        }
        crate::acceptance::AcceptanceResult::MissingVerdict => {
            warn!(
                "Acceptance completed without a canonical verdict for: {} (missing-verdict protocol failure)",
                change.id
            );
            output.on_error("Acceptance test: MISSING VERDICT (protocol failure — the acceptance command exited without a canonical verdict; status-only or waiting output is not a verdict)");
            (
                AcceptanceResult::MissingVerdict {
                    findings: tail_findings.clone(),
                },
                false,
            )
        }
    };

    let history_findings = match &result {
        AcceptanceResult::Fail { findings } => Some(findings.clone()),
        AcceptanceResult::Continue => {
            Some(vec!["Investigation incomplete - continue later".to_string()])
        }
        AcceptanceResult::Gated => Some(vec!["Implementation blocker detected".to_string()]),
        AcceptanceResult::Pass => None,
        AcceptanceResult::MissingVerdict { findings } => {
            let mut evidence = vec![MISSING_VERDICT_DIAGNOSTIC.to_string()];
            evidence.extend(findings.iter().cloned());
            Some(evidence)
        }
        AcceptanceResult::CommandFailed { .. }
        | AcceptanceResult::PermissionStalled { .. }
        | AcceptanceResult::Cancelled => Some(tail_findings.clone()),
    };
    let attempt_number = agent.next_acceptance_attempt_number(&change.id);
    let attempt = AcceptanceAttempt {
        attempt: attempt_number,
        passed,
        duration: start_time.elapsed(),
        findings: history_findings,
        exit_code: status.code(),
        stdout_tail,
        stderr_tail,
        commit_hash: commit_hash.clone(),
    };
    agent.record_acceptance_attempt(&change.id, attempt);
    match &result {
        AcceptanceResult::Fail { findings } => {
            if !findings.is_empty() {
                agent.record_acceptance_follow_up(&change.id, attempt_number, findings.clone());
            }
        }
        AcceptanceResult::Pass => agent.clear_acceptance_follow_up(&change.id),
        _ => {}
    }
    Ok((result, attempt_number, command))
}

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

    /// Table-driven contract for the dedicated missing-verdict budget: the
    /// initial attempt plus two retries, then terminal exhaustion.
    #[test]
    fn missing_verdict_budget_allows_two_retries_then_exhausts() {
        let mut state = MissingVerdictRetryState::default();
        let expected = [
            MissingVerdictRetryDecision::Retry(MissingVerdictRetry { attempt: 1, max: 2 }),
            MissingVerdictRetryDecision::Retry(MissingVerdictRetry { attempt: 2, max: 2 }),
            MissingVerdictRetryDecision::Exhausted {
                attempts: 3,
                max: 2,
            },
        ];

        for (index, want) in expected.iter().enumerate() {
            assert_eq!(
                state.record_missing_verdict(),
                *want,
                "consecutive missing verdict #{} must route as {:?}",
                index + 1,
                want
            );
        }
        assert_eq!(MAX_MISSING_VERDICT_RETRIES, 2);
        assert_eq!(
            state.consecutive(),
            3,
            "a fourth protocol retry must never be offered after exhaustion"
        );
        assert!(matches!(
            state.record_missing_verdict(),
            MissingVerdictRetryDecision::Exhausted { .. }
        ));
    }

    #[test]
    fn missing_verdict_canonical_verdict_resets_consecutive_sequence() {
        let mut state = MissingVerdictRetryState::default();
        assert!(matches!(
            state.record_missing_verdict(),
            MissingVerdictRetryDecision::Retry(MissingVerdictRetry { attempt: 1, .. })
        ));
        assert!(matches!(
            state.record_missing_verdict(),
            MissingVerdictRetryDecision::Retry(MissingVerdictRetry { attempt: 2, .. })
        ));

        // PASS/FAIL/CONTINUE/GATED/stalled-hold all reach this reset.
        state.record_canonical_verdict();
        assert_eq!(state.consecutive(), 0);

        assert_eq!(
            state.record_missing_verdict(),
            MissingVerdictRetryDecision::Retry(MissingVerdictRetry { attempt: 1, max: 2 }),
            "a later missing verdict must start a fresh protocol-retry sequence"
        );
    }

    /// The protocol budget is fixed and independent from the configured
    /// explicit-`CONTINUE` budget, whatever that budget is set to.
    #[test]
    fn missing_verdict_budget_is_independent_of_configured_continue_count() {
        for configured_continues in [0u32, 1, 5, 50] {
            let mut state = MissingVerdictRetryState::default();
            let mut retries = 0u32;
            loop {
                match state.record_missing_verdict() {
                    MissingVerdictRetryDecision::Retry(retry) => {
                        assert_eq!(retry.max, MAX_MISSING_VERDICT_RETRIES);
                        retries += 1;
                    }
                    MissingVerdictRetryDecision::Exhausted { attempts, max } => {
                        assert_eq!(attempts, MAX_MISSING_VERDICT_RETRIES + 1);
                        assert_eq!(max, MAX_MISSING_VERDICT_RETRIES);
                        break;
                    }
                }
            }
            assert_eq!(
                retries, MAX_MISSING_VERDICT_RETRIES,
                "configured acceptance_max_continues={configured_continues} must not change the \
                 dedicated missing-verdict budget"
            );
        }
    }

    #[test]
    fn missing_verdict_diagnostics_are_bounded_and_distinguish_progress_from_terminal() {
        let findings = (0..10)
            .map(|index| format!("evidence line {index}"))
            .collect::<Vec<_>>();

        let progress =
            missing_verdict_retry_progress(MissingVerdictRetry { attempt: 1, max: 2 }, &findings);
        assert!(progress.contains("protocol retry 1/2"));
        assert!(progress.contains("evidence line 4"));
        assert!(
            !progress.contains("evidence line 5"),
            "evidence must stay bounded to the first five findings, got {progress}"
        );
        assert!(
            !progress.to_ascii_lowercase().contains("protocol failure"),
            "an available retry must not read as a terminal failure: {progress}"
        );

        let terminal = missing_verdict_exhausted_error(3, 2, &findings);
        assert!(terminal.contains("missing-verdict protocol failure"));
        assert!(terminal.contains("Exhausted 3 consecutive attempts after 2 protocol retries"));
        assert!(terminal.contains("evidence line 4"));
        assert!(!terminal.contains("evidence line 5"));

        assert!(
            missing_verdict_exhausted_error(3, 2, &[]).contains("no acceptance output captured"),
            "empty evidence must still produce an actionable diagnostic"
        );
    }

    /// Replay an acceptance verdict sequence through the shared driver exactly
    /// as serial and parallel orchestration do, and report what each invocation
    /// received plus how the sequence terminated.
    fn replay_missing_verdict_sequence(
        sequence: &[AcceptanceResult],
    ) -> (
        Vec<Option<MissingVerdictRetry>>,
        Option<AcceptanceResult>,
        Option<String>,
    ) {
        let mut protocol = MissingVerdictRetryDriver::default();
        let mut received = Vec::new();
        for result in sequence {
            received.push(protocol.take_protocol_retry());
            match result {
                AcceptanceResult::MissingVerdict { findings } => {
                    match protocol.observe_missing_verdict(findings) {
                        MissingVerdictRetryStep::Retry { .. } => continue,
                        MissingVerdictRetryStep::Exhausted { error } => {
                            return (received, None, Some(error))
                        }
                    }
                }
                canonical => {
                    protocol.observe_canonical_verdict();
                    return (received, Some(canonical.clone()), None);
                }
            }
        }
        (received, None, None)
    }

    fn missing_verdict(evidence: &str) -> AcceptanceResult {
        AcceptanceResult::MissingVerdict {
            findings: vec![evidence.to_string()],
        }
    }

    #[test]
    fn missing_verdict_driver_retries_twice_then_accepts_canonical_pass() {
        let (received, canonical, error) = replay_missing_verdict_sequence(&[
            missing_verdict("waiting for verification"),
            missing_verdict("still waiting"),
            AcceptanceResult::Pass,
        ]);

        assert_eq!(received.len(), 3, "acceptance must be invoked three times");
        assert_eq!(
            received,
            vec![
                None,
                Some(MissingVerdictRetry { attempt: 1, max: 2 }),
                Some(MissingVerdictRetry { attempt: 2, max: 2 }),
            ],
            "only the retries may carry a continuation marker"
        );
        assert_eq!(canonical, Some(AcceptanceResult::Pass));
        assert!(
            error.is_none(),
            "a canonical verdict within budget must not produce a terminal error"
        );
    }

    #[test]
    fn missing_verdict_driver_exhausts_after_three_consecutive_missing_verdicts() {
        let (received, canonical, error) = replay_missing_verdict_sequence(&[
            missing_verdict("waiting one"),
            missing_verdict("waiting two"),
            missing_verdict("waiting three"),
            missing_verdict("never reached"),
        ]);

        assert_eq!(
            received.len(),
            3,
            "no fourth protocol retry may start after exhaustion"
        );
        assert!(canonical.is_none());
        let error = error.expect("third consecutive missing verdict must be terminal");
        assert!(error.contains("missing-verdict protocol failure"));
        assert!(error.contains("Exhausted 3 consecutive attempts after 2 protocol retries"));
        assert!(
            error.contains("waiting three"),
            "terminal diagnostic must carry bounded evidence, got {error}"
        );
    }

    /// Every canonical outcome — not just PASS — resets the protocol sequence
    /// and keeps its own routing untouched.
    #[test]
    fn missing_verdict_driver_treats_every_canonical_outcome_as_a_reset() {
        for canonical in [
            AcceptanceResult::Pass,
            AcceptanceResult::Fail {
                findings: vec!["src/lib.rs:1 fix".to_string()],
            },
            AcceptanceResult::Continue,
            AcceptanceResult::Gated,
            AcceptanceResult::PermissionStalled {
                blocker: crate::events::StalledBlocker::acceptance_infrastructure("denied"),
            },
        ] {
            let mut protocol = MissingVerdictRetryDriver::default();
            assert!(matches!(
                protocol.observe_missing_verdict(&["waiting".to_string()]),
                MissingVerdictRetryStep::Retry { .. }
            ));
            assert!(protocol.take_protocol_retry().is_some());

            protocol.observe_canonical_verdict();
            assert_eq!(
                protocol.consecutive_missing_verdicts(),
                0,
                "{canonical:?} must reset the consecutive protocol counter"
            );
            assert!(
                protocol.take_protocol_retry().is_none(),
                "{canonical:?} must clear any pending continuation marker"
            );

            // The next protocol failure starts a fresh full budget.
            assert!(matches!(
                protocol.observe_missing_verdict(&["waiting again".to_string()]),
                MissingVerdictRetryStep::Retry {
                    retry: MissingVerdictRetry { attempt: 1, .. },
                    ..
                }
            ));
        }
    }

    /// Routing matrix: only canonical verdicts reset the protocol sequence,
    /// only a missing verdict may consume it, and command failure or
    /// cancellation is never reclassified as a missing-verdict retry.
    #[test]
    fn acceptance_routing_matrix_keeps_missing_verdict_distinct() {
        let cases: [(AcceptanceResult, bool, bool); 8] = [
            (AcceptanceResult::Pass, true, false),
            (
                AcceptanceResult::Fail {
                    findings: vec!["src/lib.rs:1 fix".to_string()],
                },
                true,
                false,
            ),
            (AcceptanceResult::Continue, true, false),
            (AcceptanceResult::Gated, true, false),
            (
                AcceptanceResult::PermissionStalled {
                    blocker: crate::events::StalledBlocker::acceptance_infrastructure("denied"),
                },
                true,
                false,
            ),
            (missing_verdict("waiting"), false, true),
            (
                AcceptanceResult::CommandFailed {
                    error: "exit code 1".to_string(),
                    findings: vec!["boom".to_string()],
                },
                false,
                false,
            ),
            (AcceptanceResult::Cancelled, false, false),
        ];

        for (result, canonical, missing) in cases {
            assert_eq!(
                result.is_canonical_verdict(),
                canonical,
                "{result:?} canonical-verdict classification"
            );
            assert_eq!(
                matches!(result, AcceptanceResult::MissingVerdict { .. }),
                missing,
                "{result:?} must not be confused with a missing verdict"
            );
            assert!(
                !(canonical && missing),
                "{result:?} cannot be both canonical and a protocol failure"
            );
        }

        // Command failure keeps its own routing: it neither resets nor consumes
        // the protocol budget, so a later missing verdict still gets a full one.
        let mut protocol = MissingVerdictRetryDriver::default();
        for result in [
            AcceptanceResult::CommandFailed {
                error: "exit code 1".to_string(),
                findings: Vec::new(),
            },
            AcceptanceResult::Cancelled,
        ] {
            assert!(!result.is_canonical_verdict());
            assert!(protocol.take_protocol_retry().is_none());
            assert_eq!(protocol.consecutive_missing_verdicts(), 0);
        }
        assert!(matches!(
            protocol.observe_missing_verdict(&["waiting".to_string()]),
            MissingVerdictRetryStep::Retry {
                retry: MissingVerdictRetry { attempt: 1, max: 2 },
                ..
            }
        ));
    }

    /// Serial and parallel call the same driver; equivalent observations must
    /// produce equivalent routing.
    #[test]
    fn missing_verdict_driver_has_serial_and_parallel_routing_parity() {
        let sequence = [
            missing_verdict("waiting"),
            missing_verdict("waiting"),
            AcceptanceResult::Fail {
                findings: vec!["src/lib.rs:1 missing coverage".to_string()],
            },
        ];

        let serial = replay_missing_verdict_sequence(&sequence);
        let parallel = replay_missing_verdict_sequence(&sequence);
        assert_eq!(serial, parallel);
        assert_eq!(serial.0.len(), 3);
        assert!(matches!(serial.1, Some(AcceptanceResult::Fail { .. })));
        assert!(serial.2.is_none());
    }

    #[test]
    fn semantic_fingerprint_excludes_runtime_bookkeeping() {
        let temp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir_all(temp.path().join("src")).unwrap();
        std::fs::write(temp.path().join("src/lib.rs"), "one").unwrap();
        let before = semantic_progress_fingerprint(temp.path()).unwrap();
        std::fs::create_dir_all(temp.path().join(".cflx")).unwrap();
        std::fs::write(temp.path().join(".cflx/runtime.json"), "runtime").unwrap();
        assert_eq!(before, semantic_progress_fingerprint(temp.path()).unwrap());
        std::fs::write(temp.path().join("src/lib.rs"), "two").unwrap();
        assert_ne!(before, semantic_progress_fingerprint(temp.path()).unwrap());
    }

    #[test]
    fn finding_identity_prefers_code_and_uses_structural_fallback() {
        let coded = normalize_findings(&[
            "[MISSING_RETRY_TEST] old evidence at src/run.rs:10".into(),
            "[MISSING_RETRY_TEST] changed summary at tests/run.rs:99".into(),
        ]);
        assert_eq!(coded.len(), 1);
        assert_eq!(coded[0].identity, "repository|code|[missing_retry_test]");

        let changed_detail = normalize_findings(&[
            "Missing retry test at src/run.rs:10 because the branch is uncovered".into(),
            "Regression coverage absent in src/run.rs:77; add a focused test".into(),
        ]);
        assert_eq!(changed_detail.len(), 1);
        assert_eq!(
            changed_detail[0].identity,
            "repository|src/run.rs|verification"
        );

        let distinct = normalize_findings(&[
            "Missing test at src/run.rs:10".into(),
            "Incorrect implementation at src/run.rs:11".into(),
            "Missing test at src/other.rs:10".into(),
        ]);
        assert_eq!(
            distinct.len(),
            3,
            "rule and location must prevent collisions"
        );
    }

    #[test]
    fn retry_decision_normalizes_order_whitespace_duplicates_and_stalls_repeats() {
        let findings = normalize_findings(&[
            " src/lib.rs:10   missing  test ".to_string(),
            "src/lib.rs:11 missing test".to_string(),
        ]);
        assert_eq!(findings.len(), 1);
        let decision = decide_acceptance_retry(
            &[findings[0].identity.clone()],
            Some("unchanged"),
            &findings,
            "unchanged",
            2,
        );
        assert!(matches!(
            decision,
            AcceptanceRetryDecision::Stall {
                reason: "repeated_acceptance_findings",
                ..
            }
        ));
    }

    #[test]
    fn retry_decision_stalls_external_only_and_allows_progress_changed() {
        let findings = normalize_findings(&["external service outage".to_string()]);
        assert!(findings[0].external);
        assert!(matches!(
            decide_acceptance_retry(&[], None, &findings, "one", 1),
            AcceptanceRetryDecision::Stall {
                reason: "external_acceptance_blocker",
                ..
            }
        ));
        assert!(
            matches!(decide_acceptance_retry(&[], None, &findings, "one", MAX_ACCEPTANCE_RETRY_CYCLES), AcceptanceRetryDecision::Stall { reason: "acceptance_cycle_limit_exhausted", external_blockers } if external_blockers.len() == 1)
        );
    }

    #[test]
    fn semantic_fingerprint_tracks_change_specs_and_jsonc_but_excludes_runtime_follow_up() {
        let temp = tempfile::TempDir::new().unwrap();
        let tasks = temp.path().join("openspec/changes/example/tasks.md");
        let spec = temp
            .path()
            .join("openspec/changes/example/specs/runtime/spec.md");
        std::fs::create_dir_all(spec.parent().unwrap()).unwrap();
        std::fs::write(&tasks, "## Implementation Tasks\n- [x] work\n").unwrap();
        std::fs::write(&spec, "requirement one").unwrap();
        std::fs::write(temp.path().join(".cflx.jsonc"), "{ \"mode\": 1 }").unwrap();
        let before = semantic_progress_fingerprint(temp.path()).unwrap();
        std::fs::write(&tasks, "## Implementation Tasks\n- [x] work\n\n## Acceptance #2 Failure Follow-up\n- [ ] runtime finding\n").unwrap();
        assert_eq!(before, semantic_progress_fingerprint(temp.path()).unwrap());
        std::fs::write(&spec, "requirement two").unwrap();
        assert_ne!(before, semantic_progress_fingerprint(temp.path()).unwrap());
        std::fs::write(temp.path().join(".cflx.jsonc"), "{ \"mode\": 2 }").unwrap();
        assert_ne!(before, semantic_progress_fingerprint(temp.path()).unwrap());
    }

    #[test]
    fn generic_credential_and_unavailable_errors_remain_repository_fixable() {
        let findings = normalize_findings(&[
            "missing API key in test fixture".to_string(),
            "src/client.rs: rate limit retry missing".to_string(),
            "network unreachable: fix retry handling".to_string(),
            "dns resolution failed while repairing src/client.rs".to_string(),
            "missing non-mockable external credential".to_string(),
        ]);
        assert_eq!(
            findings.iter().filter(|finding| finding.external).count(),
            1
        );
        assert!(findings[0].identity.starts_with("external|"));
        assert_eq!(
            repository_findings(&[
                "missing API key in test fixture".to_string(),
                "src/client.rs: rate limit retry missing".to_string(),
                "network unreachable: fix retry handling".to_string(),
                "dns resolution failed while repairing src/client.rs".to_string(),
                "missing non-mockable external credential".to_string(),
            ])
            .len(),
            4
        );
    }

    #[test]
    fn alternating_continue_and_fail_keeps_fail_retry_history_deterministic() {
        let findings = normalize_findings(&["src/lib.rs:10 missing regression coverage".into()]);
        let identities = findings
            .iter()
            .map(|finding| finding.identity.clone())
            .collect::<Vec<_>>();

        // CONTINUE never enters the FAIL retry decision; the first later FAIL
        // remains the repair opportunity and the repeated FAIL then stalls.
        assert!(matches!(
            decide_acceptance_retry(&[], None, &findings, "unchanged", 1),
            AcceptanceRetryDecision::Retry {
                reason: "first_acceptance_failure"
            }
        ));
        assert!(matches!(
            decide_acceptance_retry(&identities, Some("unchanged"), &findings, "unchanged", 2),
            AcceptanceRetryDecision::Stall {
                reason: "repeated_acceptance_findings",
                ..
            }
        ));
    }

    #[test]
    fn serial_and_parallel_same_inputs_have_retry_outcome_parity() {
        let findings = normalize_findings(&[
            "src/lib.rs:10 missing regression coverage".into(),
            "external non-mockable prerequisite unavailable".into(),
        ]);
        let previous = findings
            .iter()
            .map(|finding| finding.identity.clone())
            .collect::<Vec<_>>();

        // Both execution modes call this shared pure decision with checkpoint
        // state. Keep an explicit parity fixture for their common boundary.
        let serial = decide_acceptance_retry(&previous, Some("same"), &findings, "same", 2);
        let parallel = decide_acceptance_retry(&previous, Some("same"), &findings, "same", 2);
        assert_eq!(serial, parallel);
        assert!(matches!(
            serial,
            AcceptanceRetryDecision::Stall {
                reason: "repeated_acceptance_findings",
                ref external_blockers
            } if external_blockers.len() == 1
        ));
    }

    #[test]
    fn retry_decision_handles_mixed_and_findingless_failures() {
        let mixed = normalize_findings(&[
            "src/lib.rs:1 fix test".into(),
            "external service outage".into(),
        ]);
        assert!(matches!(
            decide_acceptance_retry(&[], None, &mixed, "one", 1),
            AcceptanceRetryDecision::Retry { .. }
        ));
        assert!(matches!(
            decide_acceptance_retry(&[], None, &[], "one", 1),
            AcceptanceRetryDecision::Retry { .. }
        ));
        assert_eq!(
            repository_findings(&[
                "src/lib.rs:1 fix test".into(),
                "external service outage".into(),
            ]),
            vec!["src/lib.rs:1 fix test"]
        );
    }

    #[test]
    fn test_build_acceptance_tail_findings_prefers_stdout() {
        let findings = build_acceptance_tail_findings(
            Some("stdout line 1\nstdout line 2".to_string()),
            Some("stderr line".to_string()),
        );

        assert_eq!(findings, vec!["stdout line 1", "stdout line 2"]);
    }

    #[test]
    fn test_build_acceptance_tail_findings_falls_back_to_stderr() {
        let findings =
            build_acceptance_tail_findings(Some("  ".to_string()), Some("stderr".to_string()));

        assert_eq!(findings, vec!["stderr"]);
    }

    #[test]
    fn test_build_acceptance_tail_findings_fallback_message() {
        let findings = build_acceptance_tail_findings(None, Some("\n\n".to_string()));

        assert_eq!(findings, vec!["No acceptance output captured"]);
    }

    #[test]
    fn test_acceptance_result_is_pass() {
        assert!(AcceptanceResult::Pass.is_pass());
        assert!(!AcceptanceResult::Fail {
            findings: vec!["error".to_string()]
        }
        .is_pass());
        assert!(!AcceptanceResult::CommandFailed {
            error: "test".to_string(),
            findings: vec!["failure".to_string()],
        }
        .is_pass());
        assert!(!AcceptanceResult::PermissionStalled {
            blocker: crate::events::StalledBlocker::acceptance_infrastructure("permission denied"),
        }
        .is_pass());
        assert!(!AcceptanceResult::MissingVerdict {
            findings: vec!["status-only output".to_string()],
        }
        .is_pass());
        assert!(!AcceptanceResult::Cancelled.is_pass());
        assert!(!AcceptanceResult::Gated.is_pass());
    }

    #[test]
    fn test_build_acceptance_tail_findings_filters_acceptance_marker() {
        let findings = build_acceptance_tail_findings(
            Some("line 1\nACCEPTANCE: FAIL\nline 2".to_string()),
            None,
        );

        assert_eq!(findings, vec!["line 1", "line 2"]);
    }

    #[test]
    fn test_build_acceptance_tail_findings_filters_findings_line() {
        let findings = build_acceptance_tail_findings(
            Some("error 1\nFINDINGS:\n- item 1\n- item 2".to_string()),
            None,
        );

        assert_eq!(findings, vec!["error 1", "- item 1", "- item 2"]);
    }

    #[test]
    fn test_build_acceptance_tail_findings_filters_both_markers() {
        let findings = build_acceptance_tail_findings(
            Some("ACCEPTANCE: FAIL\nFINDINGS:\nactual error\nanother line".to_string()),
            None,
        );

        assert_eq!(findings, vec!["actual error", "another line"]);
    }

    // Characterization tests: document the difference between tail_findings
    // and parse_acceptance_output findings so the refactor is clearly motivated.

    #[test]
    fn test_tail_findings_includes_preamble_parse_does_not() {
        // tail_findings includes all non-marker lines (preamble, postamble, items).
        // parse_acceptance_output findings includes only FINDINGS section items.
        // The refactor unifies the FAIL path to use parse_acceptance_output findings.
        let stdout = "preamble\nACCEPTANCE: FAIL\nFINDINGS:\n- Finding 1\n- Finding 2\npostamble"
            .to_string();

        let tail = build_acceptance_tail_findings(Some(stdout.clone()), None);
        // tail includes preamble, finding items, postamble
        assert!(tail.iter().any(|l| l.contains("preamble")));
        assert!(tail.iter().any(|l| l.contains("postamble")));
        assert!(tail.iter().any(|l| l.contains("Finding 1")));

        // parse_acceptance_output returns only the FINDINGS section items
        match crate::acceptance::parse_acceptance_output(&stdout) {
            crate::acceptance::AcceptanceResult::Fail { findings } => {
                assert_eq!(findings, vec!["Finding 1", "Finding 2"]);
                assert!(!findings.iter().any(|f| f.contains("preamble")));
                assert!(!findings.iter().any(|f| f.contains("postamble")));
            }
            _ => panic!("Expected Fail"),
        }
    }

    #[test]
    fn test_parse_findings_is_preferred_source_for_fail_result() {
        // After the refactor: for AcceptanceResult::Fail, findings come from
        // parse_acceptance_output (FINDINGS section), not from build_acceptance_tail_findings.
        let stdout =
            "ACCEPTANCE: FAIL\nFINDINGS:\n- src/foo.rs:10 issue A\n- src/bar.rs:5 issue B\n"
                .to_string();

        match crate::acceptance::parse_acceptance_output(&stdout) {
            crate::acceptance::AcceptanceResult::Fail { findings } => {
                assert_eq!(findings.len(), 2);
                assert_eq!(findings[0], "src/foo.rs:10 issue A");
                assert_eq!(findings[1], "src/bar.rs:5 issue B");
            }
            _ => panic!("Expected Fail"),
        }
    }
}