cflx 0.6.327

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
//! Tests for conflict detection and resolution functionality.

use super::super::conflict::*;
use crate::vcs::WorkspaceManager;
use std::path::{Path, PathBuf};

// The conflict layer's own workspace double, shared with its unit tests.
use crate::parallel::conflict::fixtures::{ConflictProbe, MockWorkspaceManager};

#[tokio::test]
async fn test_detect_conflicts_no_conflicts() {
    let manager = MockWorkspaceManager::new(vec![]);
    let conflicts = detect_conflicts(&manager).await.unwrap();
    assert!(conflicts.is_empty());
}

#[tokio::test]
async fn test_detect_conflicts_with_conflicts() {
    let manager =
        MockWorkspaceManager::new(vec!["src/main.rs".to_string(), "src/lib.rs".to_string()]);
    let conflicts = detect_conflicts(&manager).await.unwrap();
    assert_eq!(conflicts.len(), 2);
    assert_eq!(conflicts[0], "src/main.rs");
    assert_eq!(conflicts[1], "src/lib.rs");
}

#[tokio::test]
async fn test_get_vcs_status() {
    let expected_status =
        "# On branch test\n# Changes not staged for commit:\n#   modified:   src/main.rs";
    let manager = MockWorkspaceManager::new(vec![]).with_status(expected_status.to_string());

    let status = get_vcs_status(&manager).await.unwrap();
    assert_eq!(status, expected_status);
}

#[tokio::test]
async fn test_get_vcs_log_for_revisions() {
    let expected_log = "commit def456\nAuthor: Developer\nDate: 2024-01-02\n\nUpdate feature";
    let manager = MockWorkspaceManager::new(vec![]).with_log(expected_log.to_string());

    let log = get_vcs_log_for_revisions(&manager, &["rev1".to_string(), "rev2".to_string()])
        .await
        .unwrap();
    assert_eq!(log, expected_log);
}

fn test_items() -> Vec<crate::parallel::resolve_state::SequentialMergeItem> {
    crate::parallel::resolve_state::SequentialMergeItem::batch(
        &["rev1".to_string()],
        &["change1".to_string()],
        &[PathBuf::from("/tmp/archive/change1")],
    )
    .expect("well-formed batch")
}

#[tokio::test]
async fn test_resolve_merges_with_retry_args_struct() {
    // Test that ResolveMergesWithRetryArgs can be constructed properly
    let manager = MockWorkspaceManager::new(vec![]);
    let config = crate::config::OrchestratorConfig::default();
    let items = test_items();
    let target_branch = "main";
    let base_revision = "base123";
    let max_retries = 3;

    let ai_runner = crate::ai_command_runner::AiCommandRunner::for_run(
        &config,
        std::sync::Arc::new(tokio::sync::Mutex::new(None)),
        crate::ai_command_runner::RunCommandScope::new(),
    );
    let auto_resolve_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let args = ResolveMergesWithRetryArgs {
        workspace_manager: &manager as &dyn WorkspaceManager,
        config: &config,
        event_tx: &None,
        items: &items,
        target_branch,
        base_revision,
        max_retries,
        ai_runner,
        auto_resolve_count,
        publication_owns_completion: false,
    };

    // Verify fields are accessible
    assert_eq!(args.target_branch, "main");
    assert_eq!(args.base_revision, "base123");
    assert_eq!(args.max_retries, 3);
    assert_eq!(args.items.len(), 1);
    assert_eq!(args.items[0].change_id, "change1");
    assert_eq!(
        args.items[0].archive_path,
        PathBuf::from("/tmp/archive/change1")
    );
}

#[test]
fn test_resolve_merges_with_retry_args_clone() {
    // Test that ResolveMergesWithRetryArgs implements Clone
    let manager = MockWorkspaceManager::new(vec![]);
    let config = crate::config::OrchestratorConfig::default();
    let items = test_items();

    let ai_runner = crate::ai_command_runner::AiCommandRunner::for_run(
        &config,
        std::sync::Arc::new(tokio::sync::Mutex::new(None)),
        crate::ai_command_runner::RunCommandScope::new(),
    );
    let auto_resolve_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let args1 = ResolveMergesWithRetryArgs {
        workspace_manager: &manager as &dyn WorkspaceManager,
        config: &config,
        event_tx: &None,
        items: &items,
        target_branch: "main",
        base_revision: "base123",
        max_retries: 3,
        ai_runner,
        auto_resolve_count,
        publication_owns_completion: false,
    };

    let args2 = args1.clone(); // Clone instead of Copy
    let _args3 = args1; // Can still use args1 because it's Clone

    assert_eq!(args2.target_branch, "main");
}

/// Capacity-recovery audit coverage for automatic conflict resolution.
///
/// Automatic resolve occupancy is accounted through an RAII guard, so the scheduler's
/// `calculate_available_slots` input must return to its pre-resolve value on every exit
/// path. If any path leaked the counter, queued work would stay permanently capacity
/// gated and would depend on a sticky re-analysis trigger to make progress.
async fn run_auto_resolve_and_report_counter(
    probe: ConflictProbe,
) -> (bool, usize, tempfile::TempDir) {
    let repo_dir = tempfile::TempDir::new().expect("create temp repo dir");
    let manager = MockWorkspaceManager::new(vec!["conflict.txt".to_string()])
        .with_repo_root(repo_dir.path().to_path_buf())
        .with_probe(probe);

    let config = crate::config::OrchestratorConfig {
        resolve_command: Some("echo resolve".to_string()),
        ..Default::default()
    };
    let auto_resolve_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));

    let result = resolve_conflicts_with_retry(
        &manager as &dyn WorkspaceManager,
        &config,
        &None,
        &["rev1".to_string()],
        &["change-a".to_string()],
        "merge conflict",
        1,
        crate::ai_command_runner::AiCommandRunner::for_run(
            &config,
            std::sync::Arc::new(tokio::sync::Mutex::new(None)),
            crate::ai_command_runner::RunCommandScope::new(),
        ),
        auto_resolve_count.clone(),
    )
    .await;

    let remaining = auto_resolve_count.load(std::sync::atomic::Ordering::SeqCst);
    (result.is_ok(), remaining, repo_dir)
}

#[tokio::test]
async fn auto_resolve_releases_capacity_on_success() {
    let (succeeded, remaining, _repo_dir) =
        run_auto_resolve_and_report_counter(ConflictProbe::ClearedAfterFirstCall).await;

    assert!(succeeded, "cleared conflicts should complete resolution");
    assert_eq!(
        remaining, 0,
        "successful automatic resolve must release its scheduler slot"
    );
}

#[tokio::test]
async fn auto_resolve_releases_capacity_on_failure() {
    let (succeeded, remaining, _repo_dir) =
        run_auto_resolve_and_report_counter(ConflictProbe::Static).await;

    assert!(
        !succeeded,
        "unresolved conflicts should exhaust retries and fail"
    );
    assert_eq!(
        remaining, 0,
        "failed automatic resolve must release its scheduler slot"
    );
}

#[tokio::test]
async fn auto_resolve_releases_capacity_on_early_return() {
    let (succeeded, remaining, _repo_dir) =
        run_auto_resolve_and_report_counter(ConflictProbe::AlwaysFails).await;

    assert!(
        !succeeded,
        "conflict detection failure should return early with an error"
    );
    assert_eq!(
        remaining, 0,
        "early-return automatic resolve must release its scheduler slot"
    );
}

// ---------------------------------------------------------------------------
// Sequential resolve batch classification
// ---------------------------------------------------------------------------

use crate::parallel::resolve_state::{self, BatchState, SequentialMergeItem};

// The classifier's own in-memory doubles are shared with its unit tests so both
// layers exercise the same evidence shape.
use crate::parallel::resolve_state::fixtures::{
    archived, item, live, presynced_repo, with_complete_tasks, FakeEvidence, FakeRepo,
};

#[tokio::test]
async fn absent_manager_entry_still_reports_the_supplied_worktree_path() {
    // The mock workspace manager returns an empty workspace list, exactly like
    // the reported failure. The supplied path must still reach the prompt.
    let repo = presynced_repo();
    let evidence = FakeEvidence::new(repo, "t").worktree("ws-a", "/wt/change-a", "a_tip");
    let items = vec![item("ws-a", "change-a", "/wt/change-a")];

    let rendered = super::super::conflict::render_worktree_locations(&evidence, &items).await;

    assert!(
        rendered.contains("/wt/change-a"),
        "supplied worktree path must be reported, got {}",
        rendered
    );
    assert!(
        !rendered.contains("(unknown)"),
        "process-local workspace absence must not degrade to '(unknown)', got {}",
        rendered
    );
}

#[tokio::test]
async fn unsafe_worktree_identity_blocks_every_action() {
    let evidence =
        FakeEvidence::new(presynced_repo(), "t").unsafe_worktree("ws-a", "detached HEAD");
    let items = vec![item("ws-a", "change-a", "/wt/change-a")];

    let state = resolve_state::classify_batch(&evidence, &items, "base").await;

    assert!(
        matches!(state, BatchState::UnsafeEvidence { .. }),
        "{:?}",
        state
    );
    assert!(!state.allows_agent_action());
    let rendered = super::super::conflict::render_worktree_locations(&evidence, &items).await;
    assert!(
        rendered.contains("unvalidated: detached HEAD"),
        "{}",
        rendered
    );
}

#[tokio::test]
async fn empty_batch_is_unsafe() {
    let evidence = FakeEvidence::new(presynced_repo(), "t");
    let state = resolve_state::classify_batch(&evidence, &[], "base").await;
    assert!(
        matches!(state, BatchState::UnsafeEvidence { .. }),
        "{:?}",
        state
    );
}

#[test]
fn malformed_batches_are_rejected_before_resolve() {
    assert!(SequentialMergeItem::batch(&[], &[], &[]).is_err());
    assert!(SequentialMergeItem::batch(
        &["rev1".to_string(), "rev2".to_string()],
        &["change1".to_string()],
        &[PathBuf::from("/a"), PathBuf::from("/b")],
    )
    .is_err());
    assert!(
        SequentialMergeItem::batch(&["rev1".to_string()], &["change1".to_string()], &[],).is_err()
    );
    assert!(SequentialMergeItem::batch(
        &["rev1".to_string()],
        &["".to_string()],
        &[PathBuf::from("/a")],
    )
    .is_err());

    let ordered = SequentialMergeItem::batch(
        &["rev1".to_string(), "rev2".to_string()],
        &["change1".to_string(), "change2".to_string()],
        &[PathBuf::from("/a"), PathBuf::from("/b")],
    )
    .expect("well-formed batch");
    assert_eq!(
        SequentialMergeItem::change_ids(&ordered),
        vec!["change1".to_string(), "change2".to_string()],
        "declared order must survive batch construction"
    );
}

#[tokio::test]
async fn target_state_on_first_parent_lineage_needs_no_presync() {
    let mut repo = FakeRepo::default();
    repo.commit("base", "Base", &[])
        .commit("a_tip", "Work on change-a", &["base"])
        .tree("a_tip", &[&archived("change-a")])
        .tree("base", &[]);
    with_complete_tasks(&mut repo, "a_tip", "change-a");
    let evidence = FakeEvidence::new(repo, "base").worktree("ws-a", "/wt/a", "a_tip");
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    let state = resolve_state::classify_batch(&evidence, &items, "base").await;

    assert!(
        matches!(state, BatchState::FinalMergeMissing { .. }),
        "target HEAD is already on the tip lineage, so classification proceeds to the final merge: {:?}",
        state
    );
}

#[tokio::test]
async fn valid_presync_merge_reaches_final_merge_missing() {
    let evidence = FakeEvidence::new(presynced_repo(), "t").worktree("ws-a", "/wt/a", "a_tip");
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    let state = resolve_state::classify_batch(&evidence, &items, "base").await;

    match state {
        BatchState::FinalMergeMissing {
            change_id,
            required_target_state,
            ..
        } => {
            assert_eq!(change_id, "change-a");
            assert_eq!(required_target_state, "t");
        }
        other => panic!("expected final merge missing, got {:?}", other),
    }
}

#[tokio::test]
async fn missing_duplicate_and_wrong_parent_presync_all_fail_closed() {
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    // Missing: branch never merged the advanced target.
    let mut missing = FakeRepo::default();
    missing
        .commit("base", "Base", &[])
        .commit("t", "Target advance", &["base"])
        .commit("a_tip", "Work on change-a", &["base"]);
    let state = resolve_state::classify_batch(
        &FakeEvidence::new(missing, "t").worktree("ws-a", "/wt/a", "a_tip"),
        &items,
        "base",
    )
    .await;
    assert!(
        matches!(state, BatchState::PreSyncInvalid { .. }),
        "{:?}",
        state
    );

    // Duplicate exact pre-sync subjects.
    let mut duplicated = FakeRepo::default();
    duplicated
        .commit("base", "Base", &[])
        .commit("t", "Target advance", &["base"])
        .commit("a1", "Work", &["base"])
        .commit("p1", "Pre-sync base into change-a", &["a1", "t"])
        .commit("a_tip", "Pre-sync base into change-a", &["p1", "t"]);
    let state = resolve_state::classify_batch(
        &FakeEvidence::new(duplicated, "t").worktree("ws-a", "/wt/a", "a_tip"),
        &items,
        "base",
    )
    .await;
    assert!(
        matches!(state, BatchState::PreSyncInvalid { .. }),
        "{:?}",
        state
    );

    // Wrong non-first parent: pre-synced an older target state.
    let mut wrong = FakeRepo::default();
    wrong
        .commit("base", "Base", &[])
        .commit("t_old", "Older target", &["base"])
        .commit("t", "Target advance", &["t_old"])
        .commit("a1", "Work", &["base"])
        .commit("a_tip", "Pre-sync base into change-a", &["a1", "t_old"]);
    let state = resolve_state::classify_batch(
        &FakeEvidence::new(wrong, "t").worktree("ws-a", "/wt/a", "a_tip"),
        &items,
        "base",
    )
    .await;
    match state {
        BatchState::PreSyncInvalid { reason, .. } => {
            assert!(reason.contains("non-first parent"), "{}", reason)
        }
        other => panic!("expected invalid pre-sync, got {:?}", other),
    }

    // Wrong parent count: a non-merge commit carrying the pre-sync subject.
    let mut single_parent = FakeRepo::default();
    single_parent
        .commit("base", "Base", &[])
        .commit("t", "Target advance", &["base"])
        .commit("a1", "Work", &["base"])
        .commit("a_tip", "Pre-sync base into change-a", &["a1"]);
    let state = resolve_state::classify_batch(
        &FakeEvidence::new(single_parent, "t").worktree("ws-a", "/wt/a", "a_tip"),
        &items,
        "base",
    )
    .await;
    match state {
        BatchState::PreSyncInvalid { reason, .. } => {
            assert!(reason.contains("parent(s)"), "{}", reason)
        }
        other => panic!("expected invalid pre-sync, got {:?}", other),
    }
}

#[tokio::test]
async fn unfinished_worktree_merge_and_conflicts_report_presync_unfinished() {
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    let evidence = FakeEvidence::new(presynced_repo(), "t")
        .worktree("ws-a", "/wt/a", "a_tip")
        .worktree_merging("/wt/a");
    assert!(
        matches!(
            resolve_state::classify_batch(&evidence, &items, "base").await,
            BatchState::PreSyncUnfinished { .. }
        ),
        "an unfinished worktree merge must be reported before any target guidance"
    );

    let evidence = FakeEvidence::new(presynced_repo(), "t")
        .worktree("ws-a", "/wt/a", "a_tip")
        .worktree_conflicted("/wt/a", &["src/lib.rs"]);
    assert!(matches!(
        resolve_state::classify_batch(&evidence, &items, "base").await,
        BatchState::PreSyncUnfinished { .. }
    ));
}

#[tokio::test]
async fn historical_ancestry_integration_is_exempt_from_presync_reconstruction() {
    // No exact final-subject candidate exists and the tip is already ancestral:
    // pre-sync topology cannot be reconstructed and is not required.
    let mut repo = FakeRepo::default();
    repo.commit("base", "Base", &[])
        .commit("a_tip", "Work on change-a", &["base"])
        .commit("head", "Unrelated follow-up", &["a_tip"])
        .tree("head", &[]);
    let evidence = FakeEvidence::new(repo, "head").worktree("ws-a", "/wt/a", "a_tip");
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    assert_eq!(
        resolve_state::classify_batch(&evidence, &items, "base").await,
        BatchState::Complete
    );
}

#[tokio::test]
async fn exact_final_merge_topology_is_required() {
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    // Valid: two parents, first parent `t`, non-first parent the branch tip.
    let mut valid = presynced_repo();
    valid
        .commit("merge", "Merge change: change-a", &["t", "a_tip"])
        .tree("merge", &[]);
    let evidence = FakeEvidence::new(valid, "merge").worktree("ws-a", "/wt/a", "a_tip");
    assert_eq!(
        resolve_state::classify_batch(&evidence, &items, "base").await,
        BatchState::Complete
    );

    // The expected revision is only on the first-parent side.
    let mut false_exact = presynced_repo();
    false_exact
        .commit("other", "Unrelated branch", &["base"])
        .commit("merge", "Merge change: change-a", &["a_tip", "other"])
        .tree("merge", &[]);
    let evidence = FakeEvidence::new(false_exact, "merge").worktree("ws-a", "/wt/a", "a_tip");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("non-first parent"), "{}", reason)
        }
        other => panic!("expected unsafe evidence, got {:?}", other),
    }

    // Wrong parent count.
    let mut wrong_count = presynced_repo();
    wrong_count
        .commit("merge", "Merge change: change-a", &["t"])
        .tree("merge", &[]);
    let evidence = FakeEvidence::new(wrong_count, "merge").worktree("ws-a", "/wt/a", "a_tip");
    assert!(matches!(
        resolve_state::classify_batch(&evidence, &items, "base").await,
        BatchState::UnsafeEvidence { .. }
    ));

    // Duplicate exact candidates.
    let mut duplicated = presynced_repo();
    duplicated
        .commit("merge1", "Merge change: change-a", &["t", "a_tip"])
        .commit("merge2", "Merge change: change-a", &["merge1", "a_tip"])
        .tree("merge2", &[]);
    let evidence = FakeEvidence::new(duplicated, "merge2").worktree("ws-a", "/wt/a", "a_tip");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("exactly one is required"), "{}", reason)
        }
        other => panic!("expected unsafe evidence, got {:?}", other),
    }
}

#[tokio::test]
async fn later_item_owns_target_merge_after_prior_completion() {
    let mut repo = FakeRepo::default();
    repo.commit("base", "Base", &[])
        .commit("a1", "Work a", &["base"])
        .commit("b1", "Work b", &["base"])
        .commit("merge_a", "Merge change: change-a", &["base", "a1"])
        .commit("b_tip", "Pre-sync base into change-b", &["b1", "merge_a"])
        .tree("merge_a", &[]);
    let evidence = FakeEvidence::new(repo, "merge_a")
        .worktree("ws-a", "/wt/a", "a1")
        .worktree("ws-b", "/wt/b", "b_tip")
        .merge_head("b_tip")
        .index(&[&live("change-b"), &archived("change-b")]);
    let items = vec![
        item("ws-a", "change-a", "/wt/a"),
        item("ws-b", "change-b", "/wt/b"),
    ];

    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::TargetMergeUnfinished {
            change_id,
            requires_live_removal,
            ..
        } => {
            assert_eq!(change_id, "change-b");
            assert!(
                requires_live_removal,
                "stage-0 index coexistence must predict resurrection before the final commit"
            );
        }
        other => panic!(
            "expected target merge unfinished for change-b, got {:?}",
            other
        ),
    }
}

#[tokio::test]
async fn conflict_stages_withhold_cleanup_guidance() {
    let mut repo = presynced_repo();
    repo.tree("t", &[]);
    let evidence = FakeEvidence::new(repo, "t")
        .worktree("ws-a", "/wt/a", "a_tip")
        .merge_head("a_tip")
        .conflicts(&["openspec/changes/change-a/proposal.md"])
        .index(&[&live("change-a"), &archived("change-a")]);
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::TargetMergeUnfinished {
            requires_live_removal,
            reason,
            ..
        } => {
            assert!(
                !requires_live_removal,
                "cleanup must not be authorized while conflict stages exist"
            );
            assert!(reason.contains("conflict stages"), "{}", reason);
        }
        other => panic!("expected target merge unfinished, got {:?}", other),
    }
}

#[tokio::test]
async fn target_merge_owner_must_be_unique_and_first_incomplete() {
    let items = vec![
        item("ws-a", "change-a", "/wt/a"),
        item("ws-b", "change-b", "/wt/b"),
    ];

    let mut repo = FakeRepo::default();
    repo.commit("base", "Base", &[])
        .commit("a1", "Work a", &["base"])
        .commit("b1", "Work b", &["base"])
        .tree("base", &[]);

    // Unknown owner: MERGE_HEAD matches no batch tip.
    let evidence = FakeEvidence::new(repo.clone(), "base")
        .worktree("ws-a", "/wt/a", "a1")
        .worktree("ws-b", "/wt/b", "b1")
        .merge_head("stranger");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("does not match"), "{}", reason)
        }
        other => panic!("expected unsafe evidence, got {:?}", other),
    }

    // Ambiguous owner: two items report the same tip.
    let evidence = FakeEvidence::new(repo.clone(), "base")
        .worktree("ws-a", "/wt/a", "a1")
        .worktree("ws-b", "/wt/b", "a1")
        .merge_head("a1");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("matches 2"), "{}", reason)
        }
        other => panic!("expected unsafe evidence, got {:?}", other),
    }

    // Owner is not the first incomplete item.
    let evidence = FakeEvidence::new(repo.clone(), "base")
        .worktree("ws-a", "/wt/a", "a1")
        .worktree("ws-b", "/wt/b", "b1")
        .merge_head("b1");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("first incomplete"), "{}", reason)
        }
        other => panic!("expected unsafe evidence, got {:?}", other),
    }
}

#[tokio::test]
async fn out_of_order_integration_fails_closed() {
    let mut repo = FakeRepo::default();
    repo.commit("base", "Base", &[])
        .commit("a1", "Work a", &["base"])
        .commit("b1", "Work b", &["base"])
        .commit("merge_b", "Merge change: change-b", &["base", "b1"])
        .tree("merge_b", &[]);
    let evidence = FakeEvidence::new(repo, "merge_b")
        .worktree("ws-a", "/wt/a", "a1")
        .worktree("ws-b", "/wt/b", "b1");
    let items = vec![
        item("ws-a", "change-a", "/wt/a"),
        item("ws-b", "change-b", "/wt/b"),
    ];

    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("declared order"), "{}", reason)
        }
        other => panic!("expected unsafe evidence, got {:?}", other),
    }
}

#[tokio::test]
async fn multi_change_clean_completion() {
    let mut repo = FakeRepo::default();
    repo.commit("base", "Base", &[])
        .commit("a1", "Work a", &["base"])
        .commit("b1", "Work b", &["base"])
        .commit("merge_a", "Merge change: change-a", &["base", "a1"])
        .commit("b_tip", "Pre-sync base into change-b", &["b1", "merge_a"])
        .commit("merge_b", "Merge change: change-b", &["merge_a", "b_tip"])
        .tree("merge_b", &[&archived("change-a"), &archived("change-b")]);
    let evidence = FakeEvidence::new(repo, "merge_b")
        .worktree("ws-a", "/wt/a", "a1")
        .worktree("ws-b", "/wt/b", "b_tip");
    let items = vec![
        item("ws-a", "change-a", "/wt/a"),
        item("ws-b", "change-b", "/wt/b"),
    ];

    assert_eq!(
        resolve_state::classify_batch(&evidence, &items, "base").await,
        BatchState::Complete
    );
}

#[tokio::test]
async fn committed_live_and_archive_coexistence_requires_forward_cleanup() {
    let mut repo = presynced_repo();
    repo.commit("merge", "Merge change: change-a", &["t", "a_tip"])
        .tree("merge", &[&live("change-a"), &archived("change-a")]);
    let evidence = FakeEvidence::new(repo, "merge").worktree("ws-a", "/wt/a", "a_tip");
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    let state = resolve_state::classify_batch(&evidence, &items, "base").await;
    match &state {
        BatchState::ResurrectionCleanupRequired { change_id, .. } => {
            assert_eq!(change_id, "change-a")
        }
        other => panic!("expected resurrection cleanup, got {:?}", other),
    }
    assert!(
        state
            .diagnosis()
            .contains("Cleanup resurrected change: change-a"),
        "guidance must name the exact forward cleanup subject: {}",
        state.diagnosis()
    );
}

#[tokio::test]
async fn staged_only_cleanup_remains_incomplete() {
    // The live directory is removed from the index and worktree but the commit
    // still contains it: committed evidence, not staged intent, decides.
    let mut repo = presynced_repo();
    repo.commit("merge", "Merge change: change-a", &["t", "a_tip"])
        .tree("merge", &[&live("change-a"), &archived("change-a")]);
    let evidence = FakeEvidence::new(repo, "merge")
        .worktree("ws-a", "/wt/a", "a_tip")
        .dirty();
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    assert!(matches!(
        resolve_state::classify_batch(&evidence, &items, "base").await,
        BatchState::ResurrectionCleanupRequired { .. }
    ));
}

#[tokio::test]
async fn valid_forward_cleanup_commit_completes_the_batch() {
    let mut repo = presynced_repo();
    repo.commit("merge", "Merge change: change-a", &["t", "a_tip"])
        .commit(
            "cleanup",
            "Cleanup resurrected change: change-a",
            &["merge"],
        )
        .diff("cleanup", &[('D', &live("change-a"))])
        .tree("merge", &[&live("change-a"), &archived("change-a")])
        .tree("cleanup", &[&archived("change-a")]);
    let evidence = FakeEvidence::new(repo, "cleanup").worktree("ws-a", "/wt/a", "a_tip");
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    assert_eq!(
        resolve_state::classify_batch(&evidence, &items, "base").await,
        BatchState::Complete
    );
}

#[tokio::test]
async fn invalid_cleanup_commits_fail_closed() {
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    // Touches archive content as well as the live subtree.
    let mut unrelated = presynced_repo();
    unrelated
        .commit("merge", "Merge change: change-a", &["t", "a_tip"])
        .commit(
            "cleanup",
            "Cleanup resurrected change: change-a",
            &["merge"],
        )
        .diff(
            "cleanup",
            &[('D', &live("change-a")), ('M', &archived("change-a"))],
        )
        .tree("cleanup", &[&archived("change-a")]);
    let evidence = FakeEvidence::new(unrelated, "cleanup").worktree("ws-a", "/wt/a", "a_tip");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("may only delete"), "{}", reason)
        }
        other => panic!("expected unsafe evidence, got {:?}", other),
    }

    // Merge-shaped (two-parent) cleanup commit.
    let mut merged_cleanup = presynced_repo();
    merged_cleanup
        .commit("merge", "Merge change: change-a", &["t", "a_tip"])
        .commit(
            "cleanup",
            "Cleanup resurrected change: change-a",
            &["merge", "a_tip"],
        )
        .diff("cleanup", &[('D', &live("change-a"))])
        .tree("cleanup", &[&archived("change-a")]);
    let evidence = FakeEvidence::new(merged_cleanup, "cleanup").worktree("ws-a", "/wt/a", "a_tip");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("exactly one"), "{}", reason)
        }
        other => panic!("expected unsafe evidence, got {:?}", other),
    }
}

#[tokio::test]
async fn cleanup_must_be_a_forward_commit_on_the_target_lineage() {
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    // Reachable but not on the target's own forward history: the cleanup was
    // authored on a side branch and merged back, so the target never moved
    // forward past the resurrection.
    let mut side_branch = presynced_repo();
    side_branch
        .commit("merge", "Merge change: change-a", &["t", "a_tip"])
        .commit(
            "cleanup",
            "Cleanup resurrected change: change-a",
            &["merge"],
        )
        .commit("head", "Merge side cleanup", &["merge", "cleanup"])
        .diff("cleanup", &[('D', &live("change-a"))])
        .tree("merge", &[&live("change-a"), &archived("change-a")])
        .tree("cleanup", &[&archived("change-a")])
        .tree("head", &[&archived("change-a")]);
    let evidence = FakeEvidence::new(side_branch, "head").worktree("ws-a", "/wt/a", "a_tip");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("first-parent lineage"), "{}", reason)
        }
        other => panic!("expected unsafe evidence, got {:?}", other),
    }

    // Wrong predecessor: the cleanup is on the target lineage but its parent
    // predates the commit that integrated the change, so it cannot be the
    // cleanup of that integration.
    let mut before_integration = FakeRepo::default();
    before_integration
        .commit("base", "Base", &[])
        .commit("t", "Target advance", &["base"])
        .commit("a_tip", "Work on change-a", &["base"])
        .commit("cleanup", "Cleanup resurrected change: change-a", &["t"])
        .commit("head", "Merge branch ws-a", &["cleanup", "a_tip"])
        .diff("cleanup", &[('D', &live("change-a"))])
        .tree("a_tip", &[&archived("change-a")])
        .tree("cleanup", &[&archived("change-a")])
        .tree("head", &[&archived("change-a")]);
    let evidence = FakeEvidence::new(before_integration, "head").worktree("ws-a", "/wt/a", "a_tip");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => assert!(
            reason.contains("does not contain its committed integration"),
            "{}",
            reason
        ),
        other => panic!("expected unsafe evidence, got {:?}", other),
    }

    // Wrong predecessor: on the lineage and after integration, but the parent
    // state never held the live/archive coexistence the commit claims to remove.
    let mut wrong_predecessor = presynced_repo();
    wrong_predecessor
        .commit("merge", "Merge change: change-a", &["t", "a_tip"])
        .commit("filler", "Unrelated follow-up", &["merge"])
        .commit(
            "cleanup",
            "Cleanup resurrected change: change-a",
            &["filler"],
        )
        .diff("cleanup", &[('D', &live("change-a"))])
        .tree("merge", &[&live("change-a"), &archived("change-a")])
        .tree("filler", &[&archived("change-a")])
        .tree("cleanup", &[&archived("change-a")]);
    let evidence =
        FakeEvidence::new(wrong_predecessor, "cleanup").worktree("ws-a", "/wt/a", "a_tip");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => assert!(
            reason.contains("does not hold the live/archive coexistence"),
            "{}",
            reason
        ),
        other => panic!("expected unsafe evidence, got {:?}", other),
    }

    // The same shape, cleaned up directly on top of the integration it repairs.
    let mut forward = presynced_repo();
    forward
        .commit("merge", "Merge change: change-a", &["t", "a_tip"])
        .commit(
            "cleanup",
            "Cleanup resurrected change: change-a",
            &["merge"],
        )
        .diff("cleanup", &[('D', &live("change-a"))])
        .tree("merge", &[&live("change-a"), &archived("change-a")])
        .tree("cleanup", &[&archived("change-a")]);
    let evidence = FakeEvidence::new(forward, "cleanup").worktree("ws-a", "/wt/a", "a_tip");
    assert_eq!(
        resolve_state::classify_batch(&evidence, &items, "base").await,
        BatchState::Complete,
        "a direct forward cleanup on the target lineage is the accepted shape"
    );
}

#[tokio::test]
async fn declared_order_is_verified_when_every_item_is_integrated() {
    let items = vec![
        item("ws-a", "change-a", "/wt/a"),
        item("ws-b", "change-b", "/wt/b"),
    ];

    // Both items have an exact integration commit, so no `NotIntegrated` hole
    // exists — but the target history integrated B before A.
    let mut reversed = FakeRepo::default();
    reversed
        .commit("base", "Base", &[])
        .commit("a1", "Work a", &["base"])
        .commit("b1", "Work b", &["base"])
        .commit("merge_b", "Merge change: change-b", &["base", "b1"])
        .commit("merge_a", "Merge change: change-a", &["merge_b", "a1"])
        .tree("merge_a", &[&archived("change-a"), &archived("change-b")]);
    let evidence = FakeEvidence::new(reversed, "merge_a")
        .worktree("ws-a", "/wt/a", "a1")
        .worktree("ws-b", "/wt/b", "b1");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("declared order"), "{}", reason)
        }
        other => panic!("expected unsafe evidence, got {:?}", other),
    }

    // The same two integrations in declared order are complete.
    let mut ordered = FakeRepo::default();
    ordered
        .commit("base", "Base", &[])
        .commit("a1", "Work a", &["base"])
        .commit("b1", "Work b", &["base"])
        .commit("merge_a", "Merge change: change-a", &["base", "a1"])
        .commit("b_tip", "Pre-sync base into change-b", &["b1", "merge_a"])
        .commit("merge_b", "Merge change: change-b", &["merge_a", "b_tip"])
        .tree("merge_b", &[&archived("change-a"), &archived("change-b")]);
    let evidence = FakeEvidence::new(ordered, "merge_b")
        .worktree("ws-a", "/wt/a", "a1")
        .worktree("ws-b", "/wt/b", "b_tip");
    assert_eq!(
        resolve_state::classify_batch(&evidence, &items, "base").await,
        BatchState::Complete
    );
}

#[tokio::test]
async fn prefinal_archive_evidence_comes_from_the_validated_worktree_head() {
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    // Worktree-only archive evidence: the target has never seen the archive, so
    // only the validated branch tip can prove it. The final merge is authorized.
    let mut worktree_only = presynced_repo();
    worktree_only
        .tree("t", &[&live("change-a")])
        .tree("a_tip", &[&archived("change-a")]);
    with_complete_tasks(&mut worktree_only, "a_tip", "change-a");
    let evidence = FakeEvidence::new(worktree_only, "t").worktree("ws-a", "/wt/a", "a_tip");
    assert!(
        matches!(
            resolve_state::classify_batch(&evidence, &items, "base").await,
            BatchState::FinalMergeMissing { .. }
        ),
        "an archive committed only on the branch tip must still authorize the final merge"
    );

    // Missing archive identity: the branch tip never archived the change.
    let mut unarchived = presynced_repo();
    unarchived.tree("a_tip", &[&live("change-a")]);
    let evidence = FakeEvidence::new(unarchived, "t").worktree("ws-a", "/wt/a", "a_tip");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("no valid archive proposal"), "{}", reason)
        }
        other => panic!("expected unsafe evidence, got {:?}", other),
    }

    // Nested layout: reported distinctly because it is repairable.
    let mut nested = presynced_repo();
    nested.tree(
        "a_tip",
        &["openspec/changes/archive/2026-08-03/change-a/proposal.md"],
    );
    let evidence = FakeEvidence::new(nested, "t").worktree("ws-a", "/wt/a", "a_tip");
    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("invalid nested layout"), "{}", reason)
        }
        other => panic!("expected unsafe evidence, got {:?}", other),
    }

    // Suffix collision and a non-proposal entry are not archive identities.
    for archive_like in [
        "openspec/changes/archive/prefix-change-a/proposal.md",
        "openspec/changes/archive/change-a/design.md",
    ] {
        let mut repo = presynced_repo();
        repo.tree("a_tip", &[archive_like]);
        let evidence = FakeEvidence::new(repo, "t").worktree("ws-a", "/wt/a", "a_tip");
        match resolve_state::classify_batch(&evidence, &items, "base").await {
            BatchState::UnsafeEvidence { reason } => assert!(
                reason.contains("no valid archive proposal"),
                "'{}' must not authorize the final merge: {}",
                archive_like,
                reason
            ),
            other => panic!(
                "'{}' must not authorize the final merge, got {:?}",
                archive_like, other
            ),
        }
    }
}

#[tokio::test]
async fn invalid_archive_shapes_never_authorize_deletion() {
    // Post-final: nested date layout, a suffix-similar entry, and a non-proposal
    // entry are all invalid archive identities, so committed live/archive
    // coexistence is never claimed and deletion is never authorized.
    for archive_like in [
        "openspec/changes/archive/2026-08-03/change-a/proposal.md",
        "openspec/changes/archive/prefix-change-a/proposal.md",
        "openspec/changes/archive/change-a/design.md",
    ] {
        let mut repo = presynced_repo();
        repo.commit("merge", "Merge change: change-a", &["t", "a_tip"])
            .tree("merge", &[&live("change-a"), archive_like]);
        let evidence = FakeEvidence::new(repo, "merge").worktree("ws-a", "/wt/a", "a_tip");
        let items = vec![item("ws-a", "change-a", "/wt/a")];

        let state = resolve_state::classify_batch(&evidence, &items, "base").await;
        assert!(
            !matches!(state, BatchState::ResurrectionCleanupRequired { .. }),
            "'{}' must not be treated as a valid archive identity, got {:?}",
            archive_like,
            state
        );
    }
}

#[tokio::test]
async fn dirty_target_is_never_complete() {
    let mut repo = presynced_repo();
    repo.commit("merge", "Merge change: change-a", &["t", "a_tip"])
        .tree("merge", &[&archived("change-a")]);
    let evidence = FakeEvidence::new(repo, "merge")
        .worktree("ws-a", "/wt/a", "a_tip")
        .dirty();
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    match resolve_state::classify_batch(&evidence, &items, "base").await {
        BatchState::UnsafeEvidence { reason } => {
            assert!(reason.contains("not clean"), "{}", reason)
        }
        other => panic!("expected incomplete batch, got {:?}", other),
    }
}

#[tokio::test]
async fn final_integration_verifier_matches_retry_classification() {
    let items = vec![item("ws-a", "change-a", "/wt/a")];

    // No candidate and not ancestral: verification must report the change missing.
    let mut missing = presynced_repo();
    missing.tree("t", &[]);
    let evidence = FakeEvidence::new(missing, "t").worktree("ws-a", "/wt/a", "a_tip");
    let error = resolve_state::verify_final_integration(&evidence, &items, "base")
        .await
        .expect_err("unintegrated change must fail verification");
    assert!(error.contains("change-a"), "{}", error);

    // No candidate but already ancestral: historical success.
    let mut historical = FakeRepo::default();
    historical
        .commit("base", "Base", &[])
        .commit("a_tip", "Work", &["base"])
        .commit("head", "Follow-up", &["a_tip"]);
    let evidence = FakeEvidence::new(historical, "head").worktree("ws-a", "/wt/a", "a_tip");
    assert!(
        resolve_state::verify_final_integration(&evidence, &items, "base")
            .await
            .is_ok()
    );

    // An exact candidate with the wrong second parent must fail closed rather
    // than fall back to ancestry.
    let mut false_exact = presynced_repo();
    false_exact.commit("other", "Unrelated", &["base"]).commit(
        "merge",
        "Merge change: change-a",
        &["a_tip", "other"],
    );
    let evidence = FakeEvidence::new(false_exact, "merge").worktree("ws-a", "/wt/a", "a_tip");
    let error = resolve_state::verify_final_integration(&evidence, &items, "base")
        .await
        .expect_err("ancestry fallback must not rescue an invalid exact candidate");
    assert!(error.contains("non-first parent"), "{}", error);
}

// ---------------------------------------------------------------------------
// Full reported regression against a real repository
// ---------------------------------------------------------------------------

use crate::parallel::resolve_state::GitResolveEvidence;

async fn git(dir: &Path, args: &[&str]) -> String {
    let output = tokio::process::Command::new("git")
        .args(args)
        .current_dir(dir)
        .output()
        .await
        .unwrap_or_else(|e| panic!("git {:?}: {}", args, e));
    assert!(
        output.status.success(),
        "git {:?} failed: {}",
        args,
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8_lossy(&output.stdout).trim().to_string()
}

async fn write_and_commit(dir: &Path, path: &str, contents: &str, subject: &str) {
    let full = dir.join(path);
    std::fs::create_dir_all(full.parent().unwrap()).unwrap();
    std::fs::write(full, contents).unwrap();
    git(dir, &["add", "-A"]).await;
    git(dir, &["commit", "-m", subject]).await;
}

/// The reported failure end to end, against a real Git repository.
///
/// The archive worktree path is supplied by merge admission and is deliberately
/// never registered with a workspace manager, reproducing the process-local
/// list that omitted it. Each phase is driven forward exactly as the resolve
/// agent would, and classification must track it without a generic
/// "missing merge commits" fallback.
#[tokio::test]
#[cfg_attr(not(feature = "heavy-tests"), ignore)]
async fn sequential_resolve_tracks_the_full_reported_regression() {
    let repo = tempfile::TempDir::new().expect("repo tempdir");
    let root = repo.path();
    git(root, &["init", "-b", "main"]).await;
    git(root, &["config", "user.email", "test@example.com"]).await;
    git(root, &["config", "user.name", "Test User"]).await;
    git(root, &["config", "commit.gpgsign", "false"]).await;
    write_and_commit(root, "README.md", "base\n", "Base").await;
    let base_revision = git(root, &["rev-parse", "HEAD"]).await;

    // The archived change worktree: the change is archived on its branch.
    let worktree = repo.path().parent().unwrap().join(format!(
        "{}-ws",
        root.file_name().unwrap().to_string_lossy()
    ));
    git(
        root,
        &[
            "worktree",
            "add",
            "-b",
            "ws-change-a",
            worktree.to_str().unwrap(),
            "HEAD",
        ],
    )
    .await;
    write_and_commit(
        &worktree,
        "openspec/changes/archive/2026-08-03-change-a/proposal.md",
        "archived\n",
        "Archive change-a",
    )
    .await;

    // The target branch advances independently, so pre-sync becomes required.
    write_and_commit(root, "main.txt", "advanced\n", "Target advance").await;
    // The live change directory is present on the target and must not survive.
    write_and_commit(
        root,
        "openspec/changes/change-a/proposal.md",
        "live\n",
        "Add live change-a",
    )
    .await;

    let items = vec![item("ws-change-a", "change-a", worktree.to_str().unwrap())];
    let evidence = GitResolveEvidence::new(root);

    // Phase 1: the supplied path is validated and pre-sync is required.
    let state = resolve_state::classify_batch(&evidence, &items, &base_revision).await;
    match &state {
        BatchState::PreSyncInvalid {
            worktree: reported,
            required_target_state,
            ..
        } => {
            assert_eq!(
                reported.canonicalize().unwrap(),
                worktree.canonicalize().unwrap(),
                "the supplied archive worktree path must be validated and reported"
            );
            assert_eq!(
                required_target_state,
                &git(root, &["rev-parse", "HEAD"]).await
            );
        }
        other => panic!("expected pre-sync to be required, got {:?}", other),
    }
    assert!(
        !state.diagnosis().contains("Missing merge commits"),
        "the generic fallback must be gone: {}",
        state.diagnosis()
    );

    // Phase 2: the agent pre-syncs in the validated worktree.
    git(
        &worktree,
        &[
            "merge",
            "--no-ff",
            "-m",
            "Pre-sync base into change-a",
            "main",
        ],
    )
    .await;
    let state = resolve_state::classify_batch(&evidence, &items, &base_revision).await;
    assert!(
        matches!(state, BatchState::FinalMergeMissing { .. }),
        "valid pre-sync must unblock the final merge, got {:?}",
        state
    );

    // Phase 3: the final merge is started but not committed, and it resurrects
    // the live change directory alongside the valid archive.
    let merge = tokio::process::Command::new("git")
        .args(["merge", "--no-ff", "--no-commit", "ws-change-a"])
        .current_dir(root)
        .output()
        .await
        .expect("git merge");
    assert!(
        merge.status.success() || merge.status.code() == Some(1),
        "merge should either succeed or stop for commit"
    );
    let head_before_classification = git(root, &["rev-parse", "HEAD"]).await;
    let state = resolve_state::classify_batch(&evidence, &items, &base_revision).await;
    match &state {
        BatchState::TargetMergeUnfinished {
            change_id,
            requires_live_removal,
            ..
        } => {
            assert_eq!(change_id, "change-a");
            assert!(
                requires_live_removal,
                "stage-0 index coexistence must be reported before the final commit"
            );
        }
        other => panic!("expected an unfinished target merge, got {:?}", other),
    }
    // The old conflict-free shortcut committed here. Classification is
    // side-effect free and hands the work back to the agent instead.
    assert_eq!(
        git(root, &["rev-parse", "HEAD"]).await,
        head_before_classification,
        "a conflict-free MERGE_HEAD must not be committed by classification"
    );
    assert!(
        state.diagnosis().contains("Merge change: change-a")
            && !state.diagnosis().contains("Merge changes:"),
        "guidance must name the exact per-change subject, never a combined one: {}",
        state.diagnosis()
    );

    // Phase 4: committing without removing the live directory is not success.
    git(root, &["commit", "-m", "Merge change: change-a"]).await;
    assert!(
        matches!(
            resolve_state::classify_batch(&evidence, &items, &base_revision).await,
            BatchState::ResurrectionCleanupRequired { .. }
        ),
        "committed live/archive coexistence must require forward cleanup"
    );

    // Phase 5: staged-only removal is still not cleanup.
    git(root, &["rm", "-r", "-f", "openspec/changes/change-a"]).await;
    assert!(
        matches!(
            resolve_state::classify_batch(&evidence, &items, &base_revision).await,
            BatchState::ResurrectionCleanupRequired { .. }
        ),
        "staged-only removal must not be accepted as complete"
    );

    // Phase 6: the forward cleanup commit completes the batch.
    git(
        root,
        &["commit", "-m", "Cleanup resurrected change: change-a"],
    )
    .await;
    assert_eq!(
        resolve_state::classify_batch(&evidence, &items, &base_revision).await,
        BatchState::Complete
    );
    resolve_state::verify_final_integration(&evidence, &items, &base_revision)
        .await
        .expect("terminal verification must agree with the retry classifier");

    // Phase 7: untracked dirt in the target keeps the batch incomplete.
    std::fs::write(root.join("stray.txt"), "stray\n").unwrap();
    assert!(
        matches!(
            resolve_state::classify_batch(&evidence, &items, &base_revision).await,
            BatchState::UnsafeEvidence { .. }
        ),
        "a dirty target must never read as complete"
    );

    git(
        root,
        &["worktree", "remove", worktree.to_str().unwrap(), "--force"],
    )
    .await;
}